<!-- 测试、校准或检定工作分包评审表 基本信息 -->
<script name="SubpackageReviewBasic" lang="ts" setup>
import dayjs from 'dayjs'
import type { FormRules } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { Ref } from 'vue'
import SelectOutsourcerNoDialog from '../dialog/selectOutsourcerNoDialog.vue'
import SelectEquipmentDialog from '../dialog/selectReceivedEquipmentDialog.vue'
import type { IForm } from '../review-interface'
import {
  addReview,
  failUpdateReview,
  getInfo,
  submit,
  updateReview,
} from '@/api/business/subpackage/Review'
import { getInfo as getDirectoriesDetail } from '@/api/business/subpackage/directories'
import { UploadFile } from '@/api/file'
import { getDictByCode } from '@/api/system/dict'
import showPhoto from '@/components/showPhoto/index.vue'
import type { dictType } from '@/global'
import useUserStore from '@/store/modules/user'
import { SCHEDULE } from '@/utils/scheduleDict'
const props = defineProps({
  pageType: {
    // 页面类型 add新建 edit编辑 detail详情
    type: String,
    requre: true,
    default: 'detail',
  },
  id: {
    type: String,
    requre: true,
  },
  approvalStatusName: {
    // 审批状态名称
    type: String,
    requre: true,
  },
})
const emits = defineEmits(['addSuccess', 'submitSuccess'])
const user = useUserStore() // 用户信息
const form: Ref<IForm> = ref({
  // 表单
  labCode: '', // 实验室代码
  groupCode: '', // 组别代码
  projectNo: '', // 评审表编号
  projectName: '', // 评审表名称
  formId: SCHEDULE.SUBPACKAGE_AUDIT_LIST_APPROVAL,
  applicantId: '', // 申请人
  applicantName: '', // 申请人名称
  applicantTime: '', // 申请时间
  outsourcerId: '', // 分包方id
  outsourcerNo: '', // 分包方编号
  outsourcerName: '', // 分包机构名称
  director: '', // 机构负责人
  postalCode: '', // 邮编
  fax: '', // 传真
  contacts: '', // 联系人
  mobile: '', // 联系电话
  preEndTime: '', // 预计结束时间
  preStartTime: '', // 预计开始时间
  outsourceReason: '', // 分包原因
  outsourceReasonName: '', // 原因名称
  preCost: '', // 预计费用
  approveSituation: '', // 实验室认可情况
  traceability: '', // 溯源性
  testMethod: '', // 测试方法
  techniqueAbility: '', // 技术能力
  remark: '', // 备注
  minioFileName: '', // 备注附件

  fullAddress: '', // 公司地址-详细地址
  addressArea: '', // 公司地址-区编码
  addressCity: '', // 公司地址-市编码
  addressCountry: '', // 公司地址-国家编码
  addressProvince: '', // 公司地址-省编码
  addressAreaName: '', // 公司地址-区
  addressCityName: '', // 公司地址-市
  addressCountryName: '', // 公司地址-国家
  addressProvinceName: '', // 公司地址-省
})
const fullAddress = ref<string[]>([]) // 公司地址
const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id

// 自定义校验规则--要求预计结束时间大于预计开始时间
const requireOverTimeValid = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('预计结束时间必填'))
  }
  if (
    new Date(form.value.preEndTime).getTime()
    <= new Date(form.value.preStartTime).getTime()
  ) {
    return callback(new Error('不能小于预计开始时间'))
  }
  callback()
}
const rules = ref<FormRules>({
  // 表单验证规则
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
  outsourcerNo: [{ required: true, message: '分包方编号不能为空', trigger: ['blur', 'change'] }],
  contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
  mobile: [{ required: true, message: '电话不能为空', trigger: 'blur' }],
  preStartTime: [{ required: true, message: '预计开始时间不能为空', trigger: ['blur', 'change'] }],
  preEndTime: [{ required: true, type: 'date', validator: requireOverTimeValid, trigger: 'change' }],
  outsourceReason: [{ required: true, message: '分包原因不能为空', trigger: ['blur', 'change'] }],
  preCost: [{ required: true, message: '预计费用不能为空', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '预计费用只能为数字', trigger: ['blur', 'change'] }],
  approveSituation: [{ required: true, message: '实验室认可情况不能为空', trigger: 'blur' }],
  traceability: [{ required: true, message: '溯源性不能为空', trigger: 'blur' }],
  testMethod: [{ required: true, message: '测试方法不能为空', trigger: 'blur' }],
  techniqueAbility: [{ required: true, message: '技术能力不能为空', trigger: 'blur' }],
})
// -------------------------------------------文件上传--------------------------------------
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        form.value.minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// ------------------------------------------字典----------------------------------------------
const outsourceReasonList = ref<dictType[]>([]) // 分包原因
const labCodeList = ref<dictType[]>([]) // 实验室代码
const groupCodeList = ref<dictType[]>([]) // 组别代码
function getDict() {
  // 实验室代码
  getDictByCode('bizLabCode').then((response) => {
    labCodeList.value = response.data
  })
  // 组别代码
  getDictByCode('bizGroupCode').then((response) => {
    groupCodeList.value = response.data
  })
  // 分包原因
  getDictByCode('outsourceReason').then((response) => {
    outsourceReasonList.value = response.data
  })
}
// ----------------------------------------选择分包方编号--------------------------------------
const selectOutsourcerNoDialogRef = ref() // 选择分包方组件ref
// 点击选择
const selectOutsourcerNo = () => {
  selectOutsourcerNoDialogRef.value.initDialog()
}

// 确定选择分包方
const confirmSelectOutsourcerNo = (val: any) => {
  console.log(val)
  form.value.outsourcerId = val[0].id // 分包方id
  form.value.outsourcerNo = val[0].outsourcerNo // 分包方编号
  form.value.outsourcerName = val[0].outsourcerName // 分包机构名称
  form.value.director = val[0].director // 机构负责人
  form.value.postalCode = val[0].postalCode // 邮编
  form.value.fax = val[0].fax // 传真
  fullAddress.value = [
    val[0].addressCountryName,
    val[0].addressProvinceName,
    val[0].addressCityName,
    val[0].addressAreaName,
    val[0].fullAddress,
  ]
}
// ---------------------------------------------受检设备信息表格-------------------------------
const list = ref([]) as any // 表格数据
const selectEquipmentRef = ref() // 选择设备组件ref
const checkoutList = ref([]) // 选中的内容

const columns = ref([
  { text: '受检设备编号', value: 'equipmentNo', align: 'center', width: '160' },
  { text: '受检设备名称', value: 'equipmentName', align: 'center' },
  { text: '型号', value: 'model', align: 'center' },
  { text: '出厂编号', value: 'manufactureNo', align: 'center' },
  { text: '任务单编号', value: 'orderNo', align: 'center', width: '160' },
  { text: '委托单位', value: 'customerName', align: 'center', width: '90' },
])

// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}

// 点击选择
const selectEquipment = (index: number) => {
  selectEquipmentRef.value.initDialog()
}

// 点击批量添加
const multiAdd = () => {
  selectEquipmentRef.value.initDialog()
}

// 选好设备
const clickConfirmEquipment = (val: any) => {
  console.log(val)

  val.forEach((item: any) => {
    // 只添加列表里不存在的
    const index = list.value.findIndex(
      (i: any) => item.equipmentNo === i.equipmentNo,
    )
    if (index === -1) {
      list.value.push(item)
    }
  })
}

// 删除行
const delRow = () => {
  if (checkoutList.value.length <= 0) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
  }
  else {
    checkoutList.value.forEach((item: any) => {
      list.value.forEach((element: { equipmentNo: string }, index: number) => {
        if (element.equipmentNo === item.equipmentNo) {
          list.value.splice(index, 1)
        }
      })
    })
  }
}
// -----------------------------------------其他方法------------------------------------------

// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    // loading.value = false
    form.value = res.data
    list.value = res.data.equipmentList
    getDirectoriesDetail({ id: res.data.outsourcerId }).then((response) => {
      loading.value = false
      fullAddress.value = [response.data.addressCountryName, response.data.addressProvinceName, response.data.addressCityName, response.data.addressAreaName, response.data.fullAddress]
    })
  })
}

// -----------------------------------------------保存---------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  await ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      // 基本信息表单通过校验
      ElMessageBox.confirm('确认保存吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const loading = ElLoading.service({
          lock: true,
          text: '加载中...',
          background: 'rgba(255, 255, 255, 0.6)',
        })
        const params = {
          ...form.value,
          orderSampleList: list.value.map(
            (item: { orderId: string; id: string }) => {
              return {
                orderId: item.orderId, // 委托书id
                sampleId: item.id, // 样品id、设备id
              }
            },
          ),
        }
        if (props.pageType === 'add') {
          // 新建
          addReview(params)
            .then((res) => {
              loading.close()
              form.value.outsourcerNo = res.data.outsourcerNo // 分包方编号
              infoId.value = res.data.id // id
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            })
            .catch(() => {
              loading.close()
            })
        }
        else if (props.pageType === 'edit') {
          // 编辑
          console.log(props.approvalStatusName)
          if (
            props.approvalStatusName === '草稿箱'
            || props.approvalStatusName === '全部'
          ) {
            updateReview(params)
              .then((res) => {
                loading.close()
                emits('addSuccess', infoId.value)
                ElMessage.success('已保存')
              })
              .catch(() => {
                loading.close()
              })
          }
          else {
            // '未通过' || '已取消'
            failUpdateReview(params)
              .then((res) => {
                loading.close()
                emits('submitSuccess')
                ElMessage.success('已保存')
              })
              .catch(() => {
                loading.close()
              })
          }
        }
      })
    }
  })
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param id // id
 */
const submitForm = (processId: string, id: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.6)',
  })
  submit({
    id,
    formId: SCHEDULE.SUBPACKAGE_AUDIT_LIST_APPROVAL,
    processId,
  }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}

// ---------------------------------------------钩子----------------------------------------------
watch(
  () => props.id, (newValue) => {
    infoId.value = newValue!
    if (infoId.value) {
      fetchInfo() // 获取详情信息
    }
  },
  { immediate: true },
)

onMounted(async () => {
  await getDict() // 获取字典
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
  if (props.pageType === 'add') {
    form.value.projectName = '测试、校准或检定工作分包评审表' // 评审表名称
    form.value.applicantId = user.id // 申请人id
    form.value.applicantName = user.name // 申请人名字
    form.value.applicantTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 申请时间
  }
})

defineExpose({ saveForm, submitForm })
</script>

<template>
  <detail-block v-loading="loading" title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="130"
      label-position="right"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="实验室代码" prop="labCode">
            <el-select
              v-model="form.labCode"
              :placeholder="pageType === 'detail' ? ' ' : '请选择实验室代码'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in labCodeList"
                :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="groupCode">
            <el-select
              v-model="form.groupCode"
              :placeholder="pageType === 'detail' ? ' ' : '请选择组别代码'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="item in groupCodeList"
                :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="projectNo">
            <el-input
              v-model="form.projectNo"
              :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="评审表名称:" prop="projectName">
            <el-input
              v-model.trim="form.projectName"
              :placeholder="pageType === 'detail' ? '' : '评审表名称'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请人:">
            <el-input v-model="form.applicantName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="申请时间:" prop="applicantTime">
            <el-input v-model="form.applicantTime" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包方编号:" prop="outsourcerNo">
            <el-input
              v-model="form.outsourcerNo"
              disabled
              :placeholder="pageType === 'detail' ? '' : '请选择分包方编号'"
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectOutsourcerNo">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包机构名称:" prop="outsourcerName">
            <el-input
              v-model="form.outsourcerName"
              :placeholder="pageType === 'detail' ? '' : '分包机构名称'"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="机构负责人:" prop="director">
            <el-input
              v-model="form.director"
              :placeholder="pageType === 'detail' ? '' : '机构负责人'"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="邮编:">
            <el-input
              v-model="form.postalCode"
              :placeholder="pageType === 'detail' ? ' ' : '邮编'"
              disabled
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="传真:">
            <el-input
              v-model="form.fax"
              :placeholder="pageType === 'detail' ? ' ' : '传真'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系人:" prop="contacts">
            <el-input
              v-model="form.contacts"
              :placeholder="pageType === 'detail' ? '' : '联系人'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系电话:" prop="mobile">
            <el-input
              v-model="form.mobile"
              :placeholder="pageType === 'detail' ? ' ' : '请输入联系电话'"
              :class="{ 'detail-input': pageType === 'detail' }"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计开始时间:" prop="preStartTime">
            <el-date-picker
              v-model="form.preStartTime"
              type="datetime"
              placeholder="请选择"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计结束时间:" prop="preEndTime">
            <el-date-picker
              v-model="form.preEndTime"
              type="datetime"
              placeholder="请选择"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分包原因:" prop="outsourceReason">
            <el-select
              v-model="form.outsourceReason"
              :placeholder="pageType === 'detail' ? '' : '请选择分包原因'"
              :disabled="pageType === 'detail'"
              class="full-width-input"
            >
              <el-option
                v-for="i in outsourceReasonList"
                :key="i.value"
                :label="i.name"
                :value="i.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="预计费用(元):" prop="preCost">
            <el-input
              v-model="form.preCost"
              placeholder="请输入预计费用"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="5">
        <el-form-item label="公司地址:">
          <address-select :data="fullAddress" :detail="true" />
        </el-form-item>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="实验室认可情况:" prop="approveSituation">
            <el-input
              v-model="form.approveSituation"
              type="textarea"
              autosize
              :placeholder="
                pageType === 'detail' ? ' ' : '请输入实验室认可情况'
              "
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="溯源性:" prop="traceability">
            <el-input
              v-model="form.traceability"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? ' ' : '请输入溯源性'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="测试方法:" prop="testMethod">
            <el-input
              v-model="form.testMethod"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? ' ' : '请输入测试方法'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="技术能力:" prop="techniqueAbility">
            <el-input
              v-model="form.techniqueAbility"
              type="textarea"
              autosize
              :placeholder="pageType === 'detail' ? ' ' : '请输入技术能力'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="备注:">
            <el-input
              v-model="form.remark"
              :placeholder="pageType === 'detail' ? '' : '请输入备注'"
              :disabled="pageType === 'detail'"
              :class="{ 'detail-input': pageType === 'detail' }"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="marg">
        <el-col :span="24">
          <el-form-item label="附件:">
            <show-photo v-if="form.minioFileName" :minio-file-name="form.minioFileName" />
            <span v-else-if="pageType === 'detail'">无</span>
            <input
              v-show="pageType === ''"
              ref="fileRef"
              type="file"
              @change="onFileChange"
            >
            <el-button
              v-if="pageType !== 'detail'"
              id="file"
              type="primary"
              :disabled="pageType === 'detail'"
              :style="{ 'margin-left': form.minioFileName === '' ? '0px' : '20px' }"
              @click="upload"
            >
              {{ form.minioFileName === '' ? '上传' : '更换附件' }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </detail-block>
  <detail-block title="受检设备信息">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="multiAdd">
        批量添加
      </el-button>
      <el-button type="info" @click="delRow">
        删除行
      </el-button>
    </template>
    <el-table
      :data="list"
      border
      style="width: 100%;"
      max-height="600"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="pageType !== 'detail'"
        type="selection"
        width="38"
      />
      <el-table-column align="center" label="序号" width="80" type="index" />
      <el-table-column
        v-for="item in columns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        :width="item.width"
        align="center"
      />
    </el-table>
  </detail-block>
  <!-- 选择设备组件 -->
  <select-equipment-dialog
    ref="selectEquipmentRef"
    :is-multi="true"
    @confirm="clickConfirmEquipment"
  />
  <!-- 选择分包方编号 -->
  <select-outsourcer-no-dialog
    ref="selectOutsourcerNoDialogRef"
    @confirm="confirmSelectOutsourcerNo"
  />
</template>
