<script lang="ts" setup name="ListPlan">
import type { Ref } from 'vue'
import { getCurrentInstance, reactive, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions, IlistQuery, IlistType } from './plan_interface'
import PlanAdd from './planAdd.vue'
import { exportExcel } from '@/utils/exportXlsx'
import { getDeptTree, getListDelete, getPlanList } from '@/api/system/plan'
const listQuery: Ref<IlistQuery> = ref({
  trainTime: '',
  createTime: '',
  deptId: '',
  effectiveCompany: '',
  director: '',
  offset: 1,
  limit: 10,
})
const checkoutList = ref([])
const list = ref([])
// 删除id
const deleteId = ref('')
const total = ref(0)
const show = ref(true)
const infoId = ref('')
const buttonType = ref('')
// 主管部门下拉框
const options = ref<IOptions[]>([])
const loadingTable = ref(false)
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getPlanList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}
fetchData(true)
const { proxy } = getCurrentInstance() as any
// 表头
const columns = ref([
  {
    text: '计划编号',
    value: 'planNo',
    width: '90',
  },
  {
    text: '培训名称',
    value: 'planName',
    width: '90',
  },
  {
    text: '培训对象',
    value: 'trainPerson',
    width: '90',
  },
  {
    text: '培训人数',
    value: 'trainNumber',
    width: '90',
  },
  {
    text: '培训学时',
    value: 'trainHour',
    width: '90',
  },
  {
    text: '培训时间',
    value: 'trainTime',
    width: '90',
  },
  {
    text: '主管部门',
    value: 'deptName',
  },
  {
    text: '实施单位',
    value: 'effectiveCompany',
    width: '90',
  },
  {
    text: '培训内容',
    value: 'trainContent',
    width: '90',
  },
  {
    text: '创建时间',
    value: 'createTime',
    width: '90',
  },
  {
    text: '备注',
    value: 'remark',
    width: '100',
  },
])
// 搜索
const searchList = () => {
  fetchData(true)
}
// 重置
const clearList = () => {
  listQuery.value = {
    trainTime: '',
    createTime: '',
    deptId: '',
    effectiveCompany: '',
    director: '',
    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: IlistType, index: number) => ({ index: index + 1, planNo: item.planNo, planName: item.planName, trainPerson: item.trainPerson, trainNumber: item.trainNumber, trainHour: item.trainHour, trainTime: item.trainTime, deptName: item.deptName, effectiveCompany: item.effectiveCompany, director: item.director, trainContent: item.trainContent, createTime: item.createTime, remark: item.remark })),
      name: '培训记录',
      titleArr: ['序号', '培训计划编号', '培训名称', '培训对象', '培训人数', '培训学时', '培训时间', '主管部门', '实施单位', '负责人', '培训内容', '创建时间', '备注'],
      sheetName: 'sheet1',
    })
  }
  else if (checkoutList.value.length > 0) {
    exportExcel({
      json: checkoutList.value.map((item: IlistType, index: number) => ({ index: index + 1, planNo: item.planNo, planName: item.planName, trainPerson: item.trainPerson, trainNumber: item.trainNumber, trainHour: item.trainHour, trainTime: item.trainTime, deptName: item.deptName, effectiveCompany: item.effectiveCompany, director: item.director, trainContent: item.trainContent, createTime: item.createTime, remark: item.remark })),
      name: '培训记录',
      titleArr: ['序号', '培训计划编号', '培训名称', '培训对象', '培训人数', '培训学时', '培训时间', '主管部门', '实施单位', '负责人', '培训内容', '创建时间', '备注'],
      sheetName: 'sheet1',
    })
  }
  else {
    ElMessage.warning('暂无数据')
  }
  loading.close()
}
// 关闭编辑
const close = () => {
  show.value = true
  fetchData(true)
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  planName: string
}
const handleEdit = (index: string, row: rowReturn, type: string) => {
  console.log(row)
  infoId.value = row.id
  buttonType.value = type
  show.value = false
}
// 点击删除
const handleDelete = (index: string, row: rowReturn) => {
  ElMessageBox.confirm(
    `确认删除${row.planName}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      getListDelete({ id: row.id as string }).then((res) => {
        if (res.code === 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        }
      })
    })
}
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-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-item>
          <el-select
            v-model="listQuery.deptId"
            clearable
            placeholder="主管部门"
            size="default"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.effectiveCompany"
            placeholder="实施单位"
            clearable
          />
        </search-item>
        <search-item>
          <el-input
            v-model.trim="listQuery.director"
            placeholder="负责人"
            clearable
          />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <el-button v-if="proxy.hasPerm('/measure/train/plan/add')" type="primary" @click="add">
            新建
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/train/plan/export')" type="primary" @click="exportAll">
            导出
          </el-button>
          <el-button v-if="proxy.hasPerm('/measure/train/plan/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="255">
              <template #default="{ row }">
                <el-button
                  v-if="proxy.hasPerm('/measure/train/plan/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>
                <el-button
                  v-if="proxy.hasPerm('/measure/train/plan/delete')"
                  size="small"
                  link
                  type="danger"
                  @click="handleDelete(row.$index, row)"
                >
                  删除
                </el-button>
                <el-button
                  size="small"
                  link
                  type="primary"
                >
                  二维码
                </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>
