<script lang="ts" setup name="ListPlan">
import type { Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import type { IlistQuerys, IlistTypes } from './plan_interface'
import PlanAdd from './trainLogAdd.vue'
import { exportExcel } from '@/utils/exportXlsx'
import { getDeptTree, getLogList } from '@/api/system/plan'
const listQuery: Ref<IlistQuerys> = ref({
  trainTime: '',
  createTime: '',
  logNo: '',
  trainName: '',
  offset: 1,
  limit: 20,
})
const checkoutList = ref([])
const list = ref([])
const total = ref(0)
const show = ref(true)
const infoId = ref('')
const buttonType = ref('')
// 主管部门下拉框
const options = ref([])
const loadingTable = ref(false)
// 初始化路由
const $router = useRouter()
const fetchData = (isNowPage: boolean) => {
  if (listQuery.value.trainTime === null) {
    listQuery.value.trainTime = ''
  }
  if (listQuery.value.createTime === null) {
    listQuery.value.createTime = ''
  }
  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
  })
}
fetchData(true)

// 表头
const columns = ref([
  {
    text: '记录编号',
    value: 'logNo',
    align: 'center',
  },
  {
    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',
  },
])
// 搜索
const searchList = () => {
  fetchData(true)
}
// 重置
const clearList = () => {
  listQuery.value = {
    trainTime: '',
    createTime: '',
    logNo: '',
    trainName: '',
    offset: 1,
    limit: 20,
  }
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    exportExcel({
      json: list.value.map((item: IlistTypes, index: number) => ({ index: index + 1, logNo: item.logNo, trainName: item.trainName, trainTime: item.trainTime, trainAddress: item.trainAddress, trainHour: item.trainHour, trainPerson: item.trainPerson, trainNumber: item.trainNumber, createTime: item.createTime, remark: item.remark })),
      name: '培训记录',
      titleArr: ['序号', '记录编号', '培训名称', '培训时间', '培训地点', '培训学时', '培训时间', '培训人数', '创建时间', '备注'],
      sheetName: 'sheet1',
    })
  }
  else if (checkoutList.value.length > 0) {
    exportExcel({
      json: checkoutList.value.map((item: IlistTypes, index: number) => ({ index: index + 1, logNo: item.logNo, trainName: item.trainName, trainTime: item.trainTime, trainAddress: item.trainAddress, trainHour: item.trainHour, trainPerson: item.trainPerson, trainNumber: item.trainNumber, createTime: item.createTime, remark: item.remark })),
      name: '培训记录',
      titleArr: ['序号', '记录编号', '培训名称', '培训时间', '培训地点', '培训学时', '培训时间', '培训人数', '创建时间', '备注'],
      sheetName: 'sheet1',
    })
  }
  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 handelClick = (text: string) => {}
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
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)
}
// 打印
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '证书报告模板', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
</script>

<template>
  <div v-if="show">
    <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="listQuery.trainTime"
            type="datetime"
            placeholder="培训时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="listQuery.createTime"
            type="datetime"
            placeholder="创建时间"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
          />
        </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')" v-print="printObj" icon="icon-print" title="打印" type="primary" />
        </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="140">
              <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>
  </div>
</template>

