<!-- 批量分发弹窗 -->
<script lang="ts" setup name="BatchDistributeDialog">
import type { FormInstance, FormRules } from 'element-plus'
import { ElLoading, ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import chooseLab from './chooseLab.vue'
import selectStaff from './selectStaff.vue'
import { batchAllocateLab, batchExecute } from '@/api/business/schedule/task'
const emit = defineEmits(['onSuccess'])
// 退回成功方法
const dialogVisible = ref(false) // 弹窗显示状态
const formData = ref({ // 默认表单
  measurePersonId: '', // 检定人员id
  measurePerson: '', // 检定人员名称
  measureSegmentId: '', // 检定环节id
  measureSegment: '', // 检定环节名称
  requireCertifications: undefined, // 应出具证书数量
})
const btnLoading = ref(false) // 保存按钮加载状态
const list = ref([]) // 选择设备
const moduleType = ref('') // 模块类型
// ---------------------------------表单提交---------------------------------------------
const dataFormRef = ref<FormInstance>() // 表单对象
const rules = reactive<FormRules>({ // 校验规则
  measureSegmentId: [{ required: true, message: '检定环节必填', trigger: ['blur', 'change'] }],
  measurePersonId: [{ required: true, message: '检定人员必填', trigger: ['blur', 'change'] }],
  // requireCertifications: [{ required: true, message: '应出具证书必填', trigger: ['blur', 'change'] }],
})

// 提交表单
function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) { return }
  formEl.validate((valid) => {
    if (valid) {
      if (moduleType.value === 'task') {
        const params = list.value.map((item: { orderId: string; sampleId: string }) => {
          return {
            measureProcess: {
              measurePerson: formData.value.measurePerson,
              measurePersonId: formData.value.measurePersonId,
              measureSegment: formData.value.measureSegment,
              measureSegmentId: formData.value.measureSegmentId,
              measureSequence: 0,
              requireCertifications: formData.value.requireCertifications,
            },
            orderId: item.orderId,
            sampleId: item.sampleId,
          }
        })
        console.log('上传的参数', params)

        batchExecute(params).then(() => {
          ElMessage.success('批量分发完成')
          handleClose()
          emit('onSuccess')
        })
      }
      else if (moduleType.value === 'lab') {
        const params = list.value.map((item: { id: string }) => {
          return {
            measurePersonId: formData.value.measurePersonId,
            id: item.id,
            requireCertifications: formData.value.requireCertifications,
          }
        })

        batchAllocateLab(params).then(() => {
          ElMessage.success('批量分配完成')
          handleClose()
          emit('onSuccess')
        })
      }
    }
  })
}

// ------------------------------------------弹窗操作------------------------------------
/**
 * 初始化审批弹窗
 * @param val 选中的样品列表
 * @param moduleType 模块类型 默认任务分发 task  部门检测lab
 */
function initDialog(val: any, moduleTypeParam = 'task') {
  list.value = val
  dialogVisible.value = true
  moduleType.value = moduleTypeParam
  if (moduleTypeParam === 'lab') { // 部门检测
    formData.value.measureSegment = val[0].currentSegment
    formData.value.measureSegmentId = val[0].currentSegmentId
  }
  nextTick(() => {
    if (dataFormRef.value) { dataFormRef.value!.resetFields() } // 重置该表单项，将其值重置为初始值，并移除校验结果
  })
}

// 关闭弹窗
function handleClose() {
  dialogVisible.value = false
  formData.value = { // 默认表单
    measurePersonId: '', // 检定人员id
    measurePerson: '', // 检定人员名称
    measureSegmentId: '', // 检定环节id
    measureSegment: '', // 检定环节名称
    requireCertifications: undefined, // 应出具证书数量
  }
}
// ------------------------------------选择实验室---------------------------------------------
const chooseLabDialog = ref()
// 点击选择实验室
const selectMeasureSegment = () => {
  chooseLabDialog.value.initDialog(false)
}
// 实验室选择完毕
const chooseOver = (lab: any) => {
  formData.value.measureSegmentId = lab.deptId
  formData.value.measureSegment = lab.organizeName
}
// ------------------------------------选择检定人员---------------------------------------------
const choosePersonShow = ref(false)
// 点击选择人员
const selectPerson = () => {
  choosePersonShow.value = true
}
// 人员选择完毕
const choosePersonOver = (person: { id: string; name: string }) => {
  console.log('人员选择完毕', person)
  formData.value.measurePersonId = person.id
  formData.value.measurePerson = person.name
  choosePersonShow.value = false
}
// ------------------------------------- 以下是暴露的方法内容 ------------------------------------
defineExpose({ initDialog })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="批量分发"
    width="600"
    :before-close="handleClose"
  >
    <el-form
      ref="dataFormRef"
      label-position="top"
      label-width="80px"
      :model="formData"
      :rules="rules"
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="检定环节" prop="measureSegmentId">
            <el-input
              v-model="formData.measureSegment"
              placeholder="请选择"
              disabled
            >
              <template v-if="moduleType === 'task'" #append>
                <el-button
                  size="small"
                  @click="selectMeasureSegment"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="检定人员" :prop="moduleType === 'lab' ? 'measurePersonId' : null">
            <el-input
              v-model="formData.measurePerson"
              placeholder="请选择"
              disabled
            >
              <template #append>
                <el-button
                  size="small"
                  :disabled="!formData.measureSegmentId"
                  @click="selectPerson"
                >
                  选择
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应出具证书" :prop="moduleType === 'lab' ? 'requireCertifications' : null">
            <el-input-number v-model="formData.requireCertifications" :min="1" :step="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :loading="btnLoading" @click="submitForm(dataFormRef)">
        确定
      </el-button>
      <el-button type="info" @click="handleClose">
        取消
      </el-button>
    </template>
  </el-dialog>
  <!-- 选择实验室弹窗 -->
  <choose-lab ref="chooseLabDialog" @confirm-checkout="chooseOver" />
  <!-- 成员弹框 -->
  <select-staff ref="_selectStaffDialog" v-model:visible="choosePersonShow" :data="[formData.measurePersonId]" :dept-id="formData.measureSegmentId" :dept-name="formData.measureSegment" :multi="false" @change="choosePersonOver" />
</template>

<style lang="scss" scoped>
// 样式
</style>
