<!-- 批量分发弹窗 -->
<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 { getDeptList } from '@/api/system/baseInfoDept'
import { getDictByCode } from '@/api/system/dict'
import { getStaffList } from '@/api/resource/register'
import { batchExecute } from '@/api/business/manager/task'

const emit = defineEmits(['onSuccess']) // 退回成功方法
const dialogVisible = ref(false) // 弹窗显示状态
const formData = ref({ // 默认表单
  measurePersonId: '', // 检定人员id
  measurePerson: '', // 检定人员名称
  measureSegmentId: '', // 检定环节id
  measureSegment: '', // 检定环节名称
  requireCertifications: 0, // 应出具证书数量
})
const btnLoading = ref(false) // 保存按钮加载状态
const list = ref([]) // 选择设备
// ---------------------------------表单提交---------------------------------------------
const dataFormRef = ref<FormInstance>() // 表单对象
const rules = reactive<FormRules>({ // 校验规则
  measureSegmentId: [{ required: true, message: '检定环节必填', trigger: ['blur', 'change'] }],
  measurePersonId: [{ required: true, message: '人员必填', trigger: ['blur', 'change'] }],
})

// 提交表单
function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) { return }
  formEl.validate((valid) => {
    if (valid) {
      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,
        }
      })
      batchExecute(params).then(() => {
        ElMessage.success('批量分发完成')
        dialogVisible.value = false
        emit('onSuccess')
      })
    }
  })
}

// ------------------------------------------弹窗操作------------------------------------
/**
 * 初始化审批弹窗
 * @param val 选中的样品列表
 */
function initDialog(val: any) {
  list.value = val
  getDict().then(() => {
    fetchDeptList() // 获取部门
    dialogVisible.value = true
  })
  nextTick(() => {
    if (dataFormRef.value) { dataFormRef.value!.resetFields() } // 重置该表单项，将其值重置为初始值，并移除校验结果
  })
}

// 关闭弹窗
function handleClose() {
  dialogVisible.value = false
}
// -----------------------------------------字典--------------------------------------------------------------
const deptCategoryMap = ref({}) as any// 部门类别{无线电}

/**
 * 获取字典
 */
async function getDict() {
  // 获取部门类别
  const res = await getDictByCode('eqptDeviceType')
  // 部门类别{无线电}
  res.data.forEach((item: any) => {
    deptCategoryMap.value[`${item.value}`] = item.name
  })
}
// ------------------------------------查询部门---------------------------------------------
const deptList = ref([]) as any // 部门列表
const personList = ref([]) as any // 人员列表
function fetchDeptList() {
  getDeptList({ deptName: '', deptId: '' }).then((response) => {
    // deptType === '3'是检定部门
    const tempArr = response.data.list.filter((item: { deptType: string }) => item.deptType == '3')
    deptList.value = tempArr.map((i: { tips: string }) => {
      return {
        ...i,
        deptCategoryName: deptCategoryMap.value[i.tips!],
      }
    })
  })
}
// ------------------------------------- 以下是暴露的方法内容 ------------------------------------
watch(() => formData.value.measureSegmentId, (newValue) => {
  getStaffList({
    deptId: newValue, // 部门id
    name: '', // 姓名
    deptName: '', // 工作部门名称
    offset: 1,
    limit: 999999,
  }).then((res) => {
    personList.value = res.data.rows.map((item: { staffName: string }) => {
      return {
        ...item,
        name: item.staffName,
      }
    })
  })
}, { deep: true })
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-select v-model="formData.measureSegmentId" style="width: 400px;" placeholder="请选择检定环节">
              <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.fullName"
                :value="item.id"
              >
                <div style="display: flex; flex-wrap: nowrap;">
                  <span style="flex: 1;">{{ item.fullName }}</span>
                  <span style="flex: 1;color: #8492a6; font-size: 13px;text-align: center;">{{ item.deptCategoryName }}</span>
                  <span style="flex: 1;text-align: right;">{{ item.directorName }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="请选择人员" prop="measurePersonId">
            <el-select v-model="formData.measurePersonId" style="width: 400px;" :disabled="!formData.measureSegmentId" placeholder="请选择人员">
              <el-option
                v-for="item in personList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <div style="display: flex; flex-wrap: nowrap;">
                  <span style="flex: 1;">{{ item.name }}</span>
                  <span style="flex: 1;color: #8492a6; font-size: 13px;text-align: center;">{{ item.genderName }}</span>
                  <span style="flex: 1;text-align: right;">{{ item.station }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应出具证书" prop="requireCertifications">
            <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>
</template>

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