<template>
  <SmartTable
    ref="smartTableRef"
    v-model:columns="getColumnsByReportType"
    v-model:page-no="pageNo"
    v-model:page-size="pageSize"
    v-model:form-data="searchFormData"
    :data="inspectionCommentsList"
    :total="total"
    :buttons="buttons"
    @on-page-no-change="() => getAuditListByReportType()"
    @on-page-size-change="() => getAuditListByReportType()"
    @on-reset="
      () => {
        filterStatus = '100'
        handleStatusFilter()
      }
    "
    @on-search="() => getAuditListByReportType()"
    @refresh="() => getAuditListByReportType()"
  >
    <template #toolbarRowExtra>
      <el-radio-group
        v-model="filterStatus"
        @change="handleStatusFilter"
        style="margin-bottom: 15px"
      >
        <el-radio-button label="全部" value="all" />
        <el-radio-button label="已通过" value="200" />
        <el-radio-button label="审核中" value="100" />
        <el-radio-button label="已拒绝" value="300" />
        <!--        <el-radio-button label="已作废" value="400" />-->
      </el-radio-group>
    </template>
  </SmartTable>
  <AuditCheckRecord
    v-if="showAuditCheckRecord"
    v-model:visible="showAuditCheckRecord"
    :showRollbackStage="false"
    :reportUrl="operationItem.reportUrl"
    :auditId="operationItem.reportId"
    :apiParams="auditApiParams"
    :rejectFn="rejectOpinionNoticeApproval"
    :passFn="passOpinionNoticeApproval"
    :pageType="pageType"
    :recordFn="getOpinionNoticeApprovalRecordList"
    :reportType="getReportType"
    :id="operationItem.id"
    :templateId="templateId"
    :manualUrl="manualUrl"
    :useType="useType"
    :rowInfo="rowInfo"
    @close="handleCloseAuditDetail"
    @update="() => getAuditListByReportType()"
  />
</template>
<script setup lang="tsx">
import AuditCheckRecord from './AuditCheckRecord.vue'
import SmartTable from '@/components/SmartTable/SmartTable'
import dayjs from 'dayjs'
import { useDictStore } from '@/store/modules/dict'
import {
  PressureTaskOrderStatusMap,
  PressureTaskOrderStatus,
  PressureReportType
} from '@/utils/constants'
import { useRoute } from 'vue-router'
import _, { get } from 'lodash'
import { SmartInstanceExpose, SmartTableColumn } from '@/types/table'
import { buildFileUrl } from '@/utils'
import { PipeTaskOrderApi } from '@/api/pressure2/pipetaskorder'
const route = useRoute()

const {
  getOpinionNoticeApproval,
  passOpinionNoticeApproval,
  rejectOpinionNoticeApproval,
  getOpinionNoticeApprovalRecordList // 没有分页
} = PipeTaskOrderApi

const useType = 'checkNotice'
const dictStore = useDictStore()
const auditText = ref('审核')
const getReportType = computed(() => {
  switch (route.name) {
    case 'WorkInstructionAuditPipe':
      auditText.value = '批准'
      return PressureReportType['WORKINSTRUCTION']
    case 'InspectionPlanAuditPipe':
      auditText.value = '审批'
      return PressureReportType['INSPECTIONPLAN']
    case 'MajorIssueCluesNoticePipe':
      // 重大问题线索通知
      return PressureReportType['MAINQUESTION']
    case 'AuditInspectionCommentsNoticePipe':
      // 检验意见通知书
      return PressureReportType['SUGGUESTION']
  }
})

// 检验性质  pressure_inspection_nature
const getPressureInspectionNature = computed(
  () => dictStore.getDictMap['pressure_inspection_nature_pipe']
)
const columns = ref<SmartTableColumn[]>([
  {
    label: '任务单号',
    prop: 'orderNo',
    search: {
      type: 'input'
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    }
  },
  {
    label: '工程号',
    prop: 'projectNo',
    width: 200,
    search: {
      type: 'input'
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render(row, value) {
      return (
        <div style="text-align:center">
          <div>{value}</div>
          {row.productNo && (
            <div class="mt-8px">
              <el-tag type="success">{row.productNo}</el-tag>
            </div>
          )}{' '}
        </div>
      )
    }
  },
  {
    label: '出厂编号',
    width: 120,
    prop: 'productNo',
    hidden: true,
    search: {
      type: 'input'
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    }
  },
  {
    label: '使用单位',
    prop: 'unitName',
    search: {
      type: 'input'
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    }
  },
  {
    label: '检验性质',
    prop: 'checkType',
    search: {
      type: 'select',
      options: getPressureInspectionNature.value
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render: (row, checkType) =>
      getPressureInspectionNature.value.find((x) => x.value == checkType)?.label || '-'
  },
  {
    label: '检验项目',
    prop: 'reportName',
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    }
  },
  {
    label: '检验时间',
    prop: 'checkDate',
    search: {
      type: 'daterange'
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render: (row, checkDate) => (!checkDate ? '-' : (checkDate || []).join('-'))
  },
  {
    label: '状态',
    prop: 'status',
    // search: {
    //   type: 'select',
    //   options: Object.entries(PressureTaskOrderStatusMap).map(([value, label]) => ({value, label}))
    // },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render: (row, status) => (!status ? '-' : PressureTaskOrderStatusMap[status])
  },
  {
    label: '当前流程',
    prop: 'currentNode',
    fieldProps: {
      showOverflowTooltip: true,
      headerAlign: 'center'
    },
    render: (row) => {
      switch (row.status) {
        case PressureTaskOrderStatus['CANCELLED']:
          return '-'
        case PressureTaskOrderStatus['APPROVED']:
          return '审核通过'
        case PressureTaskOrderStatus['AUDITING']:
        case PressureTaskOrderStatus['REJECTED']:
          return (
            <div>
              <p>当前流程：{row?.currentNode || '-'}</p>
              <p>
                状态：
                {row.status === PressureTaskOrderStatus['AUDITING']
                  ? '审核中'
                  : `${row?.currentAuditor?.nickname}（${row?.currentAuditor?.employeeNo}）拒绝`}
              </p>
            </div>
          )
        default:
          return '-'
      }
    }
  },
  {
    label: '退回原因',
    prop: 'returnReason',
    fieldProps: {
      showOverflowTooltip: true,
      headerAlign: 'center'
    },
    render: (row, returnReason) => returnReason || '-'
  },
  {
    label: '审核人',
    prop: 'currentAuditor',
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    search: {
      type: 'selectUserModal',
      prop: 'bpmUserId'
    },
    render: (row, val) => {
      return !val ? '-' : val?.nickname
    }
  },
  {
    label: '审批人',
    prop: 'ratifyUser',
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    // search: {
    //   type: 'selectUserModal',
    //   prop: 'bpmUserId'
    // },
    render: (row, val) => {
      return !val ? '-' : val?.nickname
    }
  },
  {
    label: '提交人',
    prop: 'submitUser',
    search: {
      type: 'input'
    },
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render: (row, submitUser) => {
      return !submitUser ? '-' : submitUser?.nickname
    }
  },
  {
    label: '提交时间',
    prop: 'submitTime',
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render: (row, submitTime) =>
      !submitTime ? '-' : dayjs(submitTime).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    label: '操作',
    prop: 'operation',
    fieldProps: {
      showOverflowTooltip: true,
      align: 'center'
    },
    render: (row) => {
      return (
        <div>
          {PressureTaskOrderStatus['AUDITING'] == row.status && (
            <el-button
              link
              type="primary"
              onClick={() => handleOpenAuditDetailOrInfo(row, 'check')}
            >
              {row.currentNode == '部长审批'?'审批':auditText.value}
            </el-button>
          )}
          {PressureTaskOrderStatus['AUDITING'] !== row.status && (
            <el-button
              link
              type="primary"
              onClick={() => handleOpenAuditDetailOrInfo(row, 'detail')}
            >
              详情
            </el-button>
          )}
        </div>
      )
    }
  }
])
const getColumnsByReportType = computed(() => {
  switch (getReportType.value) {
    case PressureReportType['SUGGUESTION']:
      return columns.value.filter((col) => col.prop !== 'bpmUserId') as SmartTableColumn[]
    case PressureReportType['WORKINSTRUCTION']:
    case PressureReportType['MAINQUESTION']:
      // const columnsTitle = [ '任务单号', '检验时间', '状态', '当前流程', '退回原因', '提交人', '审核人', '提交时间', '操作' ]
      // return columns.value.filter((col) => columnsTitle.includes(col.label)) as SmartTableColumn[]
      const columnsProp = [
        'orderNo',
        'checkDate',
        'status',
        'currentNode',
        'returnReason',
        'submitUser',
        'currentAuditor',
        'submitTime',
        'operation'
      ]
      return columns.value.filter((col) =>
        columnsProp.includes(col.prop as string)
      ) as SmartTableColumn[]
    case PressureReportType['INSPECTIONPLAN']:
      const columnsPropIns = [
        'orderNo',
        'checkDate',
        'status',
        'currentNode',
        'returnReason',
        'submitUser',
        'currentAuditor',
        'ratifyUser',
        'submitTime',
        'operation'
      ]
      return columns.value.filter((col) =>
        columnsPropIns.includes(col.prop as string)
      ) as SmartTableColumn[]
    default:
      return [] as SmartTableColumn[]
  }
})
const buttons = ref([])
const pageNo = ref(1)
const pageSize = ref(10)
const total = ref(0)
const inspectionCommentsList = ref([])
const searchFormData = ref<any>({
  status: '100' // 默认状态为审核中
})

// 状态筛选
const filterStatus = ref('100') // 默认选中审核中
// 获取检验意见通知书审核列表
const fetchInspectionCommentsAuditList = async () => {
  inspectionCommentsList.value = []
  // TODO: 在这里获取审核列表数据
  const params = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    reportType: getReportType.value,
    ...searchFormData.value,
    status: filterStatus.value
  }
  if (params.status == 'all') delete params.status
  const response = await getOpinionNoticeApproval(params)
  inspectionCommentsList.value = response.list
  total.value = response.total
}

// 获取重大问题线索 & 检验方案 & 作业指导书的审核列表
const handleGetOperationReportAuditList = async (reportType) => {
  const params = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    reportType,
    ...searchFormData.value,
    status: filterStatus.value
  }
  if (params.status == 'all') delete params.status
  const auditListResult = await PipeTaskOrderApi.getMajorIssuesAuditList(params)
  // const auditListResult = await TaskOrderApi.getMajorIssuesAuditList(params)

  inspectionCommentsList.value = auditListResult.list
  total.value = auditListResult.total
}
const getAuditListByReportType = () => {
  switch (getReportType.value) {
    case PressureReportType['SUGGUESTION']:
      fetchInspectionCommentsAuditList()
      break
    case PressureReportType['WORKINSTRUCTION']:
    case PressureReportType['INSPECTIONPLAN']:
    case PressureReportType['MAINQUESTION']:
      handleGetOperationReportAuditList(getReportType.value)
      break
    default:
      return false
  }
}
// watch(
//   () => getReportType.value,
//   (reportType) => {
//     if (!reportType) return
//     getAuditListByReportType()
//   },
//   {
//     immediate: true
//   }
// )

// 审核 && 查看详情
const showAuditCheckRecord = ref(false)
const auditApiParams = ref({})
const operationItem = ref<any>({})
const rowInfo = ref<any>({})
const pageType = ref('check')
const templateId = ref('')
const manualUrl = ref('')
const handleOpenAuditDetailOrInfo = async (row, type) => {
  operationItem.value = row
  rowInfo.value = row
  pageType.value = type
  templateId.value = row.templateId
  manualUrl.value = row.manualUrl
  auditApiParams.value = {
    ids: [row.id],
    reportIds: [row.reportId],
    reportType: getReportType.value
  }
  /*switch (getReportType.value) {
    case PressureReportType['SUGGUESTION']:
      auditApiParams.value = {
        ids: [row.reportId]
      }
      break
    case PressureReportType['WORKINSTRUCTION']:
    case PressureReportType['INSPECTIONPLAN']:
    case PressureReportType['MAINQUESTION']:
      auditApiParams.value = {
        ids: [row.id],
        reportType: getReportType.value
      }
      let reportUrl = ''
      if(PressureReportType['MAINQUESTION'] == getReportType.value && row.signFilePdf){
        reportUrl = buildFileUrl(row.signFilePdf)
      } else {
        // 获取pdf文件流
        const response = await TaskOrderApi.getReportPreview({
          reportId: row.id,
          fileType: 200
        })
        // 文件流转成url
        if (response) {
          const flow = new Blob([response], { type: 'application/pdf' })
          reportUrl = window.URL.createObjectURL(flow)
        }
      }
      operationItem.value = { ...row, reportId: row.id, reportUrl }
      break
    default:
      return false
  }*/
  // 打开弹窗
  showAuditCheckRecord.value = true
}

// 处理状态筛选
const handleStatusFilter = () => {
  if (filterStatus.value === 'all') {
    // 清除状态筛选
    searchFormData.value.status = undefined
  } else {
    // 设置状态筛选
    searchFormData.value.status = filterStatus.value
  }
  // 重置页码并触发查询
  pageNo.value = 1
  getAuditListByReportType()
}

// 关闭审核详情回调
const handleCloseAuditDetail = () => {
  operationItem.value = false
  showAuditCheckRecord.value = false
}

const smartTableRef = ref<SmartInstanceExpose>()
onMounted(() => {
  const { bpmUserId } = route.query
  if (bpmUserId && PressureReportType['SUGGUESTION'] !== unref(getReportType)) {
    searchFormData.value.bpmUserId = bpmUserId
  }
  smartTableRef.value?.setSearchForm(searchFormData.value)
  getAuditListByReportType()
})
</script>
<style lang="scss" scoped></style>
