<!-- 标准装置台账信息详情 标准配套设备 -->
<script name="StandardBookStandard" lang="ts" setup>
import type { Ref } from 'vue'
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { ElLoading, ElMessage } from 'element-plus'
import type { FormRules } from 'element-plus'
import type { IForm, IStandardList, ITechFiles } from '../book-interface'
import selectEquipmentDialog from '../dialog/selectEquipmentDialog.vue'
import selectBuildStandardDialog from './selectBuildStandardDialog.vue'
import selectTechFiles from './selectTechFiles.vue'
import { getDictByCode } from '@/api/system/dict'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import useUserStore from '@/store/modules/user'
import type { deptType, dictType } from '@/global'
import { getDeptTreeList } from '@/api/system/dept'
import { getUserList } from '@/api/system/user'
import showPhoto from '@/components/showPhoto/index.vue'
import { UploadFile } from '@/api/file'
import { toTreeList } from '@/utils/structure'
import { useCheckList } from '@/commonMethods/useCheckList'
import { useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import { isNumber } from '@/utils/validate'
import { getUid } from '@/utils/getUid'
import { addEquipment, deleteEquipment, getEquipmentList } from '@/api/equipment/standard/book'
import { useMergeCells } from '@/commonMethods/useMergeCells'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    default: 'detail',
  },
  standardId: { // id
    type: String,
  },
  standardName: { // 标准装置名称
    type: String,
  },
})
// 查询条件
const listQuery = ref({
  standardId: props.standardId!,
  offset: 1,
  limit: 20,
})
const loadingTable = ref(false) // 表格loading
const isMulti = ref(false) // 是否多选
const user = useUserStore() // 用户信息
const selectIndex = ref(0) // 点击选择选中的行
const list = ref<IStandardList[]>([]) // 表格数据
const checkoutList = ref([]) as any // 多选数据\
const equipmentRef = ref() // 选择设备组件ref
const total = ref(0) // 数据总条数
const checkoutIds = ref<{ equipmentId: string }[]>([])// 删除用的ids
const columns = [ // 表头
  { text: '统一编号', value: 'equipmentNo', align: 'center', required: true, width: '160' },
  { text: '计量标准的主标准器及配套设备名称', value: 'equipmentName', align: 'center' },
  { text: '型号规格', value: 'model', align: 'center' },
  { text: '测量范围', value: 'measureRange', align: 'center' },
  { text: '不确定度或允许误差极限或准确度等级', value: 'uncertainty', align: 'center' },
]
// -----------------------------------------methods--------------------------------------
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getEquipmentList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: { id: string }) => {
      return {
        ...item,
        equipmentId: item.id,
        delId: '', // 删除使用的id
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

// 点击标签识读
const scan = () => {
  ElMessage.info('敬请期待')
}
// 点击批量增加
const multiAdd = () => {
  isMulti.value = true
  equipmentRef.value.initDialog()
}
// 点击增加行
const add = () => {
  const index = list.value.findIndex((item: IStandardList) => !item.equipmentNo && !item.equipmentName)
  if (index !== -1) {
    ElMessage.warning('请完善上一条设备信息')
    return
  }
  list.value.unshift({
    delId: getUid(), // 主键
    equipmentNo: '', // 统一编号
    equipmentName: '', // 计量标准的主标准器及配套设备名称
    model: '', // 型号规格
    measureRange: '', // 测量范围
    uncertainty: '', // 不确定度或允许误差极限或准确度等级
  })
}
// 点击删除行
const del = async () => {
  if (!checkoutList.value.length) {
    ElMessage.warning('请选中要删除的行')
    return
  }

  // 前端删除
  const delList = checkoutList.value.filter((item: { delId: string }) => item.delId)
  list.value = list.value.filter(item => !delList.includes(item))

  // 接口删除
  const delListAjax = checkoutList.value.filter((item: { delId: string }) => !item.delId)
  console.log(delListAjax)

  checkoutIds.value = delListAjax.map((item: { equipmentId: string }) => item.equipmentId)
  if (checkoutIds.value.length) {
    loadingTable.value = true
    await deleteEquipment({ ids: checkoutIds.value })
    fetchData()
    loadingTable.value = false
  }
}
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 点击选择设备
const selectedEquipment = (index: number) => {
  isMulti.value = false
  selectIndex.value = index
  equipmentRef.value.initDialog()
}
// 选择好设备
const confirmSelect = (val: any) => {
  console.log(val)

  if (isMulti.value) { // 批量增加时push
    val.forEach((item: any) => {
      // 只添加列表里不存在的
      const index = list.value.findIndex((i: IStandardList) => item.equipmentNo === i.equipmentNo)
      if (index === -1) {
        // item.technicalTargetList.forEach((i: { measureRange: string; uncertainty: string }) => {
        list.value.unshift({
          delId: getUid(),
          equipmentId: item.id, // 设备id
          equipmentNo: item.equipmentNo, // 设备编号
          equipmentName: item.equipmentName, // 设备名称
          model: item.model, // 型号
          // measureRange: i.measureRange, // 测量范围
          // uncertainty: i.uncertainty, // 不确定度
        })
        // })
      }
    })
  }
  else { // 单选替换
    const index = list.value.findIndex((i: IStandardList) => val[0].equipmentNo === i.equipmentNo)
    if (index !== -1) {
      ElMessage.warning('此设备已添加过')
      return
    }
    const params = {
      delId: getUid(),
      equipmentId: val[0].id, // 设备id
      equipmentNo: val[0].equipmentNo, // 设备编号
      equipmentName: val[0].equipmentName, // 设备名称
      model: val[0].technicalTargetList[0].model, // 型号
      // measureRange: val[0].technicalTargetList[0].measureRange, // 测量范围
      // uncertainty: val[0].technicalTargetList[0].uncertainty, // 不确定度
    }
    list.value.splice(selectIndex.value, 1, params)
  }
}

// 点击保存增加设备
const saveEquipment = () => {
  if (!useCheckList(list.value, columns, '标准配套设备')) {
    return false
  }
  console.log(list.value)

  const tempParams = list.value.filter(item => item.delId)
  const params = tempParams.map((item) => {
    return {
      equipmentId: item.equipmentId,
      standardId: props.standardId,
      standardName: props.standardName,
    }
  })
  loadingTable.value = true
  addEquipment({ list: params }).then(() => {
    ElMessage.success('新增标准配套设备成功')
    fetchData()
  }).catch(() => {
    loadingTable.value = false
  })
}

// 改变页容量
function handleSizeChange(val: number) {
  listQuery.value.limit = val
  fetchData()
}
// 改变当前页
function handleCurrentChange(val: number) {
  listQuery.value.offset = val
  fetchData(true)
}
function spanMethod({ rowIndex, columnIndex }: { rowIndex: number; columnIndex: number }) {
  return useMergeCells(list.value, ['equipmentNo', 'equipmentName'], rowIndex, columnIndex)
}

// -------------------------------------------钩子------------------------------------------------
onMounted(async () => {
  fetchData()
})
defineExpose({
  saveEquipment,
})
</script>

<template>
  <detail-block title="标准配套设备">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="scan">
        标签识读
      </el-button>
      <el-button type="primary" @click="multiAdd">
        批量增加
      </el-button>
      <el-button type="primary" @click="add">
        增加行
      </el-button>
      <el-button type="info" @click="del">
        删除行
      </el-button>
    </template>
    <el-table
      v-loading="loadingTable"
      :data="list"
      border
      stripe
      style="width: 100%;"
      :span-method="spanMethod"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        v-if="pageType !== 'detail'"
        type="selection"
        width="38"
      />
      <el-table-column label="序号" width="55" align="center">
        <template #default="scope">
          {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="item in columns"
        :key="item.value"
        :prop="item.value"
        :label="item.text"
        :width="item.width"
        align="center"
      >
        <template
          v-if="item.value === 'equipmentNo' && pageType !== 'detail'"
          #default="scope"
        >
          <span v-if="scope.row.id">{{ scope.row[item.value] }}</span>

          <el-input
            v-else
            v-model="scope.row[item.value]"
            :placeholder="`${item.text}`"
            class="input"
            disabled
          >
            <template #append>
              <el-button
                v-if="pageType !== 'detail'"
                size="small"
                @click="selectedEquipment(scope.$index)"
              >
                选择
              </el-button>
            </template>
          </el-input>
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-pagination
      style="width: 100%;margin-top: 10px;"
      :current-page="listQuery.offset"
      :page-sizes="[10, 20, 30]"
      :page-size="listQuery.limit"
      :total="total"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </detail-block>

  <!-- 选择设备 -->
  <select-equipment-dialog ref="equipmentRef" :is-multi="isMulti" @confirm="confirmSelect" />
</template>
