<!-- 现场测试、校准或检定审批 基本信息 -->
<script name="FieldTestApproveBasic" lang="ts" setup>
import type { Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import dayjs from 'dayjs'
import type { IForm } from '../approve-interface'
import SelectStaffDialog from '../dialog/selectStaffDialog.vue'
import SelectEquipmentDialog from '../dialog/selectEquipmentDialog.vue'
import SelectCustomerDialog from '../dialog/selectCustomerDialog.vue'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import type { dictType } from '@/global'
import type { IAddress } from '@/components/AddressSelect/address-interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import useUserStore from '@/store/modules/user'
import { addFieldTestApproval, failUpdateFieldTestApproval, getInfo, submit, updateFieldTestApproval } from '@/api/business/fieldTest/approve'
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>({
  labCode: '', // 实验室代码
  groupCode: '', // 组别代码
  siteExecutiveNo: '', // 现场检测编号(审批编号)
  siteExecutiveName: '', // 现场检测名字(审批名称)
  applyId: '', // 申请人id
  applyName: '', // 申请人
  applyPersonName: '', // 申请人名称
  applyTime: '', // 申请时间
  customerId: '', // 委托方id
  customerNo: '', // 委托方编号
  customerName: '', // 委托方名称
  contacts: '', // 联系人
  mobile: '', // 委托方电话
  address: '', // 委托方地址
  executiveItem: '', // 现场测试、校准或检定项目
  executiveAddress: '', // 检测地址
  executiveEnvironment: '', // 现场环境条件
  remark: '', // 备注
  processId: '', // 流程实例id
})
const ruleFormRef = ref() // 表单ref
const loading = ref(false) // loading
const infoId = ref('') // id
const formRules = ref<FormRules>({ // 校验规则
  executiveAddress: [{ required: true, message: '测试、校准或检定地点不能为空', trigger: ['blur', 'change'] }],
  executiveEnvironment: [{ required: true, message: '现场环境条件不能为空', trigger: ['blur', 'change'] }],
  executiveItem: [{ required: true, message: '现场测试、校准或检定项目不能为空', trigger: ['blur', 'change'] }],
  customerNo: [{ required: true, message: '委托方编号不能为空', trigger: ['blur', 'change'] }],
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
})
// -----------------------------------------字典--------------------------------------------------------------
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
  })
}

// --------------------------------------检定人员-------------------------------------------------
const staffColumns = [ // 表头
  { text: '姓名', value: 'staffName', align: 'center' },
  { text: '计量人员编号', value: 'staffNo', align: 'center', width: '160' },
  { text: '工作部门', value: 'deptName', align: 'center' },
  { text: '计量专业', value: 'major', align: 'center' },
  { text: '证书编号', value: 'certificateNumber', align: 'center' },
  { text: '证书有效期', value: 'validDate', align: 'center', width: '120' },
]
const staffList = ref([]) as any// 表格数据
const checkoutStaffList = ref([]) as any // 选中数据
const selectStaffDialogRef = ref() // 选择计量人员组件ref
// 选中
const handleSelectionStaffChange = (e: any) => {
  checkoutStaffList.value = e
}
// 批量添加
const multiAddMeterPerson = () => {
  selectStaffDialogRef.value.initDialog()
}

// 确定选择计量人员
const confirmSelectStaff = (list = []) => {
  list.forEach((item: { id: string }) => {
    // 只添加列表里不存在的
    const index = staffList.value.findIndex((i: { id: string }) => item.id === i.id)
    if (index === -1) {
      staffList.value.push(item)
    }
  })
}
// 删除
const delStaffRow = () => {
  if (!checkoutStaffList.value.length) {
    ElMessage.warning('请选中要删除的行')
  }
  else {
    staffList.value = staffList.value.filter((item: any) => {
      return !checkoutStaffList.value.includes(item)
    })
  }
}
// --------------------------------------携带仪器设备-------------------------------------------------
const equipmentColumns = [ // 表头
  { text: '统一编号', value: 'equipmentNo', align: 'center', width: '160' },
  { text: '设备名称', value: 'equipmentName', align: 'center' },
  { text: '型号规格', value: 'model', align: 'center' },
  { text: '检定有效期', value: 'measureValidDate', align: 'center', width: '120' },
  { text: '所属部门', value: 'deptName', align: 'center' },
]
const equipmentList = ref([]) as any// 表格数据
const checkoutEquipmentList = ref([]) as any // 选中数据
const selectEquipmentDialogRef = ref() // 选择设备组件ref
// 选中
const handleSelectionEquipmentChange = (e: any) => {
  checkoutEquipmentList.value = e
}
// 批量添加
const multiAddEquipment = () => {
  selectEquipmentDialogRef.value.initDialog()
}

// 确定选择设备
const confirmSelectEquipment = (list = []) => {
  list.forEach((item: { id: string; measureValidDate: string }) => {
    // 只添加列表里不存在的
    const index = equipmentList.value.findIndex((i: { id: string }) => item.id === i.id)
    if (index === -1) {
      item.measureValidDate = item.measureValidDate ? dayjs(item.measureValidDate).format('YYYY-MM-DD') : item.measureValidDate
      equipmentList.value.push(item)
    }
  })
}
// 删除
const delEquipmentRow = () => {
  if (!checkoutEquipmentList.value.length) {
    ElMessage.warning('请选中要删除的行')
  }
  else {
    equipmentList.value = equipmentList.value.filter((item: any) => {
      return !checkoutEquipmentList.value.includes(item)
    })
  }
}
// --------------------------------------选择委托方-------------------------------------------------
const selectCustomerDialogRef = ref() // 选择委托方组件ref
// 点击选择委托方
const selectCustomer = () => {
  selectCustomerDialogRef.value.initDialog()
}
// 确定选择委托方
const confirmSelectCustomer = (list: any) => {
  const tempValue = list[0]
  form.value.customerId = tempValue.id// 委托方id
  form.value.customerNo = tempValue.customerNo // 委托方编号
  form.value.customerName = tempValue.customerName // 委托方名称
  form.value.contacts = tempValue.contacts // 联系人
  form.value.mobile = tempValue.mobile // 委托方电话
  form.value.address = tempValue.address // 委托方地址
}
// -----------------------------------------------保存-------------------------------------------
/**
 * 点击保存
 * @param formEl 基本信息表单ref
 */
const saveForm = async () => {
  if (!staffList.value.length) {
    ElMessage.warning('测试、校准或检定人员不能为空')
    return false
  }
  if (!equipmentList.value.length) {
    ElMessage.warning('携带仪器设备不能为空')
    return false
  }
  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.8)',
        })
        const equipmentIdList = equipmentList.value.map((item: { id: string }) => item.id)
        const staffIdList = staffList.value.map((item: { id: string }) => item.id)
        const params = {
          ...form.value,
          staffIdList,
          equipmentIdList,
        }
        if (props.pageType === 'add') { // 新建
          addFieldTestApproval(params).then((res) => {
            loading.close()
            form.value.siteExecutiveNo = res.data.siteExecutiveNo // 审批编号
            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 === '全部') {
            updateFieldTestApproval(params).then((res) => {
              loading.close()
              emits('addSuccess', infoId.value)
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
          else { // '未通过' || '已取消'
            failUpdateFieldTestApproval(params).then((res) => {
              loading.close()
              emits('submitSuccess')
              ElMessage.success('已保存')
            }).catch(() => {
              loading.close()
            })
          }
        }
      })
    }
  })
}

// ----------------------------------------------提交--------------------------------------------
// 提交
/**
 *
 * @param processId 流程实例id
 * @param 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.FIELD_TEST_APPROVAL, processId }).then((res) => {
    ElMessage.success('已提交')
    emits('submitSuccess')
    loading.close()
  })
}
// -----------------------------------------获取详情------------------------------------------
// 获取详情
const fetchInfo = () => {
  loading.value = true
  getInfo({ id: infoId.value }).then((res) => {
    loading.value = false
    form.value = res.data
    equipmentList.value = res.data.equipmentInfoList.map((item: { measureValidDate: string }) => {
      return {
        ...item,
        measureValidDate: item.measureValidDate ? dayjs(item.measureValidDate).format('YYYY-MM-DD') : item.measureValidDate,
      }
    }) // 设备
    staffList.value = res.data.meterStaffList // 人员
  })
}
// ---------------------------------------------钩子----------------------------------------------
watch(() => props.id, (newValue) => {
  infoId.value = newValue!
  if (infoId.value) {
    fetchInfo() // 获取详情信息
  }
}, { immediate: true })

onMounted(async () => {
  await getDict()
  form.value.siteExecutiveName = '现场测试、校准或检定审批' // 现场检测审批名字
  form.value.applyId = user.id// 申请人id
  form.value.applyName = user.name // 申请人名字
  form.value.applyTime = dayjs().format('YYYY-MM-DD HH-mm:ss')// 申请时间
  if (props.pageType !== 'add' && infoId.value) {
    fetchInfo() // 获取详情信息
  }
})

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

<template>
  <detail-block v-loading="loading" title="">
    <el-form
      ref="ruleFormRef"
      :model="form"
      :label-width="200"
      label-position="right"
      :rules="formRules"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <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="8">
          <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="8">
          <el-form-item label="审批编号:" prop="siteExecutiveNo">
            <el-input v-model="form.siteExecutiveNo" disabled placeholder="系统自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="审批名称:" prop="siteExecutiveName">
            <el-input
              v-model="form.siteExecutiveName"
              :placeholder="pageType === 'detail' ? '' : '请输入现场检测名称'"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人:">
            <el-input
              v-model="form.applyName" disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请时间:" prop="applyTime">
            <el-date-picker
              v-model="form.applyTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托方编号:" prop="customerNo">
            <el-input
              v-model="form.customerNo"
              :placeholder="pageType === 'detail' ? '' : '请选择委托方编号'"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            >
              <template v-if="pageType !== 'detail'" #append>
                <el-button size="small" @click="selectCustomer">
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="委托方名称:" prop="customerName">
            <el-input
              v-model="form.customerName"
              placeholder="委托方名称"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人" prop="contacts">
            <el-input
              v-model="form.contacts"
              placeholder="请输入联系人"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系方式" prop="mobile">
            <el-input
              v-model="form.mobile"
              placeholder="联系方式"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="委托方地址:" prop="address">
            <el-input
              v-model="form.address"
              type="textarea"
              autosize
              placeholder="委托方地址"
              :class="{ 'detail-input': pageType === 'detail' }"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="现场测试、校准或检定项目:" prop="executiveItem">
            <el-input
              v-model="form.executiveItem"
              :placeholder="pageType === 'detail' ? ' ' : '请输入现场测试、校准或检定项目'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="测试、校准或检定地点:" prop="executiveAddress">
            <el-input
              v-model="form.executiveAddress"
              :placeholder="pageType === 'detail' ? '' : '请输入测试、校准或检定地点'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="现场环境条件:" prop="executiveEnvironment">
            <el-input
              v-model="form.executiveEnvironment"
              :placeholder="pageType === 'detail' ? ' ' : '请输入现场环境条件'"
              :disabled="pageType === 'detail'"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="form.remark"
              autosize
              type="textarea"
              :disabled="pageType === 'detail'"
            />
          </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="multiAddMeterPerson">
        批量添加
      </el-button>
      <el-button type="info" @click="delStaffRow">
        删除行
      </el-button>
    </template>
    <el-table
      :data="staffList"
      border
      style="width: 100%;"
      @selection-change="handleSelectionStaffChange"
    >
      <el-table-column v-if="pageType !== 'detail'" type="selection" width="55" />
      <el-table-column align="center" label="序号" width="80" type="index" />
      <el-table-column
        v-for="item in staffColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        :width="item.width"
        show-overflow-tooltip
        align="center"
      />
    </el-table>
  </detail-block>
  <detail-block title="携带仪器设备">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="multiAddEquipment">
        批量添加
      </el-button>
      <el-button type="info" @click="delEquipmentRow">
        删除行
      </el-button>
    </template>
    <el-table
      :data="equipmentList"
      border
      style="width: 100%;"
      @selection-change="handleSelectionEquipmentChange"
    >
      <el-table-column v-if="pageType !== 'detail'" type="selection" width="55" />
      <el-table-column align="center" label="序号" width="80" type="index" />
      <el-table-column
        v-for="item in equipmentColumns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        :width="item.width"
        align="center"
      />
    </el-table>
  </detail-block>

  <!-- 选择计量人员  -->
  <select-staff-dialog ref="selectStaffDialogRef" @confirm="confirmSelectStaff" />
  <!-- 选择设备台账 -->
  <select-equipment-dialog ref="selectEquipmentDialogRef" @confirm="confirmSelectEquipment" />
  <!-- 选择委托方  -->
  <select-customer-dialog ref="selectCustomerDialogRef" @confirm="confirmSelectCustomer" />
</template>
