<!-- 分包方人员 -->
<script name="SubpackageDirectoriesPerson" 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 { IPerson } from '../directories-interface'
import { getDictByCode } from '@/api/system/dict'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import useUserStore from '@/store/modules/user'
import { validateMobile } from '@/utils/validate'
import { useCheckList } from '@/commonMethods/useCheckList'
import { addPerson, deletePerson, getPersonList } from '@/api/business/subpackage/directories'
import { useDoubleClickTableRow, useSetAllRowReadable } from '@/commonMethods/useSetAllRowReadable'
import type { deptType, dictType } from '@/global'
const props = defineProps({
  pageType: { // 页面类型
    type: String,
    require: true,
  },
  id: {
    type: String,
    require: true,
  },
})
// 查询条件
const listQuery = ref({
  id: props.id!,
  offset: 1,
  limit: 20,
})
const loadingTable = ref(false) // 表格loading
const user = useUserStore() // 用户信息
const total = ref(0) // 数据总条数
const list = ref<IPerson[]>([]) // 表格数据
const checkoutList = ref<IPerson[]>([]) // 选中数据
const checkoutIds = ref<string[]>([])// 删除用的ids
const columns = [ // 表头
  { text: '姓名', value: 'name', align: 'center', required: true },
  { text: '工作部门', value: 'department', align: 'center', required: true },
  { text: '职务', value: 'job', align: 'center', required: true },
  { text: '联系方式', value: 'phone', align: 'center', required: true, reg: validateMobile },
]

// -----------------------------------------列表数据--------------------------------------------------
// 数据查询
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
  })
}

// 改变页容量
function handleSizeChange(val: number) {
  listQuery.value.limit = val
  fetchData()
}
// 改变当前页
function handleCurrentChange(val: number) {
  listQuery.value.offset = val
  fetchData(true)
}

// 多选
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
// --------------------------------------------按钮------------------------------------------------
// 增加行
const addRow = () => {
  if (useCheckList(list.value, columns, '分包方人员')) {
    useSetAllRowReadable(list.value)
    list.value.push({
      name: '', // 姓名
      department: '', // 工作部门
      job: '', // 职务
      phone: '', // 联系方式
      outsourcerId: props.id, // 分包方id
      editable: true, // 是否可编辑
    })
  }
}
// 点击保存增加人员
const savePerson = () => {
  if (!useCheckList(list.value, columns, '分包方人员')) {
    return false
  }
  const params = list.value.filter(item => !item.id)
  loadingTable.value = true
  addPerson(params).then(() => {
    ElMessage.success('新增分包方人员成功')
    fetchData()
  }).catch(() => {
    loadingTable.value = false
  })
}
// 删除行
const deleteRow = 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
  }
}
// -------------------------------------------钩子-------------------------------------------------
onMounted(async () => {
  fetchData()
})
defineExpose({
  savePerson,
})
</script>

<template>
  <detail-block title="分包方人员">
    <template v-if="pageType !== 'detail'" #btns>
      <el-button type="primary" @click="addRow">
        增加行
      </el-button>
      <el-button type="info" @click="deleteRow">
        删除行
      </el-button>
    </template>

    <el-table v-loading="loadingTable" :data="list" border style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column v-if="pageType !== 'detail'" type="selection" align="center" 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"
        align="center"
      >
        <template #header>
          <span v-show="item.required && pageType !== 'detail'" style="color: red;">*</span><span>{{ item.text }}</span>
        </template>
        <template #default="scope">
          <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
          <el-input v-else v-model="scope.row[item.value]" :autofocus="true" :placeholder="`${item.text}`" class="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>
</template>
