<script lang="ts" setup name="standardListAdd">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  corollaryEquipmentType,
  measurementPersonnelType,
  regulationVerificationType,
} from '../standard_interface'
import baseInfo from './standardList/baseInfo.vue'
import TemplateTable from './standardList/templateTable.vue'
import userListDialog from './standardList/userListDialog.vue'
import SelectDeviceDialog from './standardList/equipmentDialog.vue'
import VerificationDialog from './standardList/verificationDialog.vue'
import {
  getEquipmentDelete,
  getEquipmentListPage,
  getEquipmenteAdd,
  getRegulationAdd,
  getRegulationListPage,
  getStandardLisUpdate,
  getStandardListAdd,
  getUserBatchDelete,
  getuserListPage,
  setBatchAdd,
} from '@/api/device/standard'
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
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
  }
}
interface formInlineType {
  id: string
}
// 定义数据
const formInline = ref<formInlineType>({
  id: '',
})
// 关闭
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 baseInfoRef = 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()
}
// 拿到formInline的数据
const setData = (newValue: formInlineType) => {
  formInline.value = newValue
}
const queryParams = {
  id: '',
  limit: 20,
  offset: 1,
}
// 关闭
// 表头类型
interface TableColumn {
  text: string
  value: string
  align: string
  width?: string
}

interface checkedRecord {
  text: string
}
// 设备item类型
interface equipmentListPageItem {
  name: string
  equipmentName: string
}
// 文件item类型
interface regulationListPageItem {
  name: string
  fileName: string
}
// 计量人员表头
const measurementPersonnelColumns = ref<TableColumn[]>([
  { text: '姓名', value: 'name', align: 'center' },
  { text: '计量人员编号', value: 'staffNo', align: 'center' },
  { text: '工作部门', value: 'deptId', align: 'center' },
  { text: '计量专业', value: 'major', align: 'center' },
  { text: '证书编号', value: 'verifierCertificateNo', align: 'center' },
  { text: '证书有效期', value: 'certificateDate', align: 'center' },
])
// 计量人员数据
const measurementPersonnel = ref<measurementPersonnelType[]>([])
// 计量人员表格loading
const measurementPersonnelLoading = ref(false)
// 计量人员发送请求获取数据
function fetchmeasurementPersonnel() {
  measurementPersonnelLoading.value = true
  getuserListPage({ id: infoId.value }).then((res) => {
    measurementPersonnel.value = res.data.rows
    measurementPersonnelLoading.value = false
  })
}

// 标准配套设备表头
const corollaryEquipmentColumns = ref<TableColumn[]>([
  { text: '设备名称', value: 'name', align: 'center', width: '180' },
  { text: '设备编号', value: 'equipmentNo', align: 'center' },
  { text: '型号', value: 'modelNo', align: 'center' },
  { text: '测量范围', value: 'mesureRange', align: 'center' },
  { text: '使用部门', value: 'useDept', align: 'center' },
  { text: '检定时间', value: 'mesureDate', align: 'center' },
  { text: '检定结果', value: 'mesureResult', align: 'center' },
  { text: '有效日期', value: 'validDate', align: 'center' },
])
// 标准配套设备数据
const corollaryEquipment = ref<corollaryEquipmentType[]>([])
// 标准配套设备loading
const corollaryEquipmentLoading = ref(false)
// 标准配套设备发送请求获取数据
function fetchcorollaryEquipment(query = { ...queryParams }) {
  corollaryEquipmentLoading.value = true
  getEquipmentListPage({ id: infoId.value }).then((res) => {
    corollaryEquipment.value = res.data.rows.map(
      (item: equipmentListPageItem) => {
        item.name = item.equipmentName
        return item
      },
    )
    corollaryEquipmentLoading.value = false
  })
}

// 检定规程
const regulationVerificationColumns = ref<TableColumn[]>([
  { text: '文件名称', value: 'name', align: 'center' },
  { text: '文件编号', value: 'fileNo', align: 'center' },
  { text: '文件号', value: 'fileCode', align: 'center' },
  { text: '实施时间', value: 'effectiveTime', align: 'center' },
  { text: '实施状态', value: 'effectiveStatusName', align: 'center' },
])
const regulationVerification = ref<regulationVerificationType[]>([])
const regulationVerificationLoading = ref(false)
function fetchregulationVerification(query = { ...queryParams }) {
  regulationVerificationLoading.value = true
  getRegulationListPage({ id: infoId.value }).then((res) => {
    regulationVerification.value = res.data.rows.map(
      (item: regulationListPageItem) => {
        item.name = item.fileName
        return item
      },
    )
    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 = []
  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 = []
  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 = []
  certificateManagementLoading.value = false
}
// 编辑获取详情的提交按钮
const submitFormUpdate = () => {
  formInline.value.id = infoId.value
  getStandardLisUpdate(formInline.value).then((res) => {
    if (res.code === 200) {
      close()
    }
  })
}
const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '测量标准装置', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
// 提交
const submitForm = () => {
  if (pageType.value === 'edit') {
    return submitFormUpdate()
  }
  baseInfoRef.value
    .submitForm()
    .validate()
    .then(() => {
      ElMessageBox.confirm('确认提交吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        getStandardListAdd(formInline.value).then((res) => {
          if (res.code === 200) {
            ElMessage.success('新增成功')
            close()
          }
        })
      })
    })
}
const measurementPersonnelSelectionList = ref<object[]>([]) // 计量人员选中数组
const corollaryEquipmentSelectionList = ref<object[]>([]) // 标准配套设备选中数组
const regulationVerificationSelectionList = ref<object[]>([]) // 检定规程选中数组
const userListRef = ref()
const listIndex = ref(0)
// 新增计量人员
const measurementPersonnelAddRow = () => {
  if (
    measurementPersonnel.value.length >= 1
    && !measurementPersonnel.value[measurementPersonnel.value.length - 1].name
  ) {
    ElMessage.warning('请先完善上一条计量人员信息')
  }
  else {
    measurementPersonnel.value.push({ name: '', standardEquipmentId: '' })
  }
  // ElMessage.warning('请先选择上一条信息')
}
// 新增标准配套设备
const corollaryEquipmentAddRow = () => {
  if (
    corollaryEquipment.value.length >= 1
    && !corollaryEquipment.value[corollaryEquipment.value.length - 1].name
  ) {
    ElMessage.warning('请先完善上一条配套设备信息')
  }
  else {
    corollaryEquipment.value.push({
      name: '',
      equipmentName: '',
      standardEquipmentId: '',
    })
  }
  // ElMessage.warning('请先选择上一条信息')
}
// 新增检定规程
const regulationVerificationAddRow = () => {
  if (
    regulationVerification.value.length >= 1
    && !regulationVerification.value[regulationVerification.value.length - 1].name
  ) {
    ElMessage.warning('请先完善上一条检定规程信息')
  }
  else {
    regulationVerification.value.push({
      name: '',
      standardEquipmentId: '',
      fileName: '',
    })
  }
  // ElMessage.warning('请先选择上一条信息')
}
// 设备ref
const selectDeviceDialog = ref()
// 检定规程ref
const verificationDialog = ref()
// 点击表格中的选择按钮
function selectPerson(index: number, text: string) {
  if (text === '姓名') {
    userListRef.value.initDialog()
    listIndex.value = index
  }
  else if (text === '设备名称') {
    selectDeviceDialog.value.initDialog()
    listIndex.value = index
  }
  else if (text === '文件名称') {
    verificationDialog.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) {
      ElMessageBox.confirm(`确认删除选中的${title}列表吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        measurementPersonnel.value = measurementPersonnel.value.filter(
          item => !measurementPersonnelSelectionList.value.includes(item),
        )
        const ids = ref<string[]>([]) // 删除id
        ids.value = measurementPersonnelSelectionList.value.map(item => item.id)
        getUserBatchDelete({ ids: ids.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
          }
        })
      })
    }
    else {
      ElMessage.warning('请先选择中数据')
    }
  }
  else if (title === '标准配套设备') {
    if (corollaryEquipmentSelectionList.value.length > 0) {
      ElMessageBox.confirm(`确认删除选中的${title}列表吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        corollaryEquipment.value = corollaryEquipment.value.filter(
          item => !corollaryEquipmentSelectionList.value.includes(item),
        )
        const ids = ref<string[]>([])
        ids.value = corollaryEquipmentSelectionList.value.map(item => item.id)
        // 发送请求删除标准配套设备
        getEquipmentDelete({ ids: ids.value }).then((res) => {
          if (res.code === 200) {
            ElMessage.success('删除成功')
          }
        })
      })
    }
    else {
      ElMessage.warning('请先选择中数据')
    }
  }
  else if (title === '检定规程') {
    if (regulationVerificationSelectionList.value.length > 0) {
      ElMessageBox.confirm(`确认删除选中的${title}列表吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        regulationVerification.value = regulationVerification.value.filter(
          item => !regulationVerificationSelectionList.value.includes(item),
        )
      })
    }
    else {
      ElMessage.warning('请先选择中数据')
    }
  }
}
// 选择完负责人的函数
const confirmPerson = (object: measurementPersonnelType) => {
  if (!measurementPersonnel.value.includes(object)) {
    measurementPersonnel.value[listIndex.value] = object
    measurementPersonnel.value[listIndex.value].standardEquipmentId
      = infoId.value
    measurementPersonnel.value[listIndex.value].userId = object.id
    delete object.id
    setBatchAdd(measurementPersonnel.value).then((res) => {})
  }
  else {
    ElMessage.warning('该人员已经存在')
    measurementPersonnel.value.splice(listIndex.value, 1)
  }
}
// 选择完设备后
const selectDeviceList = (data: corollaryEquipmentType) => {
  if (!corollaryEquipment.value.includes(data)) {
    corollaryEquipment.value[listIndex.value] = data
    corollaryEquipment.value[listIndex.value].standardEquipmentId = infoId.value
    corollaryEquipment.value[listIndex.value].equipmentId = data.id
    corollaryEquipment.value[listIndex.value].name = data.equipmentName
    delete data.id
    getEquipmenteAdd(corollaryEquipment.value[listIndex.value]).then((res) => {})
  }
  else {
    ElMessage.warning('该设备已经存在')
    corollaryEquipment.value.splice(listIndex.value, 1)
  }
}
// 检定规程选择完成后
const verificationList = (data: regulationVerificationType) => {
  if (!regulationVerification.value.includes(data)) {
    regulationVerification.value[listIndex.value] = data
    regulationVerification.value[listIndex.value].standardEquipmentId
      = infoId.value
    regulationVerification.value[listIndex.value].verifyRegulationId = data.id
    regulationVerification.value[listIndex.value].name = data.fileName
    delete data.id
    getRegulationAdd(regulationVerification.value[listIndex.value]).then(
      (res) => {},
    )
  }
  else {
    ElMessage.warning('该文件已经存在')
    regulationVerification.value.splice(listIndex.value, 1)
  }
}

// 增加行
const addRow = (title: string) => {
  if (title === '计量人员') {
    measurementPersonnelAddRow()
  }
  else if (title === '标准配套设备') {
    corollaryEquipmentAddRow()
  }
  else if (title === '检定规程') {
    regulationVerificationAddRow()
  }
}
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"
        @setData="setData"
      />
    </detail-page>
    <detail-block-switch
      v-if="pageType === 'detail' || pageType === 'edit'"
      :title="pageType === 'detail' ? '' : current"
    >
      <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 #btns>
        <el-button
          v-if="pageType !== 'detail'"
          type="primary"
          @click="addRow(current)"
        >
          增加行
        </el-button>
        <el-button
          v-if="pageType !== 'detail'"
          type="info"
          @click="deleteRow(current)"
        >
          删除行
        </el-button>
      </template>
      <template-table
        v-if="current === '计量人员'"
        title="计量人员"
        :button-type="pageType"
        :columns="measurementPersonnelColumns"
        :list="measurementPersonnel"
        :loading="measurementPersonnelLoading"
        @selectPerson="selectPerson"
        @handleSelectionChange="handleSelectionChange"
        @change-page="fetchmeasurementPersonnel"
      />
      <template-table
        v-if="current === '标准配套设备'"
        title="标准配套设备"
        :button-type="pageType"
        :columns="corollaryEquipmentColumns"
        :list="corollaryEquipment"
        :loading="corollaryEquipmentLoading"
        @selectPerson="selectPerson"
        @change-page="fetchcorollaryEquipment"
        @handleSelectionChange="handleSelectionChange"
      />
      <template-table
        v-if="current === '检定规程'"
        title="检定规程"
        :button-type="pageType"
        :columns="regulationVerificationColumns"
        :list="regulationVerification"
        :loading="corollaryEquipmentLoading"
        @selectPerson="selectPerson"
        @change-page="fetchregulationVerification"
        @handleSelectionChange="handleSelectionChange"
      />
      <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" @add="confirmPerson" />
    <!-- 选择设备列表组件 -->
    <select-device-dialog ref="selectDeviceDialog" @add="selectDeviceList" />
    <!-- 选择检定规程列表组件 -->
    <verification-dialog ref="verificationDialog" @add="verificationList" />
  </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>
