<!-- 测试、校准或检定合格分包方名录编辑 -->
<script lang="ts" setup name="SubpackageReviewEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import deviceTable from './deviceTable.vue'
import ApprovalDialog from './ApprovalDialog.vue'
import subpackageDialog from './subpackageDialog.vue'
import showPhoto from '@/views/tested/device/info/components/showPhotoSinge.vue'
import { delTextBtn, editBtn, submitBtn } from '@/utils/applyBtns'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import { uploadApi } from '@/api/system/notice'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
import { cancelReview, deleteReview, editReview, getDetail, submitReview } from '@/api/eqpt/subpackage/review'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const submitId = ref('') // 提交id-保存接口获取
const ruleFormRef = ref<FormInstance>() // from组件
const statusName = $route.query.statusName as string
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
// 表单
const ruleForm = ref({
  address: '',
  approvalStatus: '',
  attachment: '',
  contact: '',
  contactNumber: '',
  createDeptId: '',
  createDeptName: '',
  createTime: '',
  createUserId: '',
  createUserName: '',
  decisionItem: '',
  equipmentList: [],
  fax: '',
  id: '',
  labAccreditation: '',
  postcode: '',
  predictEndTime: '',
  predictPrice: '',
  predictStartTime: '',
  processId: '',
  remark: '',
  reviewName: '',
  reviewNo: '',
  subcontractReason: '',
  subcontractorCompanyName: '',
  subcontractorDirectorName: '',
  subcontractorId: '',
  subcontractorNo: '',
  taskId: '',
  technicalAbility: '',
  testMethod: '',
  traceability: '',
  updateTime: '',
})
const deviceRef = ref()
// 表单1验证规则
const rules = ref<FormRules>({
  subcontractorNo: [{ required: true, message: '分包方编号必选', trigger: ['blur', 'change'] }],
  predictStartTime: [{ required: true, message: '预计开始时间必选', trigger: ['blur', 'change'] }],
  predictEndTime: [{ required: true, message: '预计结束时间必选', trigger: ['blur', 'change'] }],
  subcontractReason: [{ required: true, message: '分包原因必选', trigger: ['blur', 'change'] }],
  contact: [{ required: true, message: '联系人必填', trigger: ['blur', 'change'] }],
  contactNumber: [{ required: true, message: '联系电话必填', trigger: ['blur', 'change'] }],
  labAccreditation: [{ required: true, message: '实验室认可情况必填', trigger: ['blur', 'change'] }],
  traceability: [{ required: true, message: '溯源性必填', trigger: ['blur', 'change'] }],
  testMethod: [{ required: true, message: '测试方法必填', trigger: ['blur', 'change'] }],
  technicalAbility: [{ required: true, message: '技术能力必填', trigger: ['blur', 'change'] }],
})

// 获取下拉框数据
const reasonList = ref<{ id: string; value: string; name: string }[]>() // 规模
const fetchSelectData = () => {
  // 分包原因
  getDictByCode('eqptSubpackageReason').then((res) => {
    reasonList.value = res.data
  })
}
fetchSelectData()
// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string || 'detail'
  ruleFormRef.value?.resetFields()
  if (!$route.path.includes('create')) {
    const data = JSON.parse($route.query.row as string)
    getDetail({ id: data.id }).then((res) => {
      const data = res.data
      ruleForm.value = data
    })
  }
  if ($route.path.includes('create') || $route.path.includes('update')) {
    ruleForm.value.reviewName = '测试、校准或检定工作分包评审表'
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createUserName = userStore.name
    ruleForm.value.createDeptId = userStore.deptId
    ruleForm.value.createDeptName = userStore.deptName
    // getUserDept().then((res) => {
    //   ruleForm.value.createDeptId = res.data.id
    //   ruleForm.value.createDeptName = res.data.fullName
    // })
  }
}
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  $router.back()
}

// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  Promise.all([formEl.validate()]).then(() => {
    // 验证表格
    if (deviceRef.value.checkCertificateList()) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        ruleForm.value.equipmentList = deviceRef.value.list
        editReview(ruleForm.value).then((res) => {
          submitId.value = res.data
          if (statusName === '已取消' || statusName === '未通过') {
            submitReview({ id: submitId.value, formId: SCHEDULE.SUBCONTRACT_REVIEW_APPROVAL }).then((res) => {
              ElMessage.success('已提交')
              close()
            })
          }
          else {
            ElMessage.success('保存成功')
          }
        })
      })
    }
  })
}
// 提交
const submitForm = () => {
  if (submitId.value === '') {
    ElMessage.warning('请先保存')
    return false
  }
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitReview({ id: submitId.value, formId: SCHEDULE.SUBCONTRACT_REVIEW_APPROVAL }).then((res) => {
      ElMessage.success('已提交')
      close()
    })
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
// 编辑
const editForm = () => {
  $router.push({
    path: '/reviewpage/update',
    query: { ...$route.query },
  })
}
// 删除
const delForm = () => {
  ElMessageBox.confirm(
    '确认删除吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteReview({ id: ruleForm.value.id }).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
// 取消
const cancelForm = () => {
  ElMessageBox.confirm(
    '确认取消吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelReview({ id: ruleForm.value.id, processInstanceId: ruleForm.value.processId, comments: '' }).then((res) => {
      ElMessage.success('操作成功')
      close()
    })
  })
}
// 审批
const approvalDialogRef = ref()
const apply = (type: string) => {
  const data = JSON.parse($route.query.row as string)
  approvalDialogRef.value.initDialog(type, JSON.parse($route.query.row as string).taskId, data.processId, ruleForm.value.id)
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ruleForm.value.attachment = res.data[0]
        // 重置当前验证
        ruleFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
const print = () => {

}
// 选择分包方
const subpackageRef = ref()
const selectSubpackage = () => {
  subpackageRef.value.initDialog()
}
// 确认分包方
const confirm = (subpackage: any) => {
  ruleForm.value.subcontractorNo = subpackage.subcontractorNo
  ruleForm.value.subcontractorId = subpackage.id
  ruleForm.value.subcontractorDirectorName = subpackage.directorName
  ruleForm.value.address = subpackage.address
  ruleForm.value.postcode = subpackage.postcode
  ruleForm.value.fax = subpackage.fax
  ruleForm.value.subcontractorCompanyName = subpackage.companyName
}
</script>

<template>
  <app-container style="overflow: hidden;">
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <!-- 分包方弹窗 -->
    <subpackage-dialog ref="subpackageRef" @add="confirm" />
    <detail-page class="base-info-device" :title="`测试、校准或检定工作分包评审表-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="statusName === '待审批'" type="primary" @click="apply('agree')">
          同意
        </el-button>
        <el-button v-if="statusName === '待审批'" type="primary" @click="apply('refuse')">
          拒绝
        </el-button>
        <el-button v-if="editBtn(statusName, dialogStatus)" type="primary" @click="editForm()">
          编辑
        </el-button>
        <el-button v-if="submitBtn(statusName, dialogStatus) && statusName !== '已取消' && statusName !== '未通过'" type="primary" @click="submitForm()">
          提交
        </el-button>
        <el-button v-if="submitBtn(statusName, dialogStatus)" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button v-if="delTextBtn(statusName)" type="info" @click="delForm()">
          删除
        </el-button>
        <el-button v-if="statusName === '审批中'" type="info" @click="cancelForm()">
          取消
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form
        ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="126px" class="form"
        :class="[dialogStatus === 'detail' ? 'isDetail' : '']" :disabled="$route.path.includes('detail')"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="评审表编号" prop="reviewNo">
              <el-input v-model.trim="ruleForm.reviewNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="评审表名称" prop="reviewName">
              <el-input v-model.trim="ruleForm.reviewName" placeholder="评审表名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人" prop="createUserName">
              <el-input v-model.trim="ruleForm.createUserName" placeholder="申请人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请时间" prop="createTime">
              <el-date-picker
                v-model="ruleForm.createTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="申请时间" class="normal-date" style="width: 100%;" disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="分包方编号" prop="subcontractorNo">
              <el-input v-model.trim="ruleForm.subcontractorNo" placeholder="分包方编号" @focus="selectSubpackage">
                <template v-if="!$route.path.includes('detail')" #append>
                  <span @click="selectSubpackage">选择</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分包机构名称" prop="subcontractorCompanyName">
              <el-input v-model.trim="ruleForm.subcontractorCompanyName" placeholder="分包机构名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="机构负责人" prop="subcontractorDirectorName">
              <el-input v-model.trim="ruleForm.subcontractorDirectorName" placeholder="机构负责人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="地址" prop="address">
              <el-input v-model.trim="ruleForm.address" placeholder="地址" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="邮编" prop="postcode">
              <el-input v-model.trim="ruleForm.postcode" placeholder="邮编" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传真" prop="fax">
              <el-input v-model.trim="ruleForm.fax" placeholder="传真" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model.trim="ruleForm.contact" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model.trim="ruleForm.contactNumber" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="预计开始时间" prop="predictStartTime">
              <el-date-picker
                v-model="ruleForm.predictStartTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择开始时间" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计结束时间" prop="predictEndTime">
              <el-date-picker
                v-model="ruleForm.predictEndTime" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" placeholder="请选择结束时间" class="normal-date" style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分包原因" prop="subcontractReason">
              <el-select v-model="ruleForm.subcontractReason" placeholder="请选择分包原因" style="width: 100%;">
                <el-option v-for="item in reasonList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计费用" prop="predictPrice">
              <el-input v-model.trim="ruleForm.predictPrice" placeholder="请输入预计费用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="实验室认可情况" prop="labAccreditation">
              <el-input v-model.trim="ruleForm.labAccreditation" placeholder="请输入实验室认可情况" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="溯源性" prop="traceability">
              <el-input v-model.trim="ruleForm.traceability" placeholder="请输入溯源性" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="测试方法" prop="testMethod">
              <el-input v-model.trim="ruleForm.testMethod" placeholder="请输入测试方法" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="技术能力" prop="technicalAbility">
              <el-input v-model.trim="ruleForm.technicalAbility" placeholder="请输入技术能力" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="ruleForm.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="附件" prop="attachment">
              <show-photo :minio-file-name="ruleForm.attachment" />
              <input ref="fileRef" style="display: none;" type="file" @change="onFileChange">
              <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload">
                上传
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com>
      <device-table ref="deviceRef" :data="ruleForm.equipmentList" :status="dialogStatus" />
    </detail-block-com>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      content: "";
      display: none;
    }
  }
}
</style>
