<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: 10,
})
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 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
  })
}
fetchData(true)

// 表头
const columns = ref([
  {
    text: '记录编号',
    value: 'logNo',
  },
  {
    text: '培训名称',
    value: 'trainName',
    width: '120',
  },
  {
    text: '培训时间',
    value: 'trainTime',
    width: '160',
  },
  {
    text: '培训地点',
    value: 'trainAddress',
    width: '100',
  },
  {
    text: '培训学时',
    value: 'trainHour',
    width: '100',
  },
  {
    text: '培训对象',
    value: 'trainPerson',
    width: '100',
  },
  {
    text: '培训人数',
    value: 'trainNumber',
    width: '100',
  },
  {
    text: '创建时间',
    value: 'createTime',
    width: '160',
  },
  {
    text: '备注',
    value: 'remark',
    width: '120',
  },
])
// 搜索
const searchList = () => {
  fetchData(true)
}
// 重置
const clearList = () => {
  listQuery.value = {
    trainTime: '',
    createTime: '',
    logNo: '',
    trainName: '',
    offset: 1,
    limit: 10,
  }
}
// 导出
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
// 关闭编辑
const close = () => {
  show.value = true
  fetchData(true)
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
}
const handleEdit = (index: string, row: rowReturn, type: string) => {
  console.log(row)
  infoId.value = row.id
  buttonType.value = type
  show.value = false
}
const handelClick = (text: string) => {}
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
}
const add = () => {
  infoId.value = ''
  buttonType.value = '新建'
  show.value = false
}
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>
          <el-button v-if="proxy.hasPerm('/measure/train/tarnLog/import')" type="primary" @click="add">
            批量导入
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/train/tarnLog/mould')" type="primary" @click="add">
            模板下载
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/train/tarnLog/add')" type="primary" @click="add">
            新建
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/train/tarnLog/export')" type="primary" @click="exportAll">
            导出
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/train/tarnLog/print')" v-print="printObj" type="primary">
            打印
          </el-button>
        </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.$index, row, '编辑')"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit(row.$index, row, '详情')"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
  <plan-add
    v-else :info-id="infoId"
    :button-type="buttonType"
    @close="close"
  />
</template>

<style lang="scss" scoped>
.pagination {
  position: fixed;
  bottom: 0;
}
</style>
