<script lang="ts" setup name="standardListAdd">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import type { IOptions } from '../standard_interface'
import baseInfo from './standardList/baseInfo.vue'
import TemplateTable from './standardList/templateTable.vue'
import userListDialog from '@/views/measure/person/components/userListDialog.vue'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import { getStandardLisUpdate, getStandardListAdd, getStandardListDetail, getUsersDept } from '@/api/device/standard'
import { UploadFile } from '@/api/measure/file'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
// 定义数据
const formInline = ref({})
// 关闭
interface menuType {
  name: string
  comp: any
}
const menu = shallowRef<menuType[]>([
  { name: '计量人员', comp: TemplateTable },
  { name: '标准配套设备', comp: TemplateTable },
  { name: '检定规程', comp: TemplateTable },
  { name: '重复性考核记录', comp: TemplateTable },
  { name: '稳定性考核记录', comp: TemplateTable },
  { name: '证书管理', comp: TemplateTable },
])
if (pageType.value === 'edit') {
  menu.value = [{ name: '计量人员', comp: TemplateTable },
    { name: '标准配套设备', comp: TemplateTable },
    { name: '检定规程', comp: TemplateTable }]
}
const currentCompRef = ref()
const current = ref('计量人员')
const currentComp = shallowRef(baseInfo)
watch(current, (newValue) => {
  currentComp.value = menu.value.filter(item => item.name === newValue)[0].comp
})
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const setData = (newValue: object) => {
  formInline.value = newValue
}
const queryParams = {
  id: '',
  limit: 20,
  offset: 1,
}
// 关闭
interface TableColumn {
  text: string
  value: string
  align: string
}

interface checkedRecord {
  text: string
}
// 计量人员
const measurementPersonnelColumns = ref<TableColumn[]>([
  { text: '姓名', value: 'name', align: 'center' },
  { text: '计量人员编号', value: 'staffNo', align: 'center' },
  { text: '工作部门', value: 'deptName', align: 'center' },
  { text: '计量专业', value: 'major', align: 'center' },
  { text: '证书编号', value: 'verifierCertificateNo', align: 'center' },
  { text: '证书有效期', value: 'certificateDate', align: 'center' },
])
const measurementPersonnel = ref<checkedRecord[]>([])
const measurementPersonnelLoading = ref(false)
function fetchmeasurementPersonnel(query = { ...queryParams }) {
  measurementPersonnelLoading.value = true
  measurementPersonnel.value = [{
    text: 'xx',
  }]
  measurementPersonnelLoading.value = false
}

// 标准配套设备
const corollaryEquipmentColumns = ref<TableColumn[]>([
  { text: '设备名称', value: 'text', align: 'center' },
  { text: '设备编号', value: 'text', align: 'center' },
  { text: '型号', value: 'text', align: 'center' },
  { text: '测量范围', value: 'text', align: 'center' },
  { text: '使用部门', value: 'text', align: 'center' },
  { text: '检定时间', value: 'text', align: 'center' },
  { text: '检定结果', value: 'text', align: 'center' },
  { text: '有效日期', value: 'text', align: 'center' },
])
const corollaryEquipment = ref<checkedRecord[]>([])
const corollaryEquipmentLoading = ref(false)
function fetchcorollaryEquipment(query = { ...queryParams }) {
  corollaryEquipmentLoading.value = true
  corollaryEquipment.value = [{
    text: 'xx',
  }]
  corollaryEquipmentLoading.value = false
}

// 检定规程
const regulationVerificationColumns = ref<TableColumn[]>([
  { text: '文件名称', value: 'text', align: 'center' },
  { text: '文件编号', value: 'text', align: 'center' },
  { text: '文件号', value: 'text', align: 'center' },
  { text: '实施时间', value: 'text', align: 'center' },
  { text: '实施状态', value: 'text', align: 'center' },
])
const regulationVerification = ref<checkedRecord[]>([])
const regulationVerificationLoading = ref(false)
function fetchregulationVerification(query = { ...queryParams }) {
  regulationVerificationLoading.value = true
  regulationVerification.value = [{
    text: 'xx',
  }]
  regulationVerificationLoading.value = false
}

// 重复性考核记录
const repetitiveRppraisalRecordColumns = ref<TableColumn[]>([
  { text: '记录编号', value: 'text', align: 'center' },
  { text: '记录名称', value: 'text', align: 'center' },
  { text: '考核时间', value: 'text', align: 'center' },
  { text: '考核结果', value: 'text', align: 'center' },
])
const repetitiveRppraisalRecord = ref<checkedRecord[]>([])
const repetitiveRppraisalRecordLoading = ref(false)
function fetchrepetitiveRppraisalRecord(query = { ...queryParams }) {
  repetitiveRppraisalRecordLoading.value = true
  repetitiveRppraisalRecord.value = [{
    text: 'xx',
  }]
  repetitiveRppraisalRecordLoading.value = false
}

// 稳定性考核记录
const stabilityAssessmentRecordColumns = ref<TableColumn[]>([
  { text: '记录编号', value: 'text', align: 'center' },
  { text: '记录名称', value: 'text', align: 'center' },
  { text: '考核时间', value: 'text', align: 'center' },
  { text: '考核结果', value: 'text', align: 'center' },
])
const stabilityAssessmentRecord = ref<checkedRecord[]>([])
const stabilityAssessmentRecordLoading = ref(false)
function fetchstabilityAssessmentRecord(query = { ...queryParams }) {
  stabilityAssessmentRecordLoading.value = true
  stabilityAssessmentRecord.value = [{
    text: 'xx',
  }]
  stabilityAssessmentRecordLoading.value = false
}

// 证书管理
const certificateManagementColumns = ref<TableColumn[]>([
  { text: '证书编号', value: 'text', align: 'center' },
  { text: '证书名称', value: 'text', align: 'center' },
  { text: '证书类型', value: 'text', align: 'center' },
  { text: '证书出具日期', value: 'text', align: 'center' },
  { text: '证书有效期', value: 'text', align: 'center' },
])
const certificateManagement = ref<checkedRecord[]>([])
const certificateManagementLoading = ref(false)
function fetchcertificateManagement(query = { ...queryParams }) {
  certificateManagementLoading.value = true
  certificateManagement.value = [{
    text: 'xx',
  }]
  certificateManagementLoading.value = false
}
// 编辑获取详情的提交按钮
const submitFormDetail = () => {
  if (pageType.value === 'edit') {
    formInline.value.id = infoId.value
    getStandardLisUpdate(formInline.value).then((res) => {
      if (res.code === 200) {
        close()
      }
    })
  }
  else {
    // 打印

  }
}
const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '测量标准装置', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
// 提交
const submitForm = () => {
  if (pageType.value === 'detail') { return submitFormDetail() }
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    current.value = '基本信息'
    currentCompRef.value.submitForm().validate().then(() => {
      pageType.value === 'add'
        ? getStandardListAdd(formInline.value).then((res) => {
          if (res.code === 200) {
            close()
          }
        })
        : submitFormDetail()
    })
  })
}
const measurementPersonnelSelectionList = ref<object[]>([]) // 计量人员选中数组
const corollaryEquipmentSelectionList = ref<object[]>([]) // 标准配套设备选中数组
const regulationVerificationSelectionList = ref<object[]>([]) // 检定规程选中数组
const userListRef = ref()
const listIndex = ref(0)
// 新增计量人员
const measurementPersonnelAddRow = () => {
  measurementPersonnel.value.push({})
  // ElMessage.warning('请先选择上一条信息')
}
// 新增标准配套设备
const corollaryEquipmentAddRow = () => {
  corollaryEquipment.value.push({})
  // ElMessage.warning('请先选择上一条信息')
}
// 新增检定规程
const regulationVerificationAddRow = () => {
  regulationVerification.value.push({})
  // ElMessage.warning('请先选择上一条信息')
}
function selectPerson(index: number, text: string) {
  if (text === '姓名') {
    userListRef.value.initDialog()
    listIndex.value = index
  }
}
// 多选框选中
function handleSelectionChange(Array: object[], title: string) {
  if (title === '计量人员') {
    measurementPersonnelSelectionList.value = Array
  }
  else if (title === '标准配套设备') {
    corollaryEquipmentSelectionList.value = Array
  }
  else if (title === '检定规程') {
    regulationVerificationSelectionList.value = Array
  }
}
// 点击删除行
const deleteRow = (title: string) => {
  if (title === '计量人员') {
    if (measurementPersonnelSelectionList.value.length > 0) {
      measurementPersonnel.value = measurementPersonnel.value.filter(item => !measurementPersonnelSelectionList.value.includes(item))
    }
    else {
      ElMessage.warning('请先选择中数据')
    }
  }
  else if (title === '标准配套设备') {
    if (corollaryEquipmentSelectionList.value.length > 0) {
      corollaryEquipment.value = corollaryEquipment.value.filter(item => !corollaryEquipmentSelectionList.value.includes(item))
    }
    else {
      ElMessage.warning('请先选择中数据')
    }
  }
  else if (title === '检定规程') {
    if (regulationVerificationSelectionList.value.length > 0) {
      regulationVerification.value = regulationVerification.value.filter(item => !regulationVerificationSelectionList.value.includes(item))
    }
    else {
      ElMessage.warning('请先选择中数据')
    }
  }
}
// 选择完负责人的函数
const confirmPerson = (object: object) => {
  if (!measurementPersonnel.value.includes(object)) {
    measurementPersonnel.value[listIndex.value] = object
  }
  else {
    ElMessage.warning('该人员已经存在')
    measurementPersonnel.value.splice(listIndex.value, 1)
  }
}
onMounted(() => {
  if (pageType.value === 'detail') {
    // fetchmeasurementPersonnel()  // 计量人员
    fetchcorollaryEquipment() // 标准配套设备
    fetchregulationVerification() // 检定规程
    fetchrepetitiveRppraisalRecord() // 重复性考核记录
    fetchstabilityAssessmentRecord() // 稳定性考核记录
    fetchcertificateManagement() // 证书管理
  }
  else if (pageType.value === 'edit') {
    // fetchmeasurementPersonnel()  // 计量人员
    fetchcorollaryEquipment() // 标准配套设备
    fetchregulationVerification() // 检定规程
  }
})
</script>

<template>
  <app-container>
    <detail-page :title="`测量标准装置-${textMap[pageType]}`">
      <template #btns>
        <el-button
          v-if="pageType !== 'detail'"
          type="primary"
          @click="submitForm()"
        >
          提交
        </el-button>
        <el-button
          v-else
          v-print="printObj"
          type="primary"
        >
          打印
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <base-info id="form" ref="baseInfoRef" :info-id="infoId" :button-type="pageType" />
    </detail-page>
    <detail-block-switch v-if="pageType === 'detail' || pageType === 'edit'" title="">
      <template #menu>
        <el-radio-group v-model="current">
          <el-radio-button v-for="item in menu" :key="item.name" :label="item.name">
            {{ item.name }}
          </el-radio-button>
        </el-radio-group>
      </template>
      <template-table v-if="current === '计量人员'" title="计量人员" :button-type="pageType" :columns="measurementPersonnelColumns" :list="measurementPersonnel" :loading="measurementPersonnelLoading" @deleteRow="deleteRow" @selectPerson="selectPerson" @add-row="measurementPersonnelAddRow" @handleSelectionChange="handleSelectionChange" @change-page="fetchmeasurementPersonnel" />
      <template-table v-if="current === '标准配套设备'" title="标准配套设备" :button-type="pageType" :columns="corollaryEquipmentColumns" :list="corollaryEquipment" :loading="corollaryEquipmentLoading" @deleteRow="deleteRow" @selectPerson="selectPerson" @change-page="fetchcorollaryEquipment" @handleSelectionChange="handleSelectionChange" @add-row="corollaryEquipmentAddRow" />
      <template-table v-if="current === '检定规程'" title="检定规程" :button-type="pageType" :columns="regulationVerificationColumns" :list="regulationVerification" :loading="corollaryEquipmentLoading" @deleteRow="deleteRow" @selectPerson="selectPerson" @change-page="fetchregulationVerification" @handleSelectionChange="handleSelectionChange" @add-row="regulationVerificationAddRow" />
      <template-table v-if="current === '重复性考核记录'" title="重复性考核记录" :button-type="pageType" :columns="repetitiveRppraisalRecordColumns" :list="repetitiveRppraisalRecord" :loading="repetitiveRppraisalRecordLoading" @change-page="fetchrepetitiveRppraisalRecord" />
      <template-table v-if="current === '稳定性考核记录'" title="稳定性考核记录" :button-type="pageType" :columns="stabilityAssessmentRecordColumns" :list="stabilityAssessmentRecord" :loading="stabilityAssessmentRecordLoading" @change-page="fetchstabilityAssessmentRecord" />
      <template-table v-if="current === '证书管理'" title="证书管理" :button-type="pageType" :columns="certificateManagementColumns" :list="certificateManagement" :loading="certificateManagementLoading" @change-page="fetchcertificateManagement" />
    </detail-block-switch>
    <!-- 选择用户列表组件 -->
    <user-list-dialog ref="userListRef" :list="measurementPersonnel" @add="confirmPerson" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.body {
  background-color: #fff;
  margin-top: 10px;
}
</style>
