<!-- 现场检测审批详情 -->
<script lang="ts" setup name="FieldTestRecordDetail">
import { ref } from 'vue'
import dayjs from 'dayjs'
import { ElLoading, ElMessage } from 'element-plus'
import selectApproveList from './dialog/selectFieldTestApprove.vue'
import type { IForm } from './record-interface'
import { getStaffList } from '@/api/resource/register'
import useUserStore from '@/store/modules/user'
import { getDictByCode } from '@/api/system/dict'
import type { dictType } from '@/global'
import { useCheckList } from '@/commonMethods/useCheckList'
import { getInfo } from '@/api/business/fieldTest/approve'
import { addFieldTestRecordList, getRecordDetail, updateFieldTestRecord } from '@/api/business/fieldTest/record'
// import type { IOptions } from '@/views/device/standardEquipment/standard_interface'
const user = useUserStore() // 用户信息
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const $router = useRouter() // 关闭页面使用
const $route = useRoute() // 路由参数
const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // 列表id
const ruleFormRef = ref() // 表单ref
const staffPersonList = ref([]) as any// 记录人列表（用户）
const staffPersonOptions = ref([]) as any// 记录人列表（用户）--模糊搜索数据
const applyPersonLoading = ref(false) // 申请人模糊搜索框loading
const form = ref<IForm>({
  labCode: '', // 实验室代码
  groupCode: '', // 组别代码
  groupCodeName: '',	// 组别代码(字典value)
  logNo: '', // 记录单编号
  logName: '', // 记录单名称
  createUserId: '', // 创建人id
  createUserName: '', // 创建人名称
  createTime: '', // 创建时间
  siteExecutiveId: '', // 现场检测id
  siteExecutiveNo: '', // 现场测试、校准或检定审批单编号
  customerName: '', // 委托方名称
  address: '', // 委托方地址
  contacts: '', // 联系人
  mobile: '', // 联系方式
  executiveAddress: '', // 现场工作地点
  outputVoltage: '', // 供电电压
  zeroGroundVoltage: '', // 零地电压
  temperature: '', // 温度
  humidity: '', // 湿度
  remark: '', // 备注
  siteExecutiveEquipmentRelationList: [] as any, // 仪器设备表
})
const list = ref([]) // 记录结果表
// 校验规则
const formRules = ref({
  labCode: [{ required: true, message: '实验室代码不能为空', trigger: ['blur', 'change'] }],
  groupCode: [{ required: true, message: '组别代码不能为空', trigger: ['blur', 'change'] }],
  siteExecutiveNo: [{ required: true, message: '现场检测编号必填', trigger: ['blur', 'change'] }],
  executiveAddress: [{ required: true, message: '现场工作地点必填', trigger: ['blur', 'change'] }],
  outputVoltage: [{ required: true, message: '供电电压必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '供电电压只能为数字', trigger: ['blur', 'change'] }],
  zeroGroundVoltage: [{ required: true, message: '零地电压必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '零地电压只能为数字', trigger: ['blur', 'change'] }],
  temperature: [{ required: true, message: '温度必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '温度只能为数字', trigger: ['blur', 'change'] }],
  humidity: [{ required: true, message: '相对湿度必填', trigger: ['blur', 'change'] },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '相对湿度只能为数字', trigger: ['blur', 'change'] }],
})

const equipmentColumns = [ // 仪器设备表头
  { text: '工作开始前外观及功能检查', value: 'beforeWorkCheck', required: true },
  { text: '工作开始前指标测试结果', value: 'beforeWorkResult', required: true },
  { text: '工作开始前记录人', value: 'beforeWorkRecorderId', required: true },
  { text: '工作开始前记录时间', value: 'beforeWorkRecorderDate', required: true },
  { text: '工作开始后外观及功能检查', value: 'afterWorkCheck', required: true },
  { text: '工作开始后指标测试结果', value: 'afterWorkResult', required: true },
  { text: '工作开始后记录人', value: 'afterWorkRecorderId', required: true },
  { text: '工作开始后记录时间', value: 'afterWorkRecorderDate', required: true },
]
// -------------------------------------------字典------------------------------------------
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表
const labCodeList = ref<dictType[]>([]) // 实验室代码
const groupCodeList = ref<dictType[]>([]) // 组别代码
// 获取字典值
async function getDict() {
  // 实验室代码
  getDictByCode('bizLabCode').then((response) => {
    labCodeList.value = response.data
  })
  // 组别代码
  getDictByCode('bizGroupCode').then((response) => {
    groupCodeList.value = response.data
  })

  // 专业组
  const res = await getDictByCode('bizGroupCode')
  groupCodeList.value = res.data

  // 获取用户列表
  const resStaffList = await getStaffList({ offset: 1, limit: 999999 })
  userList.value = resStaffList.data.rows
}
// ----------------------------------路由参数--------------------------------------------
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  console.log(pageType.value)

  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
// ------------------------------------选择现场检测编号-------------------------------------------------
const approveListRef = ref()
const selectFieldTestApprove = () => {
  approveListRef.value.initDialog()
}
// 选择好了现场检测
const confirmSelectApproveList = (val: any) => {
  getInfo({ id: val[0].id }).then((res) => {
    form.value.siteExecutiveNo = res.data.siteExecutiveNo// 现场检测编号
    form.value.siteExecutiveId = res.data.id// 现场检测id
    form.value.customerName = res.data.customerName // 委托方名称
    form.value.address = res.data.address // 委托方地址
    // form.value.phone = res.data.phone // 委托方电话
    form.value.contacts = res.data.contacts // 联系人
    form.value.mobile = res.data.mobile // 送样人联系方式
    form.value.executiveAddress = form.value.executiveAddress ? form.value.executiveAddress : res.data.executiveAddress // 现场检测地址
    list.value = res.data.equipmentInfoList.map((item: any) => {
      return {
        equipmentId: item.id, // 设备id
        siteExecutiveId: res.data.id, // 现场检测审批id
        equipmentModel: item.model, // 设备型号
        equipmentNo: item.equipmentNo, // 设备编号
        equipmentName: item.equipmentName, // 设备名称
      }
    })
  })
}
// -------------------------------------------------------------------------------------

// ---------------------------------------------记录人-----------------------------------
// 查询条件
const staffListQuery = ref({
  staffNo: '', // 人员编号
  name: '', // 姓名
  deptId: '', // 所在部门
  limit: 20,
  offset: 1,
})
// 获取计量人员列表(增加模糊查询)
const fetchStaffList = () => {
  getStaffList(staffListQuery.value).then((res: any) => {
    staffPersonList.value = res.data.records
    staffPersonOptions.value = res.data.records
  })
}

// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 获取详情信息
const fetchInfo = () => {
  const loading = ElLoading.service({
    lock: true,
    background: 'rgba(255, 255, 255, 0.8)',
  })
  getRecordDetail({ id: infoId.value }).then((res) => {
    form.value = res.data
    list.value = res.data.siteExecutiveEquipmentRelationList
    form.value.createUserId = user.id// 创建人
    form.value.createUserName = user.name // 创建人名称
    form.value.logName = '现场检测记录单' // 记录单名称
    loading.close()
  })
}

// 保存
const save = () => {
  if (!useCheckList(list.value, equipmentColumns, '仪器设备')) {
    return false
  }
  ruleFormRef.value!.validate((valid: boolean) => {
    if (valid) {
      const loading = ElLoading.service({
        lock: true,
        background: 'rgba(255, 255, 255, 0.8)',
      })
      // 新建
      form.value.siteExecutiveEquipmentRelationList = list.value
      if (pageType.value === 'add') { // 新建
        addFieldTestRecordList(form.value).then((res) => {
          ElMessage.success('保存成功')
          form.value.logNo = res.data // 记录表单号
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
      // 保存
      else if (pageType.value === 'edit') { // 编辑
        updateFieldTestRecord({ ...form.value, id: infoId.value }).then((res) => {
          ElMessage.success('保存成功')
          pageType.value = 'detail'
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }
    }
    else {
      console.log('表单校验不通过')
    }
  })
}

onMounted(async () => {
  getDict().then(() => {
    // await fetchStaffList()
    form.value.createUserId = user.id// 创建人
    form.value.createUserName = user.name // 创建人名字
    form.value.logName = '现场检测记录单' // 记录单名称
    form.value.createTime = dayjs().format('YYYY-MM-DD HH-mm:ss')// 创建时间
    if (pageType.value !== 'add') {
      fetchInfo()
    }
  })
})
</script>

<template>
  <app-container class="fieldtest-record-detail">
    <detail-page :title="`现场检测记录-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="save">
          保存
        </el-button>
        <!-- <el-button v-if="pageType === 'detail'" type="primary" @click="print">
          打印
        </el-button> -->
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="form"
        label-width="240"
        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="logNo">
              <el-input v-model="form.logNo" class="full-width-input" disabled placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="记录单表称:" prop="logName">
              <el-input v-model="form.logName" class="full-width-input" disabled placeholder="请输入记录单名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人:" prop="createUserName">
              <el-input
                v-model="form.createUserName"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? '' : '创建人'"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间:" prop="createTime">
              <el-date-picker
                v-model="form.createTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                class="full-width-input"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="现场测试、校准或检定审批单编号:" prop="siteExecutiveNo">
              <el-input v-model="form.siteExecutiveNo" class="full-width-input" disabled placeholder="请选择">
                <template v-if="pageType !== 'detail'" #append>
                  <el-button size="small" @click="selectFieldTestApprove">
                    选择
                  </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"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? '' : '委托方名称'"
                :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"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? '' : '联系人'"
                :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"
                class="full-width-input"
                :placeholder="pageType === 'detail' ? '' : '联系方式'"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="委托方地址:" prop="address">
              <el-input
                v-model="form.address"
                class="full-width-input"
                type="textarea"
                autosize
                :placeholder="pageType === 'detail' ? '' : '委托方地址'"
                :class="{ 'detail-input': pageType === 'detail' }"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="8">
            <el-form-item label="现场工作地点" prop="executiveAddress">
              <el-input
                v-model="form.executiveAddress"
                class="full-width-input"
                placeholder="请输入现场工作地点"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供电电压(V)" prop="outputVoltage">
              <el-input
                v-model="form.outputVoltage"
                class="full-width-input"
                placeholder="请输入供电电压"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="零地电压(V)" prop="zeroGroundVoltage">
              <el-input
                v-model="form.zeroGroundVoltage"
                class="full-width-input"
                placeholder="请输入零地电压"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="温度(℃)" prop="temperature">
              <el-input
                v-model="form.temperature"
                class="full-width-input"
                placeholder="请输入温度"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相对湿度(%)" prop="humidity">
              <el-input
                v-model="form.humidity"
                class="full-width-input"
                placeholder="请输入相对湿度"
                :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"
                class="full-width-input"
                autosize
                type="textarea"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="仪器设备">
      <el-table
        :data="list"
        style="width: 100%;"
      >
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          prop="equipmentName"
          label="设备名称"
          align="center"
        />
        <el-table-column
          prop="equipmentNo"
          label="设备编号"
          width="160"
          align="center"
        />
        <el-table-column
          prop="equipmentModel"
          label="型号"
          align="center"
        />
        <el-table-column label="工作开始前" align="center">
          <el-table-column
            prop="beforeWorkCheck"
            label="外观及功能检查"
            align="center"
            min-width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>外观及功能检查</span>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.beforeWorkCheck" type="textarea" autosize :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '请输入'" class="input" />
            </template>
          </el-table-column>
          <el-table-column
            prop="beforeWorkResult"
            label="指标测试结果"
            align="center"
            min-width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>指标测试结果</span>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.beforeWorkResult" type="textarea" autosize :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '请输入'" class="input" />
            </template>
          </el-table-column>
          <el-table-column
            prop="beforeWorkRecorderId"
            label="记录人"
            align="center"
            width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>记录人</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.beforeWorkRecorderId"
                :placeholder="pageType === 'detail' ? ' ' : '请选择'"
                class="full-width-input"
                :disabled="pageType === 'detail'"
                filterable
                :loading="applyPersonLoading"
              >
                <el-option v-for="item in userList" :key="item.id" :label="item.staffName" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="beforeWorkRecorderDate"
            label="记录时间"
            align="center"
            width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>记录时间</span>
            </template>
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.beforeWorkRecorderDate"
                type="datetime"
                :placeholder="pageType === 'detail' ? ' ' : '请选择'"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                class="full-width-input"
                :disabled="pageType === 'detail'"
              />
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="工作开始后" align="center">
          <el-table-column
            prop="afterWorkCheck"
            label="外观及功能检查"
            align="center"
            min-width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>外观及功能检查</span>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.afterWorkCheck" type="textarea" autosize :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '请输入'" class="input" />
            </template>
          </el-table-column>
          <el-table-column
            prop="afterWorkResult"
            label="指标测试结果"
            align="center"
            min-width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>指标测试结果</span>
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.afterWorkResult" type="textarea" autosize :disabled="pageType === 'detail'" :placeholder="pageType === 'detail' ? ' ' : '请输入'" class="input" />
            </template>
          </el-table-column>
          <el-table-column
            prop="afterWorkRecorderId"
            label="记录人"
            align="center"
            width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>记录人</span>
            </template>
            <template #default="scope">
              <el-select
                v-model="scope.row.afterWorkRecorderId"
                :placeholder="pageType === 'detail' ? ' ' : '请选择'"
                class="full-width-input"
                :disabled="pageType === 'detail'"
                filterable
                :loading="applyPersonLoading"
              >
                <el-option v-for="item in userList" :key="item.id" :label="item.staffName" :value="item.id" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            prop="afterWorkRecorderDate"
            label="记录时间"
            align="center"
            width="180"
          >
            <template #header>
              <span style="color: red;">*</span><span>记录时间</span>
            </template>
            <template #default="scope">
              <el-date-picker
                v-model="scope.row.afterWorkRecorderDate"
                type="datetime"
                :placeholder="pageType === 'detail' ? ' ' : '请选择'"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                class="full-width-input"
                :disabled="pageType === 'detail'"
              />
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </detail-block>
    <!-- 选择现场检测编号 -->
    <select-approve-list ref="approveListRef" @add="confirmSelectApproveList" />
  </app-container>
</template>

<style lang="scss">
.fieldtest-record-detail {
  .el-table thead.is-group th.el-table__cell {
    background: #f2f6ff;
  }
}
</style>
