<script lang="ts" setup name="standardListAdd">
import { ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import dayjs from 'dayjs'
import type { ICertification } from './cert-interface'
import filePreviewDialog from './components/filePreviewDialog.vue'
import ApprovalDialogPart from './components/ApprovalDialogPart.vue'
import { printJSON, printPdf } from '@/utils/printUtils'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import { UploadFile } from '@/api/measure/file'
import useUserStore from '@/store/modules/user'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { changePrintStatus, getPhotoUrl } from '@/api/system/tool'
import { certificatePrintDetail } from '@/api/business/lab/cert'
import { cancelApproval, fetchApproval, submitApproval } from '@/api/approval'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/global'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'

const loading = ref(false) // 表单加载状态
const infoId = ref('') // 证书id
const pdfUrl = ref('')
const decisionItem = ref('') // 同意、驳回、拒绝按钮权限
const processId = ref('') // 流程实例id
const taskId = ref('') // 任务id，用于同意、驳回、拒绝审批
const approvalStatusName = ref('') // 审批状态名称
const printFileName = ref('') // 打印文件名称
const { proxy } = getCurrentInstance() as any
const printStatus = ref('') // 可打印状态
const buttonArray = ref<string[]>([]) // 顶部按钮数组
const pageType = ref('detail') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const filePreviewDialogRef = ref() // 预览弹窗ref
const approvalDialogPart = ref() // 审批对话ref

// 从路由中获取页面类型参数
const $route = useRoute()

// 逻辑代码
const dataForm = ref<ICertification>({
  certificationId: '',
  certificationReportCode: '',
  certificationReportName: '',
  certificateReportType: '',
  certificateReportTypeName: '',
  sampleId: '',
  originalRecordCode: '', // 原始记录编号
  sampleNo: '', // 样品编号
  measureCategory: '', // 检校验类别
  sampleName: '',
  sampleModel: '',
  manufacturingNo: '',
  orderId: '',
  orderNo: '',
  customerNo: '',
  customerName: '',
  measureCatogory: '',
  measureCatogoryName: '',
  createUser: '',
  createUserName: '',
  printNum: '',
  printStatus: '',
  createTime: '',
  calibrationMajor: '',
  issuanceDate: '',
  signId: '',
  signName: '',
  approvalSignId: '',
  approvalSignName: '',
  certificateReportFile: '',
  originalRecordId: '',
  originalRecordName: '', // 原始记录名称
  roomNumber: '',
  temperature: '',
  humidity: '',
  manufacturer: '',
  customerPhone: '',
  customerAddress: '',
  deliverer: '',
  delivererTel: '',
  planDeliverTime: '',
  requireOverTime: '',
  measureContent: '', // 检定项目
  remark: '', // 备注
})

// 下拉框数组类型
interface IOptions {
  id: string
  name: string
  value: string
  organizeName: string
  deptId: string
}
const checkTypeOptions = ref<IOptions[]>([])
const calibrationMajorList = ref<IOptions[]>([]) // 计量专业下拉框
const standardManagerStateList = ref<IOptions[]>([]) // 管理状态下拉框
const standardLevelList = ref<IOptions[]>([]) // 标准等级下拉框
const transmitRangeList = ref<IOptions[]>([]) // 传递范围下拉框
// 标准所在部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 获取下拉框
const getSelectList = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'calibrationMajor') {
      calibrationMajorList.value = res.data
    }
    else if (code === 'standardManagerState') {
      standardManagerStateList.value = res.data
    }
    else if (code === 'standardLevel') {
      standardLevelList.value = res.data
    }
    else if (code === 'transmitRange') {
      transmitRangeList.value = res.data
    }
    else if (code === 'standardCategory') {
      checkTypeOptions.value = res.data
    }
  })
}
getSelectList('calibrationMajor') // 获取校准专业下拉框
getSelectList('standardManagerState') // 获取管理状态下拉框
getSelectList('standardLevel') // 获取标准等级下拉框
getSelectList('transmitRange') // 获取传递范围下拉框
getSelectList('standardCategory') // 获取类别下拉框
const mesureCategoryList = ref<dictType[]>([]) // 校检类别

// 获取字典值
function getDict() {
  // 校检类别
  getDictByCode('measureCategory').then((response) => {
    mesureCategoryList.value = response.data
  })
}
getDict()
const params = ref({
  director: '',
  meterMajor: '',
  createEndTime: '',
  createstartTime: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '2',
  pdeptId: null,
  offset: 1,
  limit: 999999,
})

// 添加表格弹窗开关
const dialogVisible = ref(false)
// 初始化路由
const $router = useRouter()
// 关闭
const close = () => {
  // emit('close')
  $router.back()
}

// 获取详情信息
const getInfo = (id: string | number) => {
  certificatePrintDetail({ id }).then((res) => {
    dataForm.value = res.data
    printStatus.value = res.data.printStatus // 打印状态
    printFileName.value = res.data.printFileName // 打印文件名
    dataForm.value.createTime = res.data.createTime.split('T')[0]
  })
}

// 打印证书
const printCert = () => {
  ElMessageBox.confirm(
    '确定要打印吗？',
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    getPhotoUrl(printFileName.value as string).then((res) => {
      const url = res.data
      console.log(url)

      pdfUrl.value = res.data
      console.log(pdfUrl.value)
      changePrintStatus({ id: infoId.value }).then(() => {
        console.log('状态已经更改')
      })
      printPdf(res.data)

      // pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js'
      // proxy.$refs.pdf.print()
      // download(url, row.printFileName as string)
    })
    // const loading = ElLoading.service({
    //   lock: true,
    //   background: 'rgba(255, 255, 255, 0.8)',
    // })
    // getPdfStream(row.printFileName as string).then((res) => {
    //   const blob = new Blob([res.data], { type: 'application/pdf' })
    //   var date = (new Date()).getTime()
    //   var ifr = document.createElement('iframe')
    //   // ifr.style.frameborder = 'no'
    //   ifr.style.display = 'none'
    //   ifr.style.pageBreakBefore = 'always'
    //   ifr.setAttribute('id', `printPdf${date}`)
    //   ifr.setAttribute('name', `printPdf${date}`)
    //   ifr.src = window.URL.createObjectURL(blob)
    //   document.body.appendChild(ifr)
    //   doPrint(`printPdf${date}`)
    //   window.URL.revokeObjectURL(ifr.src) // 释放URL 对象
    //   loading.close()
    // })
  })
}

// 点击文档预览功能
const filePreView = () => {
  filePreviewDialogRef.value.initDialog(printFileName.value)
}

// -------------------------------------审批-----------------------------------------

// 审批结束回调
const approvalSuccess = () => {
  close() // 返回上一页
}
// 审批
const handleDistribute = (status: string) => {
  if (status === 'agree') {
    approvalDialogPart.value.initDialog('agree', taskId.value)
  }
  else {
    approvalDialogPart.value.initDialog('refuse', taskId, infoId.value)
  }
}
const approvalRecordData = ref([]) // 审批流程数据
// 查询审批记录
function getApprovalRecord(processId: string) {
  if (pageType.value !== 'add') {
    if (processId) {
      fetchApproval(processId).then((res) => {
        approvalRecordData.value = res.data
      })
    }
    else {
      ElMessage.warning('流程实例id为空')
    }
  }
}
// -------------------------------------------------------------------------------

onMounted(() => {
  infoId.value = $route.query.id as string
  // printStatus.value = $route.query.printStatus as string// 打印状态
  // printFileName.value = $route.query.printFileName as string// 打印文件名
  approvalStatusName.value = $route.query.approvalStatusName as string // 审批状态名称
  taskId.value = $route.query.taskId as string // 流程id
  decisionItem.value = $route.query.decisionItem as string // 流程id
  processId.value = $route.query.processId as string // 流程id

  getInfo(infoId.value)
  if (approvalStatusName.value !== '草稿箱' && processId.value) {
    getApprovalRecord(processId.value) // 获取审批流程
  }
})
</script>

<template>
  <app-container>
    <detail-page title="证书打印">
      <template #btns>
        <!-- <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批'" type="primary" @click="handleApprove('同意')">
          同意
        </el-button> -->
        <!-- <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '3'" type="primary" @click="handleApprove('驳回')">
          驳回
        </el-button> -->
        <!-- <el-button v-if="pageType === 'detail' && approvalStatusName === '待审批' && decisionItem !== '2'" type="danger" @click="handleApprove('拒绝')">
          拒绝
        </el-button> -->
        <!-- <el-button v-if="pageType === 'detail' && approvalStatusName === '审批中'" type="info" @click="handleApprove('取消')">
          取消
        </el-button> -->
        <el-button v-if="proxy.hasPerm('/schedule/certPrint/agree') && approvalStatusName === '待审批'" type="primary" @click="handleDistribute('agree')">
          同意
        </el-button>
        <el-button v-if="proxy.hasPerm('/schedule/certPrint/refuse') && approvalStatusName === '待审批'" type="danger" @click="handleDistribute('refuse')">
          拒绝
        </el-button>
        <el-button v-if="printStatus === '1'" type="primary" @click="printCert">
          打印
        </el-button>
        <el-button type="primary" @click="filePreView">
          预览
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form ref="ruleFormRef" :model="dataForm" label-position="right" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="证书编号:">
              <el-input
                v-model.trim="dataForm.certificateReportCode"
                :placeholder="pageType === 'detail' ? '' : '请输入证书编号'" class="full-width-input" clearable disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书报告名称:">
              <el-input
                v-model.trim="dataForm.certificateReportName"
                :placeholder="pageType === 'detail' ? '' : '请输入证书报告名称'" class="full-width-input" clearable disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原始记录编号:">
              <el-input v-model.trim="dataForm.originalRecordCode" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="原始记录名称:" prop="category">
              <el-input v-model.trim="dataForm.originalRecordName" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="校检类别:">
              <el-select
                v-model="dataForm.measureCategory"
                :placeholder="pageType === 'detail' ? ' ' : '请选择校检类别'"
                :disabled="pageType === 'detail'"
                class="full-width-input"
              >
                <el-option v-for="item of mesureCategoryList" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="6">
            <el-form-item label="依据文件:">
              <el-input
                v-model.trim="dataForm.file"
                :placeholder="pageType === 'detail' ? '' : '请输入依据文件'" class="full-width-input" clearable disabled
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="样品编号:">
              <el-input v-model.trim="dataForm.sampleNo" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="样品名称:" prop="standardLaboratory">
              <el-input v-model.trim="dataForm.sampleName" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号:" prop="laboratoryOwner">
              <el-input v-model.trim="dataForm.manufacturingNo" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型号:" prop="laboratoryOwnerContact">
              <el-input v-model.trim="dataForm.sampleModel" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托方代码:" prop="measureMajor">
              <el-input v-model.trim="dataForm.customerNo" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托方名称:" prop="assessmentUnit">
              <el-input v-model.trim="dataForm.customerName" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="委托方电话:" prop="assessDate">
              <el-input v-model.trim="dataForm.customerPhone" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="委托方地址:" prop="uncertainty">
              <el-input v-model.trim="dataForm.customerAddress" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="送检人:" prop="mesureRange">
              <el-input v-model.trim="dataForm.deliverer" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式:" prop="mesureRange">
              <el-input v-model.trim="dataForm.delivererTel" class="full-width-input" clearable disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计送达时间:" prop="planDeliverTime">
              <el-date-picker
                v-model="dataForm.planDeliverTime" type="datetime" class="full-width-input" clearable
                format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计检完时间:" prop="requireOverTime">
              <el-date-picker
                v-model="dataForm.requireOverTime" type="datetime" class="full-width-input"
                format="YYYY-MM-DD hh:mm:ss" clearable value-format="YYYY-MM-DD HH:mm:ss" disabled
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="电子签章:">
              <el-input v-model.trim="dataForm.signName" class="full-width-input" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="检定项目:">
              <el-input v-model.trim="dataForm.measureContent" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input v-model.trim="dataForm.remark" class="full-width-input" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="证书报告附件:">
              <show-photo v-if="dataForm.certificateReportFile" :minio-file-name="dataForm.certificateReportFile" />
              <span v-else-if="pageType === 'detail'">无</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <file-preview-dialog ref="filePreviewDialogRef" />
    <detail-block v-if="approvalStatusName !== '草稿箱' && pageType !== 'add' && processId" title="审批流程">
      <!-- 审批流程 -->
      <approval-record ref="approvalRecord" :approval-record-data="approvalRecordData" />
    </detail-block>
    <!-- 审批弹窗 -->
    <!-- <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" /> -->
    <approval-dialog-part ref="approvalDialogPart" @on-success="approvalSuccess" />
  </app-container>
</template>

<style lang="scss">
.el-upload-list {
  display: none !important;
}
</style>
