<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, ISupplier, IlistQuery, IlistType } from './plan_interface'
import { exportExcel } from '@/utils/exportXlsx'
import { exportPlanList, getDeptTree, getListDelete, getPlanList } from '@/api/system/plan'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
const listQuery: Ref<IlistQuery> = ref({
  createEndTime: '',
  createStartTime: '',
  deptId: '',
  director: '',
  effectiveCompany: '',
  ids: [],
  trainEndTime: '',
  trainStartTime: '',
  offset: 1,
  limit: 20,
})
const checkoutList = ref<string[]>([])
const list = ref<ISupplier[]>([])
// 删除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 trainTimeArr = ref([
  listQuery.value.trainStartTime,
  listQuery.value.trainEndTime,
])
// 创建时间数组
const createTimeArr = ref([
  listQuery.value.createStartTime,
  listQuery.value.createEndTime,
])
const $router = useRouter()
const fetchData = (isNowPage: boolean) => {
  listQuery.value.trainStartTime = trainTimeArr.value[0] || ''
  listQuery.value.trainEndTime = trainTimeArr.value[1] || ''
  listQuery.value.createStartTime = createTimeArr.value[0] || ''
  listQuery.value.createEndTime = createTimeArr.value[0] || ''
  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',
    align: 'center',
  },
  {
    text: '培训名称',
    value: 'planName',
    align: 'center',
  },
  {
    text: '培训对象',
    value: 'trainPerson',
    align: 'center',
  },
  {
    text: '培训人数',
    value: 'trainNumber',
    align: 'center',
  },
  {
    text: '培训学时',
    value: 'trainHour',
    align: 'center',
  },
  {
    text: '培训时间',
    value: 'trainTime',
    width: '180',
    align: 'center',
  },
  {
    text: '主管部门',
    value: 'deptName',
    align: 'center',
  },
  {
    text: '实施单位',
    value: 'effectiveCompany',
    align: 'center',
  },
  {
    text: '培训内容',
    value: 'trainContent',
    align: 'center',
  },
  {
    text: '创建时间',
    value: 'createTime',
    width: '180',
    align: 'center',
  },
  {
    text: '备注',
    value: 'remark',
    align: 'center',
  },
])
// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    createEndTime: '',
    createStartTime: '',
    deptId: '',
    director: '',
    effectiveCompany: '',
    ids: [],
    trainEndTime: '',
    trainStartTime: '',
    offset: 1,
    limit: 20,
  }
  trainTimeArr.value = []
  createTimeArr.value = []
}
// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      createEndTime: '',
      createStartTime: '',
      deptId: 0,
      director: '',
      effectiveCompany: '',
      trainEndTime: '',
      trainStartTime: '',
      ids: checkoutList.value,
    }
    exportPlanList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '培训计划列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}
// 关闭编辑
const close = () => {
  show.value = true
  fetchData(true)
}
// 点击编辑id和删除row类型
interface rowReturn {
  id: string
  planName: string
}
// 点击编辑/详情
const handleEdit = (row: rowReturn, pageType: 'edit' | 'detail') => {
  $router.push(`/train/${pageType}/${row.id}`)
}
// 点击删除
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.map((item: { id: string }) => item.id)
}
const add = () => {
  $router.push('/train/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: ISupplier) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '培训计划列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
const qrDialog = ref()
// 点击二维码
const qrDialogShow = (row: rowReturn) => {
  qrDialog.value.initDialog(row.id, row.planName)
}
</script>

<template>
  <div v-if="show">
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="clearList">
        <search-item>
          <el-date-picker
            v-model="trainTimeArr"
            type="datetimerange"
            range-separator="到"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
            start-placeholder="培训时间开始时间"
            end-placeholder="培训时间结束时间"
          />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="createTimeArr"
            type="datetimerange"
            range-separator="到"
            format="YYYY/MM/DD HH:mm:ss"
            value-format="YYYY-MM-DD h:m:s"
            start-placeholder="创建时间开始时间"
            end-placeholder="创建时间结束时间"
          />
        </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>
          <icon-button
            v-if="proxy.hasPerm('/measure/train/plan/add')"
            icon="icon-add"
            title="新建"
            type="primary"
            @click="add"
          />
          <icon-button
            v-if="proxy.hasPerm('/measure/train/plan/export')"
            icon="icon-export"
            title="导出"
            type="primary"
            @click="exportAll"
          />
          <icon-button
            v-if="proxy.hasPerm('/measure/train/plan/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="190">
              <template #default="{ row }">
                <el-button
                  v-if="proxy.hasPerm('/measure/train/plan/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>
                <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"
                  @click="qrDialogShow(row)"
                >
                  二维码
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
    <qr-dialog ref="qrDialog" />
  </div>
</template>
