<!-- 训练登记表列表 -->
<script name="TrainList" lang="ts" setup>
import type { DateModelType } from 'element-plus'
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IListQuery, ITrainInfo } from './train-interface'
import type { IDictType } from '@/commonInterface/resource-interface'
import { deleteTrainInfo, getTrainList } from '@/api/resource/train'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'

// 定义变量
const { proxy } = getCurrentInstance() as any
const router = useRouter()
const searchQuery = ref<IListQuery>({
  trainNo: '',
  dutyLeader: '',
  createTimeStart: '',
  createTimeEnd: '',
  offset: 1,
  limit: 20,
})
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<Array<TableColumn>>([
  { text: '登记表编号', value: 'trainNo', align: 'center', width: '160' },
  { text: '训练场地', value: 'trainSiteName', align: 'center', width: '100' },
  { text: '训练组别', value: 'trainGroupName', align: 'center' },
  { text: '培训内容', value: 'trainText', align: 'center' },
  { text: '培训方式', value: 'trainWayName', align: 'center', width: '120' },
  { text: '值班领导', value: 'dutyLeader', align: 'center', width: '100' },
  { text: '创建时间', value: 'createTime', align: 'center' },
]) // 表头
const list = ref([]) // 表格数据

const trainSiteDict = ref<Array<IDictType>>([]) // 训练地点 HK / XC
const trainGroupDict = ref<Array<IDictType>>([]) // 培训组别
const trainContentDict = ref<Array<IDictType>>([]) // 培训内容
const trainWayDict = ref<Array<IDictType>>([]) // 培训方式

// 逻辑
const getTrainGroupName = (group: string) => {
  if (group === '' || group === undefined) { return '' }
  else {
    const groupArray = group.split(',')
    if (groupArray.length > 0) {
      let retStr = ''
      groupArray.forEach((item) => {
        const target = trainGroupDict.value.filter(dict => dict.value === item)
        if (target.length > 0) {
          retStr += `${target[0].name}, `
        }
      })
      if (retStr.length > 0) {
        return retStr.substring(0, retStr.length - 2)
      }
      else {
        return ''
      }
    }
  }
}

const addTrain = () => {
  router.push({
    query: {
      type: 'create',
    },
    path: 'train/detail',
  })
}

// 获取数据列表
const fetchData = (isNowPage = false) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    searchQuery.value.offset = 1
  }
  getTrainList(searchQuery.value).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: ITrainInfo) => ({
        ...item,
        trainGroupName: getTrainGroupName(item.trainGroup),
        trainGroupArray: item.trainGroup.split(','),
      }))
      total.value = Number(res.data.total)
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}

const search = () => {
  fetchData()
}

const clearList = () => {
  searchQuery.value = {
    trainNo: '',
    dutyLeader: '',
    createTimeStart: '',
    createTimeEnd: '',
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.value.limit = val.size
  }
  if (val && val.page) {
    searchQuery.value.offset = val.page
  }
  fetchData(true)
}

// 查看详情信息
const detail = (row: any) => {
  sessionStorage.setItem('trainInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'detail',
      id: row.id,
    },
    path: 'train/detail',
  })
}

// 编辑信息
const update = (row: any) => {
  sessionStorage.setItem('trainInfo', JSON.stringify(row))
  router.push({
    query: {
      type: 'update',
      id: row.id,
    },
    path: 'train/detail',
  })
}

// 删除信息
const deleteTrainById = (id: string, trainNo: string) => {
  ElMessageBox.confirm(`是否删除训练登记表 ${trainNo}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteTrainInfo({ id }).then((res: { code: number; message: any }) => {
      if (res.code === 200) {
        ElMessage.success(`训练登记表 ${trainNo} 删除成功`)
        fetchData()
      }
      else {
        ElMessage.error(`训练登记表 ${trainNo} 删除失败: ${res.message}`)
      }
    })
  })
}

const getTrainSiteDict = () => {
  if (sessionStorage.getItem('bizTrainSite') === null || sessionStorage.getItem('bizTrainSite') === undefined) {
    getDictByCode('bizTrainSite').then((res) => {
      if (res.code === 200) {
        trainSiteDict.value = res.data
        sessionStorage.setItem('bizTrainSite', JSON.stringify(trainSiteDict.value))
      }
    })
  }
  else {
    trainSiteDict.value = JSON.parse(sessionStorage.getItem('bizTrainSite')!)
  }
}
const getTrainGroupDict = async () => {
  if (sessionStorage.getItem('bizGroupCode') === null || sessionStorage.getItem('bizGroupCode') === undefined) {
    await getDictByCode('bizGroupCode').then((res) => {
      if (res.code === 200) {
        trainGroupDict.value = res.data
        sessionStorage.setItem('bizGroupCode', JSON.stringify(trainGroupDict.value))
      }
    })
  }
  else {
    trainGroupDict.value = JSON.parse(sessionStorage.getItem('bizGroupCode')!)
  }
}
const getTrainContentDict = () => {
  if (sessionStorage.getItem('bizTrainContent') === null || sessionStorage.getItem('bizTrainContent') === undefined) {
    getDictByCode('bizTrainContent').then((res) => {
      if (res.code === 200) {
        trainContentDict.value = res.data
        sessionStorage.setItem('bizTrainContent', JSON.stringify(trainContentDict.value))
      }
    })
  }
  else {
    trainContentDict.value = JSON.parse(sessionStorage.getItem('bizTrainContent')!)
  }
}

const getTrainWayDict = () => {
  if (sessionStorage.getItem('bizTrainWay') === null || sessionStorage.getItem('bizTrainWay') === undefined) {
    getDictByCode('bizTrainWay').then((res) => {
      if (res.code === 200) {
        trainWayDict.value = res.data
        sessionStorage.setItem('bizTrainWay', JSON.stringify(trainWayDict.value))
      }
    })
  }
  else {
    trainWayDict.value = JSON.parse(sessionStorage.getItem('bizTrainWay')!)
  }
}

const getDict = async () => {
  getTrainSiteDict()
  await getTrainGroupDict()
  getTrainContentDict()
  getTrainWayDict()
}

watch(dateRange, (val) => {
  if (val) {
    searchQuery.value.createTimeStart = dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss') === 'Invalid Date' ? '' : dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss')
    searchQuery.value.createTimeEnd = dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss') === 'Invalid Date' ? '' : dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss')
  }
  else {
    searchQuery.value.createTimeStart = ''
    searchQuery.value.createTimeEnd = ''
  }
})

onMounted(async () => {
  await getDict()
  fetchData()
})
</script>

<template>
  <app-container>
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="clearList">
      <search-item>
        <el-input v-model="searchQuery.trainNo" placeholder="登记表编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model="searchQuery.dutyLeader" placeholder="值班领导" clearable />
      </search-item>
      <search-item>
        <el-date-picker v-model="dateRange" type="daterange" start-placeholder="创建时间（开始）" end-placeholder="创建时间（结束）" />
      </search-item>
    </search-area>

    <!-- 表格数据展示 -->
    <table-container>
      <!-- 表头区域 -->
      <template #btns-right>
        <!-- <icon-button v-if="proxy.hasPerm(`/measure/person/list/add`)" icon="icon-add" title="新建" @click="addStaff" /> -->
        <icon-button v-if="proxy.hasPerm('/resource/person/train/add')" icon="icon-add" title="新建" @click="addTrain" />
      </template>

      <!-- 表格区域 -->
      <normal-table
        id="registerTabel"
        :data="list" :total="total" :columns="columns"
        :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
        :list-loading="loadingTable"
        @change="changePage"
      >
        <template #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column fixed="right" label="操作" align="center" width="130">
            <template #default="{ row }">
              <el-button v-if="proxy.hasPerm('/resource/person/train/edit')" size="small" type="primary" link @click="update(row)">
                编辑
              </el-button>
              <el-button size="small" type="primary" link @click="detail(row)">
                详情
              </el-button>
              <el-button v-if="proxy.hasPerm('/resource/person/train/del')" size="small" type="danger" link @click="deleteTrainById(row.id, row.trainNo)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

