<!-- 计量组织新增或详情弹窗 -->
<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 type { userType } from '@/views/system/user/user-interface'
import { listPageApi, standardlistPageApi, updateApi } from '@/api/measure/measureDept'
import { getStaffList } from '@/api/measure/person'
const emits = defineEmits(['resetData'])
const router = useRoute()
const ruleFormRef = ref<FormInstance>() // from组件
const ruleForm = ref({
  organizeType: '', // 类型
  organizeName: '', // 名称
  organizeNo: '', // 编号
  deptId: '', // 部门
  director: '', // 负责人
  administrationJob: '', // 行政职务
  technologyJob: '', // 技术职务
  remark: '', // 备注
  pDeptId: '',
  pDeptName: '',
}) // 表单
const title = 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 = () => {
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    userList.value = res.data.rows
  })
} // 获取用户列表
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 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('提交成功')
            emits('resetData')
          }
        })
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  emits('resetData')
}
// 重置
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 searchQuery = ref({
//   limit: 10,
//   offset: 1,
//   total: 0,
//   pageSizes: [10, 20, 30],
// })
// 部门列表数据
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 = () => {
  console.log(router.path.split('/')[2], '路由')
  if (router.path.split('/')[2] === 'bm') {
    // 获取科室
    listPageApi({
      organizeNo: '',
      organizeName: '',
      limit: 9999,
      offset: 1,
      organizeType: '3',
      createTime: '', // 创建时间
      director: '', // 负责人
      meterMajor: '', // 专业
      pDeptId: ruleForm.value.deptId, // 所属科室
    }).then((res) => {
      console.log(res, '科室')
      changeList_bm.value[0].data = res.data.rows
    })
  }
  else if (router.path.split('/')[2] === 'ks') {
    // 获取工程组
    listPageApi({
      organizeNo: '',
      organizeName: '',
      limit: 9999,
      offset: 1,
      organizeType: '4',
      createTime: '', // 创建时间
      director: '', // 负责人
      meterMajor: '', // 专业
      pDeptId: ruleForm.value.deptId, // 所属科室
    }).then((res) => {
      console.log(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 handleSizeChange = (val: number) => {
//   searchQuery.value.limit = val
//   getDepartmentList()
//   getuserInfoList()
//   getInstrumentInfo()
//   getDeviceInfo()
// }
// const handleCurrentChange = (val: number) => {
//   searchQuery.value.offset = val
//   getDepartmentList()
//   getuserInfoList()
//   getInstrumentInfo()
//   getDeviceInfo()
// }
// 弹窗初始化
const initDialog = (row: any) => {
  reset()
  title.value = row.title
  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
  }
  else if (title.value.split('-')[1] === '工程组') {
    changeList.value = changeList_gcz.value
    current.value = changeList_gcz.value[0].name
  }
}
defineExpose({ initDialog })
</script>

<template>
  <app-container style="overflow: hidden;">
    <div class="body-container">
      <div class="header">
        <div class="title">
          {{ title }}
        </div>
        <span class="btns">
          <el-button v-if="title.split('-')[2] === '编辑'" type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button type="info" @click="resetForm(ruleFormRef)">
            关闭
          </el-button>
        </span>
      </div>
      <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" class="marg">
          <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-row>
        <el-row v-if="title.split('-')[1] === '工程组'" :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="科室编号">
              <el-input v-model.trim="ruleForm.pDeptId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="科室名称">
              <el-input v-model.trim="ruleForm.pDeptName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门编号">
              <el-input v-model.trim="ruleForm.pDeptId" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门名称">
              <el-input v-model.trim="ruleForm.pDeptName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="负责人" prop="director">
              <el-select v-model="ruleForm.director" :placeholder="title.split('-')[2] === '详情' ? '' : '负责人'" :disabled="title.split('-')[2] === '详情'">
                <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] === '详情'">
                <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] === '详情'">
                <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" class="marg">
          <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>
      <!-- 科室信息-人员信息等列表切换 -->
      <div>
        <div class="header" style="margin-top: 10px;">
          <!-- 切换 -->
          <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>
          <div class="title">
            {{ current }}
          </div>
          <span class="btns">
          <!-- <el-button type="info" :disabled="title === '详情'" @click="removeRow">
            删除行
          </el-button>
          <el-button type="primary" :disabled="title === '详情'" @click="addRow">
            添加行
          </el-button> -->
          </span>
        </div>
        <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>
        <!-- <div style="width: 100%;margin-top: 10px;">
          <el-pagination
            :current-page="searchQuery.offset"
            :page-sizes="searchQuery.pageSizes"
            :page-size="searchQuery.limit"
            :total="searchQuery.total"
            layout="total, sizes, prev, pager, next"
            hide-on-single-page
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div> -->
      </div>
    </div>
  </app-container>
</template>

<style lang="scss" scoped>
.body-container {
  .form {
    border-radius: 8px;
    background-color: #fff;
    margin-top: 10px;
    padding-top: 10px;
  }

  .header {
    background-color: #fff;
    height: 40px;
    border-radius: 8px;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    display: flex;
    position: relative;

    .change-btn {
      position: absolute;
      left: 40px;
      top: 4px;
    }

    .title {
      font-weight: 700;
    }

    .btns {
      position: absolute;
      right: 40px;
      top: 4px;
    }
  }
}

.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;
    }
  }
}

.marg {
  margin-top: 10px;
}
</style>
