<!-- 计量组织新增或详情弹窗 -->
<script lang="ts" setup name="addMeasureDept">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { detailType } from '../measureDept-interface'
// import { getUserList } from '@/api/system/user'
import { getDictByCode } from '@/api/system/dict'
import { getStaffDetail, getStaffList } from '@/api/measure/person'
import type { userType } from '@/views/system/user/user-interface'
import { getpDeptApi, listPageApi, standardlistPageApi, updateApi } from '@/api/measure/measureDept'
const $route = useRoute()
const $router = useRouter()
const ruleFormRef = ref<FormInstance>() // from组件
const ruleForm = ref({
  organizeType: '', // 类型
  organizeName: '', // 名称
  organizeNo: '', // 编号
  deptId: '', // 部门
  director: '', // 负责人
  administrationJob: '', // 行政职务
  technologyJob: '', // 技术职务
  remark: '', // 备注
  pDeptId: '',
  pDeptName: '',
}) // 表单
// 展示父级组织
const pDept = ref({
  pDeptName: '',
  pOrganizeNo: '',
  ppDeptName: '',
  ppOrganizeNo: '',
})
const title = ref('')
const path = ref('')
const rules = ref<FormRules>({
  organizeName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  director: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  administrationJob: [{ required: true, message: '行政职务不能为空', trigger: 'blur' }],
  technologyJob: [{ required: true, message: '技术职务不能为空', trigger: 'blur' }],
}) // 表单验证规则
const userList = ref<userType[]>([]) // 用户列表
// 获取计量人员列表
const getuser = () => {
  getStaffList({
    staffNo: '', // 人员编号
    name: '', // 姓名
    deptId: '', // 所在部门
    limit: 999999,
    offset: 1,
  }).then((res) => {
    if (res.code === 200) {
      userList.value = res.data.records
    }
  })
}
const technologyJobList = ref<{ id: string;name: string;value: string }[]>([])
// 获取技术职务列表
const getTechnologyJobList = () => {
  getDictByCode('technologyJob').then((response) => {
    technologyJobList.value = response.data
  })
}
const administrationJobList = ref<{ id: string;name: string;value: string }[]>([])
// 获取行政职务列表
const getAdministrationJob = () => {
  getDictByCode('administrationJob').then((response) => {
    administrationJobList.value = response.data
  })
}
// 选择负责人自动填充职务信息
const directorChange = (val: string) => {
  const selectUser = userList.value.filter(item => item.name === val)[0]
  getStaffDetail(selectUser).then((res) => {
    if (res.code === 200) {
      ruleForm.value.administrationJob = res.data.administrationJob
      ruleForm.value.technologyJob = res.data.technologyJob
    }
  })
}
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认提交吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        updateApi({ ...ruleForm.value, title: undefined }).then((res) => {
          if (res.code == 200) {
            formEl?.resetFields()
            ElMessage.success('提交成功')
            $router.go(-1)
          }
        })
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  $router.go(-1)
}
// 重置
const reset = () => {
  ruleForm.value.organizeType = '' // 类型
  ruleForm.value.organizeName = '' // 名称
  ruleForm.value.organizeNo = '' // 编号
  ruleForm.value.deptId = '' // 部门
  ruleForm.value.director = '' // 负责人
  ruleForm.value.administrationJob = '' // 行政职务
  ruleForm.value.technologyJob = '' // 技术职务
  ruleForm.value.remark = '' // 备注
}
const multipleTableRef = ref()
const current = ref('')
const changeList = ref<detailType[]>()
// 部门列表数据
const changeList_bm = ref<detailType[]>([
  {
    name: '科室信息',
    data: [],
    column: [
      {
        label: '科室编号',
        data: 'organizeNo',
      },
      {
        label: '科室名称',
        data: 'organizeName',
      },
      {
        label: '负责人姓名',
        data: 'director',
      },
      {
        label: '计量专业',
        data: 'meterMajor',
      },
      {
        label: '创建时间',
        data: 'createTime',
      },
    ],
  },
  {
    name: '人员信息',
    data: [],
    column: [
      {
        label: '人员编号',
        data: 'staffNo',
      },
      {
        label: '姓名',
        data: 'name',
      },
      {
        label: '联系方式',
        data: 'phone',
      },
      {
        label: '技术职务',
        data: 'technologyJob',
      },
      {
        label: '行政职务',
        data: 'administrationJob',
      },
    ],
  },
])
// 科室列表数据
const changeList_ks = ref<detailType[]>([
  {
    name: '工程组信息',
    data: [],
    column: [
      {
        label: '工程组编号',
        data: 'organizeNo',
      },
      {
        label: '工程组名称',
        data: 'organizeName',
      },
      {
        label: '负责人姓名',
        data: 'director',
      },
      {
        label: '计量专业',
        data: 'meterMajor',
      },
      {
        label: '创建时间',
        data: 'createTime',
      },
    ],
  },
  {
    name: '仪器信息',
    data: [],
    column: [
      {
        label: '统一编号',
        data: '',
      },
      {
        label: '设备名称',
        data: 'name',
      },
      {
        label: '型号',
        data: '',
      },
      {
        label: '测量范围',
        data: '',
      },
      {
        label: '使用部门',
        data: '',
      },
      {
        label: '使用人',
        data: '',
      },
    ],
  },
  {
    name: '标准装置信息',
    data: [],
    column: [
      {
        label: '标准装置编号',
        data: 'standardNo',
      },
      {
        label: '标准装置名称',
        data: 'standardName',
      },
      {
        label: '类别',
        data: 'categoryName',
      },
      {
        label: '标准等级',
        data: 'standardLevelName',
      },
      {
        label: '传递范围',
        data: 'transmitRangeName',
      },
      {
        label: '使用人',
        data: 'standardOwnerName',
      },
    ],
  },
])
// 工程组列表数据
const changeList_gcz = ref<detailType[]>([
  {
    name: '人员信息',
    data: [],
    column: [
      {
        label: '人员编号',
        data: 'staffNo',
      },
      {
        label: '姓名',
        data: 'name',
      },
      {
        label: '联系方式',
        data: 'phone',
      },
      {
        label: '技术职务',
        data: 'technologyJob',
      },
      {
        label: '行政职务',
        data: 'administrationJob',
      },
    ],

  },
  {
    name: '仪器信息',
    data: [],
    column: [
      {
        label: '统一编号',
        data: '',
      },
      {
        label: '设备名称',
        data: 'name',
      },
      {
        label: '型号',
        data: '',
      },
      {
        label: '测量范围',
        data: '',
      },
      {
        label: '使用部门',
        data: '',
      },
      {
        label: '使用人',
        data: '',
      },
    ],
  },
  {
    name: '标准装置信息',
    data: [],
    column: [
      {
        label: '标准装置编号',
        data: 'standardNo',
      },
      {
        label: '标准装置名称',
        data: 'standardName',
      },
      {
        label: '类别',
        data: 'categoryName',
      },
      {
        label: '标准等级',
        data: 'standardLevelName',
      },
      {
        label: '传递范围',
        data: 'transmitRangeName',
      },
      {
        label: '使用人',
        data: 'standardOwnerName',
      },
    ],
  },
])
const currentShow = computed(() => {
  return changeList.value?.filter((item: detailType) => item.name === current.value)[0]
})
// 获取科室/工程组信息
const getDepartmentList = () => {
  if (path.value === 'bm') {
    // 获取科室
    listPageApi({
      organizeNo: '',
      organizeName: '',
      limit: 9999,
      offset: 1,
      organizeType: '3',
      createEndTime: '', // 创建时间
      createStartTime: '', // 创建时间
      director: '', // 负责人
      meterMajor: '', // 专业
      pDeptId: ruleForm.value.deptId, // 所属科室
    }).then((res) => {
      changeList_bm.value[0].data = res.data.rows
    })
  }
  else if (path.value === 'ks') {
    // 获取工程组
    listPageApi({
      organizeNo: '',
      organizeName: '',
      limit: 9999,
      offset: 1,
      organizeType: '4',
      createEndTime: '', // 创建时间
      createStartTime: '', // 创建时间
      director: '', // 负责人
      meterMajor: '', // 专业
      pDeptId: ruleForm.value.deptId, // 所属科室
    }).then((res) => {
      changeList_ks.value[0].data = res.data.rows
    })
  }
}
// 获取人员信息
const getuserInfoList = () => {
  const params = {
    staffNo: '',
    name: '',
    deptId: ruleForm.value.deptId,
    major: '',
    verifierCertificateNo: '',
    certificateStatus: '',
    limit: 9999,
    offset: 1,
  }
  getStaffList(params).then((response) => {
    changeList_bm.value[1].data = response.data.records
    changeList_gcz.value[0].data = response.data.records
  })
}
// 获取仪器信息
const getInstrumentInfo = () => {
  // 接口暂未写好 根据实际情况赋值
  // getDictByCode('pDeptId').then((response) => {
  //   changeList_ks.value[1].data = response.data
  //   changeList_gcz.value[1].data = response.data
  // })
}
// 获取标准装置信息
const getDeviceInfo = () => {
  standardlistPageApi({ standardLaboratory: ruleForm.value.deptId, limit: 99999, offset: 1 }).then((res) => {
    if (res.code == 200) {
      changeList_ks.value[2].data = res.data.rows
      changeList_gcz.value[2].data = res.data.rows
    }
  })
}
// 弹窗初始化
const initDialog = (row: any) => {
  reset()
  title.value = row.title
  path.value = row.path
  ruleForm.value.organizeType = row.organizeType
  ruleForm.value.deptId = row.deptId
  getuser()
  getTechnologyJobList()
  getAdministrationJob()
  getDepartmentList()
  getuserInfoList()
  if (title.value.split('-')[1] !== '部门') {
    getInstrumentInfo()
    getDeviceInfo()
  }
  ruleForm.value = row
  console.log(row, 'row')
  // 不同组织来判断展示的列表
  if (title.value.split('-')[1] === '部门') {
    changeList.value = changeList_bm.value
    current.value = changeList_bm.value[0].name
  }
  else if (title.value.split('-')[1] === '科室') {
    changeList.value = changeList_ks.value
    current.value = changeList_ks.value[0].name
    // 获取所属部门
    getpDeptApi({ deptId: ruleForm.value.deptId }).then((res) => {
      pDept.value.pDeptName = res.data.pDeptName
      pDept.value.pOrganizeNo = res.data.pOrganizeNo
    })
  }
  else if (title.value.split('-')[1] === '工程组') {
    changeList.value = changeList_gcz.value
    current.value = changeList_gcz.value[0].name
    // 获取所属部门
    getpDeptApi({ deptId: ruleForm.value.deptId }).then((res) => {
      pDept.value.pDeptName = res.data.pDeptName
      pDept.value.pOrganizeNo = res.data.pOrganizeNo
      getpDeptApi({ deptId: res.data.pDeptId }).then((res) => {
        pDept.value.ppDeptName = res.data.pDeptName
        pDept.value.ppOrganizeNo = res.data.pOrganizeNo
      })
    })
    console.log(pDept.value, 'pDept.value')
  }
}
onMounted(() => {
  initDialog($route.query)
})
</script>

<template>
  <app-container style="overflow: hidden;">
    <detail-page :title="title">
      <template #btns>
        <el-button v-if="title.split('-')[2] === '编辑'" type="primary" @click="submitForm(ruleFormRef)">
          提交
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form" :class="[title.split('-')[2] === '详情' ? 'isDetail' : '']">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item :label=" `${title.split('-')[1]}编号`" prop="organizeNo">
              <el-input v-model.trim="ruleForm.organizeNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item :label="`${title.split('-')[1]}名称`" prop="organizeName">
              <el-input v-model.trim="ruleForm.organizeName" :placeholder="title.split('-')[2] === '详情' ? '' : `${title.split('-')[1]}名称`" :disabled="title.split('-')[2] === '详情'" />
            </el-form-item>
          </el-col>
          <el-col v-if="title.split('-')[1] === '科室'" :span="6">
            <el-form-item label="所属部门编号">
              <el-input v-model.trim="pDept.pOrganizeNo" disabled />
            </el-form-item>
          </el-col>
          <el-col v-if="title.split('-')[1] === '科室'" :span="6">
            <el-form-item label="所属部门名称">
              <el-input v-model.trim="pDept.pDeptName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="title.split('-')[1] === '工程组'" :gutter="24">
          <el-col :span="6">
            <el-form-item label="科室编号">
              <el-input v-model.trim="pDept.pOrganizeNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="科室名称">
              <el-input v-model.trim="pDept.pDeptName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门编号">
              <el-input v-model.trim="pDept.ppOrganizeNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门名称">
              <el-input v-model.trim="pDept.ppDeptName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="负责人" prop="director">
              <el-select v-model="ruleForm.director" :placeholder="title.split('-')[2] === '详情' ? '' : '负责人'" :disabled="title.split('-')[2] === '详情'" style="width: 100%;" @change="directorChange">
                <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="技术职务" prop="technologyJob">
              <el-select v-model="ruleForm.technologyJob" :placeholder="title.split('-')[2] === '详情' ? '' : '技术职务'" :disabled="title.split('-')[2] === '详情'" style="width: 100%;">
                <el-option v-for="item in technologyJobList" :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="administrationJob">
              <el-select v-model="ruleForm.administrationJob" :placeholder="title.split('-')[2] === '详情' ? '' : '行政职务'" :disabled="title.split('-')[2] === '详情'" style="width: 100%;">
                <el-option v-for="item in administrationJobList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="ruleForm.remark" :placeholder="title.split('-')[2] === '详情' ? '' : '备注'" :disabled="title.split('-')[2] === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block-switch :title="current">
      <template #menu>
        <el-radio-group v-model="current" class="change-btn">
          <el-radio-button v-for="item in changeList" :key="item.name" :label="item.name">
            {{ item.name }}
          </el-radio-button>
        </el-radio-group>
      </template>
      <el-table ref="multipleTableRef" :data="currentShow?.data || []" style="width: 100%;margin-top: 10px;" border stripe>
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column v-for="item in currentShow?.column || []" :key="item.label" :prop="item.data" :label="item.label" align="center" />
      </el-table>
    </detail-block-switch>
  </app-container>
</template>

<style lang="scss" scoped>
.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      content: "";
      display: none;
    }
  }
}
</style>
