<!-- 标准装置台账信息详情 计量人员 -->
<script name="StandardBookPerson" lang="ts" setup>
import type { Ref } from 'vue'
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import type { IPersonList } from '../book-interface'
import selectPerson from '../dialog/selectPerson.vue'
import useUserStore from '@/store/modules/user'
import { useCheckList } from '@/commonMethods/useCheckList'
import { addPerson, deletePerson, getPersonList } from '@/api/equipment/standard/book'
const props = defineProps({
  pageType: { // 页面类型 add新建 edit编辑 detail详情
    type: String,
    default: 'detail',
  },
  standardId: { // id
    type: String,
  },
})
// 查询条件
const listQuery = ref({
  standardId: props.standardId!,
  offset: 1,
  limit: 20,
})
const user = useUserStore() // 用户信息
const loadingTable = ref(false) // 表格loading
const list = ref<IPersonList[]>([]) // 表格数据
const checkoutList = ref<IPersonList[]>([]) // 多选数据\
const personRef = ref() // 选择计量人员组件ref
const total = ref(0) // 数据总条数
const checkoutIds = ref<string[]>([])// 删除用的ids
const columns = [ // 表头
  { text: '人员编号', value: 'staffNo', align: 'center', required: true },
  { text: '姓名', value: 'staffName', align: 'center' },
  { text: '职称', value: 'titleExperience', align: 'center' },
  { text: '检定员证书', value: 'certName', align: 'center' },
  { text: '证书有效期', value: 'effectiveDate', align: 'center', width: '120' },
  { text: '计量专业', value: 'major', align: 'center' },
]
// -----------------------------------------methods--------------------------------------
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getPersonList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}

const selectIndex = ref(0) // 选中第几行
// 点击增加行
const add = () => {
  const index = list.value.findIndex((item: IPersonList) => !item.staffNo && !item.staffName)
  if (index !== -1) {
    ElMessage.warning('请完善上一条人员信息')
    return
  }
  list.value.unshift({
    id: '', // 主键
    staffNo: '', // 人员编号
    staffName: '', // 姓名
    titleExperience: '', // 职称
    certName: '', // 检定员证书
    effectiveDate: '', // 证书有效期
    major: '', // 计量专业
  })
}
// 点击删除行
const del = async () => {
  if (!checkoutList.value.length) {
    ElMessage.warning('请选中要删除的行')
    return
  }
  // 前端删除
  list.value = list.value.filter(item => !checkoutList.value.includes(item))

  // 接口删除
  checkoutIds.value = checkoutList.value.map(item => item.id!)
  checkoutIds.value = checkoutIds.value.filter(item => item)
  if (checkoutIds.value.length) {
    loadingTable.value = true
    await deletePerson({ ids: checkoutIds.value })
    fetchData()
    loadingTable.value = false
  }
}
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// 点击选择人员
const selectedPerson = (index: number) => {
  selectIndex.value = index
  personRef.value.initDialog()
}
// 选择好计量人员
const confirmSelect = (val: any) => {
  const index = list.value.findIndex((i: IPersonList) => val[0].staffNo === i.staffNo)
  if (index !== -1) {
    ElMessage.warning('此人员已添加过')
    return
  }
  const params = {
    id: '',
    staffId: val[0].id,
    standardId: props.standardId,
    remark: val[0].remark,
    staffNo: val[0].staffNo, // 人员编号
    staffName: val[0].staffName, // 人员名称
    titleExperience: val[0].titleExperience, // 职称
    certName: val[0].certName, // 检定员证书
    effectiveDate: val[0].effectiveDate, // 证书有效期
    major: val[0].major, // 计量专业
  }
  list.value.splice(selectIndex.value, 1, params)
}

// 点击保存增加人员
const savePerson = () => {
  if (!useCheckList(list.value, columns, '计量人员')) {
    return false
  }
  const tempParams = list.value.filter(item => !item.id)
  const params = tempParams.map((item) => {
    return {
      remark: item.remark,
      standardId: item.standardId,
      staffId: item.staffId,
    }
  })
  loadingTable.value = true
  addPerson({ 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)
}

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

<template>
  <detail-block title="计量人员">
    <template v-if="pageType !== 'detail'" #btns>
      <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%;"
      @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 === 'staffNo' && 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
                size="small"
                @click="selectedPerson(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-person ref="personRef" @confirm="confirmSelect" />
</template>
