<!-- 培训记录列表 -->
<script lang="ts" setup name="TrainLog">
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import type { ItrainLoglistQuery } from './plan_interface'
import { exportExcel } from '@/utils/exportXlsx'
import { exportLogList, getDeptTree, getLogList } from '@/api/measure/plan'
import { printJSON } from '@/utils/printUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportFile } from '@/utils/exportUtils'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
const listQuery = ref<ItrainLoglistQuery>({
  createEndTime: '', // 创建结束时间
  createStartTime: '', // 创建开始时间
  logNo: '', // 记录编号
  trainStartTime: '', // 培训开始时间
  trainEndTime: '', // 培训结束时间
  trainName: '', // 培训名称
  offset: 1, // 当前页
  limit: 20, // 每页多少条
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, 'measure-trainLog', listQuery.value)
})
// 重新赋值
listQuery.value = renewSearchParams('measure-trainLog') || {
  createEndTime: '', // 创建结束时间
  createStartTime: '', // 创建开始时间
  logNo: '', // 记录编号
  trainStartTime: '', // 培训开始时间
  trainEndTime: '', // 培训结束时间
  trainName: '', // 培训名称
  offset: 1, // 当前页
  limit: 20, // 每页多少条
}
const checkoutList = ref<string[]>([])
const list = ref([])
const total = ref(0)
const show = ref(true)
const infoId = ref('')
const buttonType = ref('')
// 主管部门下拉框
const options = ref([])
// 培训时间数组
const trainTime = ref('')
// 创建时间数组
const createTime = ref('')
const loadingTable = ref(false)
// 初始化路由
const $router = useRouter()
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   listQuery.value.offset = 1
  // }
  getLogList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
onMounted(() => {
  fetchData(true)
})

// 表头
const columns = ref<TableColumn[]>([
  { text: '记录编号', value: 'logNo', align: 'center', width: '160' },
  { text: '培训名称', value: 'trainName', align: 'center' },
  { text: '培训时间', value: 'trainTime', width: '180', align: 'center' },
  { text: '培训地点', value: 'trainAddress', align: 'center' },
  { text: '培训学时', value: 'trainHour', align: 'center' },
  { text: '培训对象', value: 'trainPerson', align: 'center' },
  { text: '培训人数', value: 'trainNumber', align: 'center' },
  { text: '创建时间', value: 'createTime', width: '180', align: 'center' },
  // { text: '备注', value: 'remark', align: 'center' },
])
// 培训时间数组变更
watch(trainTime, (val) => {
  if (val) {
    listQuery.value.trainStartTime = `${val[0]}`
    listQuery.value.trainEndTime = `${val[1]}`
  }
  else {
    listQuery.value.trainStartTime = ''
    listQuery.value.trainEndTime = ''
  }
})
// 创建时间变更
watch(createTime, (val) => {
  if (val) {
    listQuery.value.createStartTime = `${val[0]}`
    listQuery.value.createEndTime = `${val[1]}`
  }
  else {
    listQuery.value.createStartTime = ''
    listQuery.value.createEndTime = ''
  }
})

// 搜索
const searchList = () => {
  fetchData(true)
}
// 重置
const clearList = () => {
  listQuery.value = {
    createEndTime: '', // 创建结束时间
    createStartTime: '', // 创建开始时间
    logNo: '', // 记录编号
    trainEndTime: '', // 培训结束时间
    trainName: '', // 培训名称
    trainStartTime: '', // 培训开始时间
    offset: 1, // 当前页
    limit: 20, // 每页多少条
  }
  trainTime.value = ''
  createTime.value = ''
  fetchData(true)
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      createEndTime: listQuery.value.createEndTime,
      createStartTime: listQuery.value.createStartTime,
      logNo: listQuery.value.logNo,
      trainEndTime: listQuery.value.trainEndTime,
      trainName: listQuery.value.trainName,
      trainStartTime: listQuery.value.trainStartTime,
      ids: checkoutList.value,
    }
    exportLogList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '培训计录列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}
const { proxy } = getCurrentInstance() as any
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
}
// 点击编辑/详情
const handleEdit = (row: rowReturn, pageType: 'edit' | 'detail') => {
  $router.push(`/train/trainLog/${pageType}/${row.id}`)
}
// 表格多选框
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
// 点击新增
const add = () => {
  $router.push('/train/trainLog/add')
}
// 导出
const exportAll = () => {
  exportExcelBtn()
}
// 获取到组织信息
const getDept = () => {
  const params = {
    roleId: '',
    deptType: '',
    tips: '',
  }
  getDeptTree(params).then((response) => {
    options.value = response.data
  })
}
getDept()
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}
// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '培训计划列表')
  }
  else if (checkoutList.value.length > 0) {
    const printList = list.value.filter((item: { id: string }) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '培训计划列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="searchList" @clear="clearList">
      <search-item>
        <el-input
          v-model.trim="listQuery.logNo"
          placeholder="培训记录编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.trainName"
          placeholder="培训名称"
          clearable
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="trainTime"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="培训时间开始时间"
          end-placeholder="培训时间结束时间"
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="createTime"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="创建时间开始时间"
          end-placeholder="创建时间结束时间"
        />
      </search-item>
    </search-area>
    <table-container>
      <template #btns-right>
        <!-- <icon-button v-if="proxy.hasPerm('/measure/train/tarnLog/import')" icon="icon-import" title="批量导入" type="primary" /> -->
        <!-- <icon-button v-if="proxy.hasPerm('/measure/train/tarnLog/mould')" icon="icon-template" title="模板下载" type="primary" /> -->
        <icon-button v-if="proxy.hasPerm('/measure/train/tarnLog/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/measure/train/tarnLog/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/measure/train/tarnLog/print')" icon="icon-print" title="打印" type="primary" @click="printList" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
      >
        <template #columns>
          <el-table-column label="操作" align="center" width="100" fixed="right">
            <template #default="{ row }">
              <el-button
                v-if="proxy.hasPerm('/measure/train/tarnLog/edit')"
                size="small"
                type="primary"
                link
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'detail')"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

