<template>
  <div class="template-edit">
    <!-- 批量校核校核显示 -->
    <div class="btn-group" v-if="isBatch">
      <div class="left">
        <el-button
          v-for="report in getRecheckList"
          :type="currentSelectedReport.reportId == report.reportId ? 'primary' : 'default'"
          :key="report.reportId"
          @click="() => handleSelectedReport(report)"
          plain
        >{{ report.reportName }}</el-button>
      </div>
      <div class="right">
        <template v-if="pageType === 'check'">
          <el-button type="primary" v-if="equipId && route.name !== 'InspectionPlanAudit'"  plain @click="() => handleViewEquipment()">查看设备档案</el-button>
          <el-button type="primary" v-if="showViewFile" plain @click="handleUploadItem">查看附件</el-button>
          <el-button type="success" @click="handlePass">通过</el-button>
          <el-button type="primary" @click="handleRevert">回退</el-button>
        </template>
        <el-button type="default" @click="handleClose">取消</el-button>
      </div>
    </div>
    <!-- 批量校核校核显示 -->
    <div class="audit-container" :style="{}"> <!-- 批量校核单独校核的高度不一样 -->
      <div ref="auditCheckRecordRef" class="content" v-loading="loading">
<!--        <el-scrollbar :height="contentHeight">-->
<!--          <VuePdfEmbed-->
<!--            :height="500"-->
<!--            :width="contentWidth"-->
<!--            :source="recordSource"-->
<!--            v-if="recordSource"-->
<!--            :text-layer="false"-->
<!--            :annotation-layer="false"-->
<!--            @rendered="handlePdfRendered"-->
<!--          />-->
<!--        </el-scrollbar>-->
        <SpreadViewer :initData="initData" ref="spreadRef"/>
      </div>
<!--      <SpreadDesigner-->
<!--        ref="spreadDesignerRef"-->
<!--        :fullScreen="true"-->
<!--        :showFullScreenOperationBtn="false"-->
<!--        @init="handleDesignerInit"-->
<!--        style="display: none"-->
<!--      />-->
      <div class="operation-panel">
        <!-- 单独校核显示 -->
        <div class="default-toolbar" v-if="!isBatch">
          <template v-if="pageType === 'check'">
            <el-button type="primary" v-if="equipId && route.name !== 'InspectionPlanAudit'" plain @click="() => handleViewEquipment()">查看设备档案</el-button>
            <el-button type="success" @click="handlePass">通过</el-button>
            <el-button type="primary" @click="handleRevert">回退</el-button>
          </template>
          <el-button type="primary" v-if="showViewFile" plain @click="handleUploadItem">查看附件</el-button>
          <el-button type="default" @click="handleClose">取消</el-button>
        </div>
        <!-- 单独校核显示 end -->

        <div class="operation-inner">
          <!-- 流转记录 -->
          <div class="operation-item">
            <div class="item-header"> 回退原因 </div>
            <div class="item-content">
              <el-form
                ref="returnFormRef"
                :model="returnForm"
                :rules="returnFormRules"
                label-position="right"
                label-width="80px"
              >
                <!-- 批量校核 -->
                <el-form-item label="退回报告" v-if="isBatch">
                  <el-select
                    v-model="selectedRollBackIds"
                    placeholder="请选择退回报告"
                    style="width: 100%"
                    multiple
                    clearable
                  >
                    <el-option v-for="item in getRecheckList" :key="item.reportId" :value="item.reportId" :label="item.reportName"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="退回阶段" v-if="showRollbackStage">
                  <el-select
                    v-model="selectedRollbackStatus"
                    placeholder="请选择回退阶段"
                    style="width: 100%"
                  >
                    <el-option label="记录录入" :value="PressureCheckerMyTaskStatus.RECORD_INPUT" />
                  </el-select>
                </el-form-item>
                <el-form-item label="回退原因" prop="reason">
                  <el-input
                    v-model="returnForm.reason"
                    type="textarea"
                    :rows="5"
                    maxlength="100"
                    placeholder="请输入回退原因"
                  />
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div class="operation-item">
            <div class="item-header"> 流转记录 </div>
            <div class="item-content">
              <el-empty v-if="!recordList" description="暂无流转记录" :image-size="120" />
              <SmartTable
                v-else
                ref="smartTableRef"
                v-model:pageNo="pageNo"
                v-model:pageSize="pageSize"
                v-model:total="total"
                v-model:columns="columns"
                :showRefresh="false"
                :useBorderLayout="false"
                :data="recordList"
                :buttons="[]"
                :isPagination="total > 0"
                @on-page-no-change="() => fetchRecordList()"
                @on-page-size-change="() => fetchRecordList()"
              />
            </div>
          </div>
        </div>
      </div>
      <Dialog v-model="isShowAuditDialog" width="400" title="请选择审核人">
        <CustomLargeListSelect
          v-model="form.recheckUser"
          :fetchFunc="getUserList"
          label-key="nickname"
          value-key="id"
          searchKeyProp="nickName"
          @change="handleChangeEntrustUnit"
        />
        <template #footer>
          <el-button type="primary" @click="handleAuditSelectConfirm">保 存</el-button>
          <el-button @click="handleAuditSelectCancel">取 消</el-button>
        </template>
      </Dialog>
    </div>
  </div>
  <!-- 设备档案弹窗 -->
     <EquipBoilerForm ref="EquipBoilerFormRef" />

  <ReportListUploadModal ref="reportListUploadModalRef" :selectedItem="currentReport" :reportList="allReportList" />
</template>
<script setup lang="tsx">
  // const RejectDialog = defineAsyncComponent(() => import('@/views/pressure/components/RejectDialog.vue'))
  import SmartTable from '@/components/SmartTable/SmartTable'
  import VuePdfEmbed from 'vue-pdf-embed'
  import 'vue-pdf-embed/dist/styles/annotationLayer.css'
  import 'vue-pdf-embed/dist/styles/textLayer.css'
  import { debounce, update } from 'lodash-es'
  import { BoilerTaskOrderApi, ReportItemVO } from '@/api/pressure2/boilertaskorder'
  import { getUserList } from '@/api/common/user'
  import { useRoute } from 'vue-router'
  import dayjs from 'dayjs'
  import {
    PressureCheckerMyTaskStatusMap,
    PressureCheckerMyTaskStatus,
    PressureTaskOrderStatusMap,
    PressureCheckerRecheckStatusMap,
    PressureReportType
  } from '@/utils/constants'
  import * as UserApi from '@/api/system/user'
  import { uploadFile } from '@/api/common/index'
import { ElMessageBox } from 'element-plus'
import ReportListUploadModal from '@/views/pressure2/boilerchecker/components/reportListUploadModal.vue'
  import EquipBoilerForm from '@/components/EquipBoilerForm/index.vue'
  import * as GC from "@grapecity-software/spread-sheets";
  import {DynamicTbValApi} from "@/api/pressure2/dynamictbval";
  import {ref, watch} from "vue";
  import {getPDF, getStandardTemplateInfo} from "@/api/laboratory/standard/template";
  import {buildFileUrl} from "@/utils";
  import axios from "axios";
  import {editReport} from "@/utils/reportUtil";
  import {DynamicTbColApi} from "@/api/pressure2/dynamictbcol";
  import {InitParams} from "@/components/pressure2/DynamicReport/SpreadInterface";
  import {PipeTaskOrderApi} from "@/api/pressure2/pipetaskorder";
  import {SpreadViewer} from "@/components/pressure2/DynamicReport";
  const route = useRoute()
  const routeNameTypes = {
    'BoilerCheckerRecordCheck': '记录校核审核',
    'AuditInspectionCommentsNotice': '检验意见通知书审核',
    'majorIssueCluesNotice': '重大线索通知审核'
  }
  const getRouteName = computed(() => route.name)
  // 校核人选择对话框状态
  const isShowAuditDialog = ref(false)
  const form = ref<Record<string, any>>({
    recheckUser: {}
  })
  const props = defineProps({
    visible: {
      type: Boolean
    },
    reportUrl: {
      type: String,
      default: ''
    },
    recheckInfo: {
      type: Object,
      default: () => ({})
    },
    pageType: {
      type: String,
      default: 'check'
    },
    auditId: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    equipId: { // 设备Id
      type: String,
      default: ''
    },
    apiParams: {
      required: true,
      type: Object,
      default: () => ({})
    },
    showRollbackStage: {
      type: Boolean,
      default: true
    },
    rejectFn: { // 回退接口
      required: true,
      type: Function,
      default: () => {}
    },
    passFn: { // 通过审核接口
      required: true,
      type: Function,
      default: () => {}
    },
    recordFn: { // 流转记录接口
      required: true,
      type: Function,
      default: () => {}
    },
    reportType: {
      required: true,
      type: Number,
      default: undefined
    },
    templateId:{
      required: true,
      type: String,
      default: ''
    },
    useType:{
      required: true,
      type: String,
      default: ''
    }
  })
  const emits = defineEmits(['update:visible', 'close', 'update', 'update:recheckInfo'])
  const loading = ref(true)
  const recordSource = ref('')
  const flag = ref<boolean>(true)

  // 报告附件信息
  const allReportList = ref<ReportItemVO[]>([])
  const currentReport = ref<ReportItemVO>()
  const template = ref('')
  const currentSelectedReport = ref({})
  const getRecheckList = computed(() => {
    currentSelectedReport.value = props.recheckInfo?.recheckList && props.recheckInfo?.recheckList.length ? props.recheckInfo?.recheckList[0] : {}
    return props.recheckInfo?.recheckList
  })
  const isBatch = computed(() => !!getRecheckList.value && getRecheckList.value.length > 1)
  // 加载pdf
  let previewSpread = null
  const pdfLoad = ref(true)
  const fetchTemplateData = async () => {
    let res
    let apiParamsId = props.apiParams.id ? props.apiParams.id : props.apiParams.ids[0]
    switch(props.reportType) {
      case PressureReportType['WORKINSTRUCTION']:
      case PressureReportType['INSPECTIONPLAN']:
      case PressureReportType['MAINQUESTION']:
      case PressureReportType['SUGGUESTION']:
        res = {templateId: props.templateId}
        break
      default:
        res = await BoilerTaskOrderApi.getTaskOrderItemReportRecord(apiParamsId)
    }
    template.value = res.templateId
    const templateRes = await getStandardTemplateInfo({id: res.templateId})
    if (templateRes && templateRes.fileUrl) {
      const fileUrl = buildFileUrl(templateRes.fileUrl)
      const response = await axios.get(fileUrl, {responseType: 'blob'});
      return new Blob([response.data], {type: response.headers['content-type']});
    }
    return null
  }
  const handleDesignerInit = async (instance) => {
    try {
      previewSpread = instance.getWorkbook()
      let blob = await fetchTemplateData();
      if (!blob) return;
      let apiParamsId = props.apiParams.id ? props.apiParams.id : props.apiParams.ids[0]
      previewSpread.open(blob, async () => {
        console.log('预览加载完成');
        await DynamicTbValApi.getDynamicTbValByRefId(apiParamsId).then(async res => {
        let sheet1 = previewSpread.sheets[0];
          for (let i = 0; i < previewSpread.sheets.length; i++) {
            let dataSource1 = new GC.Spread.Sheets.Bindings.CellBindingSource({});
            if (res && res.length) {
              // 设置数据
              let sheetData = {};
              res.forEach(i => sheetData[i.colCode] = i.valValue);
              dataSource1 = new GC.Spread.Sheets.Bindings.CellBindingSource(sheetData);
            }
            sheet1.setDataSource(dataSource1);
            let imgCol = await DynamicTbColApi.getImgDynamicTbColByTbId(template.value)
            imgCol = imgCol.map(i => i.colCode)
            await editReport(sheet1,null,imgCol)
          }
        })
        loading.value = false
        pdfLoad.value = !pdfLoad.value
      }, (error) => {
        console.error('文件打开失败:', error);
      });
    } catch (error) {
      console.error('预览加载失败:', error);
    }
  }
  const savePreview = () => {
    const formData = new FormData()
    previewSpread.save(async function (blob) {
      formData.append('file', blob)
      const response = await getPDF(formData)
      if (response) {
        const flow = new Blob([response], { type: 'application/pdf' })
        recordSource.value = URL.createObjectURL(flow)
      }
    }, (e) => {

    }, {
      includeBindingSource: true
    })
  }
  // watch(pdfLoad, async (newValue) => {
  //   savePreview()
  // })
  // 获取报告pdf
  /*watch(() => [props.reportUrl, props.reportType, getRecheckList.value], async ([reportUrl, reportType, getRecheckList]) => {
    // 批量不走以下逻辑
    if(!reportUrl || getRecheckList?.length > 0) return
    switch(reportType) {
      case PressureReportType['WORKINSTRUCTION']:
      case PressureReportType['INSPECTIONPLAN']:
      case PressureReportType['MAINQUESTION']:
        recordSource.value = props.reportUrl
        break
      case PressureReportType['SUGGUESTION']:
      default:
        // const url = buildFileUrl(props.reportUrl)
        const data = {
          fileType: 200,
          type: 100,
          reportId: props.auditId
        }
        const pdfBlob = await BoilerTaskOrderApi.getReportPreview({...data})
        recordSource.value = URL.createObjectURL(pdfBlob)
    }
  }, {
    immediate: true
  })*/

  // 切换校核报告
  const handleSelectedReport = (report) => {
    currentSelectedReport.value = report
  }

 /* watch(() => currentSelectedReport.value, async (currentSelectedReport) => {
    if(!Object.keys(currentSelectedReport).length) return
    const data = {
      fileType: 200,
      type: 100,
      reportId: currentSelectedReport?.reportId
    }
    const pdfBlob = await BoilerTaskOrderApi.getReportPreview({...data})
    recordSource.value = URL.createObjectURL(pdfBlob)
  }, {
    immediate: true
  })
*/

  const spreadRef=ref();
  const initData=ref<InitParams>(
    {
      templateId: '',
      refId: '',
      refName:'',
      insId:'',
      opType: 1, // 0:excel,1: pdf
    });

  const initPreview = async ()=>{

    // const reportId = props.selectedItem?.id;
    // const refId = showReportPdfType.value === 'report' ? "report_" + reportId :
    //   showReportPdfType.value === 'result' ? "result_" + reportId : reportId
    // const templateId = showReportPdfType.value === 'report' ? templateParams.value.reportTemplateId :
    //   showReportPdfType.value === 'result' ? templateParams.value.resultTemplateId : templateParams.value.templateId

    let res
    let apiParamsId;
    switch(props.reportType) {
      case PressureReportType['SUGGUESTION']:
        apiParamsId = props.apiParams.reportId ? props.apiParams.reportId : props.apiParams.reportIds[0]
        break
      case PressureReportType['WORKINSTRUCTION']:
      case PressureReportType['INSPECTIONPLAN']:
      case PressureReportType['MAINQUESTION']:
      default:
        apiParamsId = props.apiParams.id ? props.apiParams.id : props.apiParams.ids[0]
        break
    }
    // if (props.useType === 'checkNotice'){
    //   apiParamsId = props.apiParams.reportId ? props.apiParams.reportId : props.apiParams.reportIds[0]
    // }else{
    //   apiParamsId = props.apiParams.id ? props.apiParams.id : props.apiParams.ids[0]
    // }
    //let apiParamsId = props.apiParams.id ? props.apiParams.id : props.apiParams.ids[0]
    switch(props.reportType) {
      case PressureReportType['WORKINSTRUCTION']:
      case PressureReportType['INSPECTIONPLAN']:
      case PressureReportType['MAINQUESTION']:
      case PressureReportType['SUGGUESTION']:
        res = {templateId: props.templateId}
        break
      default:
        res = await BoilerTaskOrderApi.getTaskOrderItemReportRecord(apiParamsId)
    }

    template.value = res.templateId

    initData.value.templateId = template.value;
    initData.value.refId = apiParamsId;
    initData.value.opType = 1;

    //spreadRef.value?.reloadView();

    setTimeout(()=>{
      spreadRef.value?.reloadView();
    },50)

    console.log('initPreview', initData.value)
  }


  // 通过
  const handlePass = () => {
    const canSubmit = canSubmitMainReportType()
    if(!canSubmit) return
    // 
    ElMessageBox.confirm(isBatch.value ? '确定批量通过吗？' : '确定通过吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      // TODO: 批量通过
      let params = {}
      if(getRecheckList.value && getRecheckList.value?.length) {
        params = {
          ids: getRecheckList.value.map(item => item.reportId)
        }
      } else {
        params = props.apiParams
      }

      const passResult = await props.passFn(params)
      // 校核通过后，判断当前报告是否为主报告
      // 如果是，查询主报告是否有子报告: 1、有子报告的条件下，是否所有子报告都办结；2、没有子报告 这两种条件下都可以直接提交审核
      // 否：直接关闭校核详情页面
      console.log(passResult);
      if(passResult && props.reportType !== PressureReportType['MAIN']) {

        ElMessage.success('通过成功')
        emits('update')
        handleClose()

      } else if(passResult && props.reportType === PressureReportType['MAIN']) {

        // 查询主报告下的所有子报告
        const getSubReportList = await handleCheckoutAllSubReport()
        if(getSubReportList === false) return
        if(!getSubReportList || !getSubReportList?.length) {

          //handleSubmitToApproval('该设备所有子报告已办结，是否提交至报告审核？')
          ElMessage.success('通过成功')
          emits('update')
          handleClose()

        } else {
          
          // 查询未办结的报告列表
          const unFinishList = getSubReportList.filter(report => report.taskStatus !== PressureCheckerMyTaskStatus.CANCELLATION && report.taskStatus !== PressureCheckerMyTaskStatus.REPORT_END)

          if(!unFinishList.length) {
            // 没有未办结的子报告，可以提交审核
            handleSubmitToApproval('该设备所有子报告已办结，是否提交至报告审核？')
          } else {
            // 存在未办结的子报告，关闭校核页面
            ElMessage.success('通过成功')
            emits('update')
            handleClose()
          }

        }
      } else {
        ElMessage.error('出错啦!')
      }
    }).catch(() => {
      console.log('用户取消操作！')
    })
    
  }

  // 主报告提交至报告审核环节
  const handleSubmitToApproval = (title) => {
    ElMessageBox.confirm(title, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      let res = await UserApi.getApprovalDetail({}) // 判断是否有审批信息
      if (res && res.approveUser) {
        form.value = Object.assign(form.value, {recheckUser: res.approveUser})
      } else {
        form.value.recheckUser = {}
      }
      isShowAuditDialog.value = true
    }).catch(() => {
      emits('update')
      ElMessage.success('通过成功')
      handleClose()
    })
  }

  // 获取主报告下的所有子报告
  const handleCheckoutAllSubReport = async () => {
    try {
      const subReport = await BoilerTaskOrderApi.subReportApi({id: props.id})
      return (subReport || []).filter(report => report.taskStatus !==  PressureCheckerMyTaskStatus['REPORT_END'])
    } catch (err) {
      console.error('获取主报告的子报告列表报错了')
      return false
    }
  }

  // 取消
  const handleClose = () => {
    emits('update:visible', false)
    emits('close')
  }


  // pdf组件渲染完成后的回调函数
  const handlePdfRendered = () => {
    loading.value = false
  }
  const contentWidth = ref(1000)
  const contentHeight = ref(500)
  const auditCheckRecordRef = ref()
  const handleWindowResize = debounce(() => {
    contentWidth.value = auditCheckRecordRef.value.clientWidth > 1000 ? 1000 : auditCheckRecordRef.value.clientWidth
    contentHeight.value = auditCheckRecordRef.value.clientHeight
  }, 100)

// 获取任务详情数据
const reportList = ref<ReportItemVO[]>([])
async function fetchTaskDetail() {
  if(!props.id) return
  loading.value = true
  try {
    const response = await BoilerTaskOrderApi.getTaskOrderOrderItem(props.id)
    if(!response || !response.reportList || !Array.isArray(response.reportList)) return
    // 过滤报告列表 - 只显示状态 >= CONFIRMED 的项目 已认领 400
    const filteredReportList = response.reportList.filter(
      (item) => item.taskStatus >= PressureCheckerMyTaskStatus.CONFIRMED
    )
    reportList.value = filteredReportList
    console.log('reportList.value', reportList.value)
    const recheckList = props.recheckInfo?.recheckList || [{...props.apiParams, reportId: props.apiParams.id || props.auditId}]
    console.log('recheckList', recheckList)
    const reportIds = recheckList.map(v=> v.reportId)
    allReportList.value = response.reportList.filter(report => reportIds.includes(report.id))
    currentReport.value = response.reportList.find(report => report.id === (props.apiParams.id || props.auditId))
    console.log('allReportList', allReportList.value)
    console.log('currentReport', currentReport.value)
  } catch (error) {
    console.error('获取任务详情失败:', error)
    ElMessage.error('获取任务详情失败')
    reportList.value = []
  } finally {
    loading.value = false
  }
}
// 当意见通知书未办结时，主报告不能流转到后续流程(提交校核)
const canSubmitMainReportType = ()=>{
  // 不是主报告，直接返回true
  if(props.reportType !== PressureReportType['MAIN']) return true
  // 判断检验意见通知书的状态
  const report = unref(reportList).find(x => x.reportType === PressureReportType['SUGGUESTION'])
  console.log('检验意见通知书', report)
  // 不存在检验意见通知书返回true
  if(!report) return true
  // 检验意见通知书已办结，返回true
  if(report.taskStatus === PressureCheckerMyTaskStatus['REPORT_END']) return true
  ElMessage.warning('该报告存在未办结检验意见通知书，无法通过校核请退回报告到记录录入')
  return false
}


  onMounted(() => {
    contentWidth.value = auditCheckRecordRef.value.clientWidth > 1000 ? 1000 : auditCheckRecordRef.value.clientWidth
    contentHeight.value = auditCheckRecordRef.value.clientHeight
    window.addEventListener('resize', handleWindowResize);
    // 获取当前报告的所有子报告
    fetchTaskDetail()
    fetchTemplateData()
    initPreview()
  })
  onUnmounted(() => {
    window.removeEventListener('resize', handleWindowResize);
  })

  // 回退
  const selectedRollbackStatus = ref(500)
  const selectedRollBackIds = ref([])
  const returnForm = ref({
    reason: ''
  })
  const returnFormRules = ref({
    reason: [{required: true, message: '请输入回退原因', trigger: 'blur'}]
  })
  const returnFormRef = ref()

  const handleRevert = () => {
    returnFormRef.value.validate(async (valid) => {
      if(!valid) return ElMessage.error('请填写回退原因')
      const params = {
        ...props.apiParams,
        reason: returnForm.value.reason,
      }

      // 批量回退的参数
      if(getRecheckList.value && getRecheckList.value?.length) {
        delete params?.id
        delete params?.reason
        params['returnReason'] = returnForm.value.reason
        params['ids'] = getRecheckList.value?.length === 1 ? [getRecheckList.value[0].reportId] : selectedRollBackIds.value
      }
      props.rejectFn(params).then((returnRes)=>{
        if(returnRes) {
          if(getRecheckList.value && getRecheckList.value?.length > (params['ids']) || 0) {
            // 批量部分退回
            const unReturnList = getRecheckList.value.filter(x => !selectedRollBackIds.value.includes(x.reportId))
            emits('update:recheckInfo', {...props.recheckInfo, recheckList: unReturnList})
            selectedRollBackIds.value = []
            returnForm.value.reason = ''
            ElMessage.success(`回退成功`)
            return
          }
          // 批量全部退回判断 && 非批量校核逻辑
          emits('update')
          handleClose()
          ElMessage.success('回退成功')
        }
      })
      // const returnRes = await props.rejectFn(params)
      // if(returnRes) {
      //   if(getRecheckList.value && getRecheckList.value?.length > (params['ids']) || 0) {
      //     // 批量部分退回
      //     const unReturnList = getRecheckList.value.filter(x => !selectedRollBackIds.value.includes(x.reportId))
      //     emits('update:recheckInfo', {...props.recheckInfo, recheckList: unReturnList})
      //     selectedRollBackIds.value = []
      //     returnForm.value.reason = ''
      //     ElMessage.success(`回退成功`)
      //     return
      //   }
      //   // 批量全部退回判断 && 非批量校核逻辑
      //   emits('update')
      //   handleClose()
      //   ElMessage.success('回退成功')
      // }
    })
  }

  // 流转记录
  const pageNo = ref(1)
  const pageSize = ref(10)
  const total = ref(0)
  const recordList = ref([])
  const columns = ref([
    {
      label: '环节',
      prop: 'process',
      render: (row, process) => {
        if(getRouteName.value === 'BoilerCheckerRecordCheck')
          return PressureCheckerMyTaskStatusMap[process]
        else 
          return PressureTaskOrderStatusMap[process]
      }
    },
    {
      label: '处理人',
      prop: '',
      render: (row) => {
        return <div>
          <p>{row.createUser.nickname}</p>
          <p>（{row.createUser.employeeNo}）</p>
        </div>
      }
    },
    {
      label: '处理时间',
      prop: 'createTime',
      render: (row, value) => {
        return !value ? '-' : dayjs(value).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    {
      label: '结果',
      prop: 'result',
      render: (row, result) => {
        return ['100', '200'].includes(result) ? resultMap[result] : !result ? '-' : PressureCheckerRecheckStatusMap[Number(result)]
        // return result === '100'
        //   ?
        // getRouteName.value === 'AuditInspectionCommentsNotice' ? '拒绝' : '通过'
        //   :
        // (          
        //   result === '200'
        //     ?
        //   getRouteName.value === 'AuditInspectionCommentsNotice' ? '通过' : '拒绝'
        //     :
        //   !result ? '-' : PressureCheckerRecheckStatusMap[Number(result)]
        // )
      }
    },
    {
      label: '描述',
      prop: 'remark',
      render: (row, value) => {
        return !value ? '-' : value
      }
    }
  ])

  const resultMap = {
    '100': '通过',
    '200': '拒绝',
  }
  
  // 记录校核：审核
  const fetchRecordList = async () => {
    // 流转记录接口数据
    const params = {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      reportId: props.auditId
    }
    try {
      const response = await BoilerTaskOrderApi.getTaskOrderItemReportRecordPage(params)
      // 根据实际接口返回的数据结构获取数据
      recordList.value = response.list
      total.value = response.total
    } catch (error: any) {
      console.error('获取流转记录失败:', error)
      ElMessage.error('获取流转记录失败，请稍后重试')
      recordList.value = []
    }
  }

  const handleChangeEntrustUnit = (unit: Record<string, any>) => {
    form.value.recheckUser = unit
  }

  // 上传主报告文件流
  const handleUploadAPIReportPreviewBlob = async (submitApprovalFn) => {
    if(props.reportType !== PressureReportType['MAIN']) return 
    // 获取文件流
    const blob = await BoilerTaskOrderApi.getReportPreview({
      reportId: props.apiParams.id,
      type:  300, // 报告模板
      fileType: 100 // xlsx
    })
    if(blob) {
      // 上传文件流
      const formData = new FormData()
      formData.append('file', blob)
      const response = await uploadFile(formData)

      // 保存报告编制的url
      const saveResult = await BoilerTaskOrderApi.saveReportPrepare({
        id: props.apiParams.id,
        prepareUrl: response,
      })
      
      if(saveResult) {
        console.log('上传文件流成功!')
        // 提交审核
        await submitApprovalFn()
      } else {
        console.error('上传文件流失败!')
      }
    }
  }

  const handleSubmitMainReportApproval = async () => {
    const submitResult = await BoilerTaskOrderApi.submitReportAudit({
      ...props.apiParams,
      approveId: form.value?.recheckUser?.id
    })
    if (submitResult) {
      ElMessage.success('提交审核成功！')
      isShowAuditDialog.value = false
      emits('update')
      // 这里可以做页面刷新
      handleClose()
    }
  }
  // 选择审核人的保存回调
  const handleAuditSelectConfirm = async () => {
    // 这里需要查询主报告文件流，模拟报告编制后，再提交审核
    handleUploadAPIReportPreviewBlob(handleSubmitMainReportApproval)
  }

  const handleAuditSelectCancel = async () => {
      isShowAuditDialog.value = false
      handleClose()
  }
  // 重大线索告知 && 检验意见通知书的流转记录
  const fetchOtherRecordList = async () => {
    try {
      console.log(props)
      const response = await props.recordFn({id: props.id, reportType: props.reportType})
      recordList.value = response
      total.value = 0
    } catch (error: any) {
      console.error('获取流转记录失败:', error)
      ElMessage.error('获取流转记录失败，请稍后重试')
      recordList.value = []
    }
  }
  if(getRouteName.value === 'BoilerCheckerRecordCheck') {
    fetchRecordList()
  } else {
    fetchOtherRecordList()
  }

  // 设备档案弹窗
  const EquipBoilerFormRef = ref<InstanceType<typeof EquipBoilerForm>>()
  const handleViewEquipment = () => {
    EquipBoilerFormRef.value.open(props.equipId)
  }

  // 查看附件
  const showViewFile = computed(() => {
    console.log('props.reportType', props.reportType)
    return props.reportType && ![PressureReportType.INSPECTIONPLAN, PressureReportType.WORKINSTRUCTION, PressureReportType.MAINQUESTION].includes(props.reportType)
  })
  const reportListUploadModalRef = ref<InstanceType<typeof ReportListUploadModal>>()
  const handleUploadItem = () => {
    reportListUploadModalRef.value?.openModal(false)
  }

</script>
<style lang="scss" scoped>
.btn-group {
  display: flex;
  justify-content: space-between;
  padding-bottom: 12px;
  max-width: 100%;
  overflow: hidden;
  gap: 48px;
  .left {
    display: flex;
    align-items: center;
    flex-wrap: nowrap;
    flex: 1;
    overflow-x: auto;
    .title {
      white-space: nowrap;
    }
  }
}
.default-toolbar {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-bottom: 20px;
  white-space: nowrap;
  ::v-deep .el-button {
    margin-left: 0;
  }
}
.template-edit {
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1000;
  padding: 20px 20px 0;
  box-sizing: border-box;
  background-color: #fff;
  .audit-container {
    height: calc(100vh - 154px);
    display: flex;
    align-items: stretch;
    .content {
      height: calc(100% - 10px);
      display: flex;
      justify-content: center;
      padding: 10px 40px;
      flex: 1;
      border: 1px solid var(--el-border-color);
      // border-right: 1px solid var(--el-border-color);
      box-sizing: border-box;
      overflow-y: auto;
    }
    .operation-panel {
      display: flex;
      flex-direction: column;
      flex-basis: 440px;
      height: calc(100% - 10px);
      padding: 10px;
      box-sizing: border-box;
      border: 1px solid var(--el-border-color);
      border-left: 0;
      overflow: hidden;
    }
    .operation-inner {
      display: flex;
      flex-direction: column;
      position: relative;
      flex: 1;
      background-color: #fff;
      box-sizing: border-box;
      overflow: hidden;
    }
    .operation-item {
      /*max-height: calc(100% / 3);*/
      margin-bottom: 10px;
      overflow-y: auto;

      .item-header {
        position: sticky;
        top: 0;
        left: 0;
        z-index: 1000;
        width: 100%;
        height: 28px;
        padding-left: 20px;
        font-size: 16px;
        line-height: 28px;
        color: #fff;
        background: #fff url('@/assets/imgs/pressure/my-task-detail-operation-bg.png') no-repeat
          left top;
        background-size: 100% 28px;
      }
      .item-content {
        padding: 10px 0;
        font-size: 14px;
        overflow-y: auto;
        box-sizing: border-box;
        .el-empty {
          width: 100%;
          height: 150px;
          padding: 0;
          box-sizing: border-box;
        }
        :deep(.smart-table-inner) {
          .toolbar {
            margin: 0 !important;
          }
        }
      }
      &:first-child {
        overflow: hidden;
      }
      &:last-child {
        max-height: unset;
        flex: 1;
      }
    }
  }
  // .content {
  //   display: flex;
  //   justify-content: center;
  //   margin-top: 20px;
  //   border-radius: 4px;
  //   border: 1px solid var(--el-border-color-light);
  //   background-color: #fff;
  //   height: calc(100% - 82px);
  //   overflow-y: scroll;
  //   overflow-x: hidden;
  //   .empty-text {
  //     width: 100%;
  //     height: 100%;
  //     display: flex;
  //     justify-content: center;
  //     align-items: center;
  //     font-size: 28px;
  //     color: rgba($color: #000000, $alpha: 0.2);
  //   }
  // }
}
</style>
