<!-- 培训计划审批表格 -->
<script lang="ts" setup name="ListApproval">
import type { PropType, Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IButton, IOptions, IPlanList, IlistApprovalQuery } from '../plan_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { printJSON } from '@/utils/printUtils'
import { exportPlanList, getApprovalDelete, getDeptTree, getListSubmit, getapprovalList } from '@/api/measure/plan'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import { exportFile } from '@/utils/exportUtils'
import { cancelApproval, submitApproval } from '@/api/approval'
const props = defineProps({
  status: {
    type: String,
    default: '0',
  },
  buttons: {
    type: Array as PropType<IButton[]>,
    default: () => [],
  },
})
// 获取权限
const { proxy } = getCurrentInstance() as any
// 操作列宽度-计算属性
const operationWidth = computed(() => {
  // 审批中状态时候长度返回错误
  if (props.status === '3' || props.status === '6') {
    props.buttons.length = 4 // 传递长度 + 判断条件下显示按钮长度
  }
  return props.buttons.length * 40 + 23
})

// 查询条件
const listQuery: Ref<IlistApprovalQuery> = ref({
  approvalStatus: props.status, // 审批状态
  formId: SCHEDULE.TRAIN_APPROVAL, // 表单id
  createEndTime: '', // 创建结束时间
  createStartTime: '', // 创建开始时间
  deptId: '', // 部门id
  director: '', // 负责人
  effectiveCompany: '', // 实施单位
  trainEndTime: '', // 培训结束时间
  trainStartTime: '', // 培训开始时间
  offset: 1, // 当前页
  limit: 20, // 每页多少条
})
// 筛选时间段数据-创建时间
const createTimeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 筛选时间段数据-培训时间
const trainTimeRange = ref<[DateModelType, DateModelType]>(['', ''])
// 表格数据
const list = ref<IPlanList[]>([])
// 总数
const total = ref(0)
// 表头
const columns = ref<TableColumn[]>([
  { text: '计划编号', value: 'planNo', align: 'center', width: '160' },
  { 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: 'director', align: 'center' },
  { text: '培训内容', value: 'trainContent', align: 'center' },
  { text: '创建时间', value: 'createTime', width: '180', align: 'center' },
  { text: '审批状态', value: 'approvalStatusName', align: 'center' },
])
// 初始化路由
const $router = useRouter()
// 选中的内容
const checkoutList = ref<string[]>([])
// 点击按钮
const buttonType = ref('')
const loadingTable = ref(false)
// 获取列表
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true

  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  listQuery.value.createEndTime = createTimeRange.value[0] as string || ''
  listQuery.value.createStartTime = createTimeRange.value[1] as string || ''
  listQuery.value.trainEndTime = trainTimeRange.value[0] as string || ''
  listQuery.value.trainStartTime = trainTimeRange.value[1] as string || ''
  getapprovalList(listQuery.value).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
// fetchData(true)
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
// 点击删除或者取消
const handleDelete = (row: IPlanList) => {
  ElMessageBox.confirm(
    '确认删除所选记录吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    getApprovalDelete({ id: row.id, taskId: row.taskId }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      }
    })
  })
}

// 取消
const handleCancel = (row: IPlanList) => {
  const params = {
    processInstanceId: row.processId!,
    comments: '',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      cancelApproval(params).then(() => {
        ElMessage({
          type: 'success',
          message: '取消成功',
        })
        fetchData(true)
      })
    })
}
// 审批组件ref
const approvalDialog = ref()

// 点击搜索
const searchList = () => {
  fetchData(false)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    approvalStatus: props.status, // 审批状态
    formId: SCHEDULE.TRAIN_APPROVAL, // 表单id
    createEndTime: '', // 创建结束时间
    createStartTime: '', // 创建开始时间
    deptId: '', // 部门id
    director: '', // 负责人
    effectiveCompany: '', // 实施单位
    trainEndTime: '', // 培训结束时间
    trainStartTime: '', // 培训开始时间
    offset: 1, // 当前页
    limit: 20, // 每页多少条
  }
  createTimeRange.value = ['', '']
  trainTimeRange.value = ['', '']
  fetchData(true)
}
// 主管部门下拉框
const options = ref<IOptions[]>([])

// 导出
const exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  listQuery.value.ids = []
  if (list.value.length > 0) {
    const params = {
      approvalStatus: props.status, // 审批状态
      formId: SCHEDULE.TRAIN_APPROVAL, // 表单id
      createEndTime: listQuery.value.createEndTime, // 创建结束时间
      createStartTime: listQuery.value.createStartTime, // 创建开始时间
      deptId: listQuery.value.deptId, // 部门id
      director: listQuery.value.director, // 负责人
      effectiveCompany: listQuery.value.effectiveCompany, // 实施单位
      trainEndTime: listQuery.value.trainEndTime, // 培训结束时间
      trainStartTime: listQuery.value.trainStartTime, // 培训开始时间
      offset: 1, // 当前页
      limit: 20, // 每页多少条
      ids: checkoutList.value,
    }
    // 调导出接口
    exportPlanList(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, '培训计划列表.xlsx')
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 goDetail = (row: IPlanList) => {
  $router.push({
    path: `trainPlanApprove/${props.status}/${row.id}`,
    query: { ...row },
  })
}
// 获取到组织信息
const getDept = () => {
  const params = {
    roleId: '',
    deptType: '',
    tips: '',
  }
  getDeptTree(params).then((response) => {
    options.value = response.data
  })
}
getDept()
// 提交
const approvalSubmit = (row: IPlanList) => {
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    getListSubmit({ id: row.id, formId: SCHEDULE.TRAIN_APPROVAL }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        fetchData(true)
      }
    })
  })
}
// 批量导出
const exportAll = () => {
  exportExcelBtn()
}
// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}

// 点击数据后的操作按钮
const clickBtn = (row: IPlanList, buttonType: string) => {
  let from = ''
  switch (buttonType) {
    case '查看':
      goDetail(row)
      break
    case '提交':
      approvalSubmit(row)
      break
    case '编辑':
      if (row.approvalStatusName === '草稿箱') {
        from = 'caogao'
      }
      else {
        from = 'reject'
      }
      $router.push({
        path: `/train/edit/${row.id}`,
        query: {
          from,
          processId: row.processId,
        },
      })
      break
    case '同意':
      approvalDialog.value.initDialog('agree', row.taskId)
      break
    case '驳回':
      approvalDialog.value.initDialog('reject', row.taskId)
      break
    case '拒绝':
      approvalDialog.value.initDialog('refuse', row.taskId)
      break
    case '取消':
      handleCancel(row)
      break
    case '删除':
      handleDelete(row)
      break
  }
}

// 监听status变化，更新approvalStatus
watch (
  () => props.status,
  (newVal: string) => {
    listQuery.value.approvalStatus = newVal
    fetchData(false)
  },
  { immediate: 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: IPlanList) => 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-date-picker
          v-model="trainTimeRange"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled="buttonType === '详情'"
          start-placeholder="培训开始时间"
          end-placeholder="培训结束时间"
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="createTimeRange"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          :disabled="buttonType === '详情'"
          start-placeholder="创建开始时间"
          end-placeholder="创建结束时间"
        />
      </search-item>
      <search-item>
        <dept-select
          ref="deptSelect"
          v-model="listQuery.deptId"
          placeholder="请选择主管部门"
          :dept-show="true"
        />
      </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('/train/plan/approve/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" /> -->
        <icon-button v-if="proxy.hasPerm('/train/plan/approve/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 #preColumns>
          <el-table-column label="序号" width="55" align="center">
            <template #default="scope">
              {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
            </template>
          </el-table-column>
        </template>
        <template #columns>
          <el-table-column label="操作" align="center" :width="operationWidth" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="clickBtn(row, '查看')"
              >
                查看
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/agree') && (status === '0' || status === '2')"
                size="small"
                link
                type="primary"
                :disabled="(row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中') || row.decisionItem === 3"
                @click="clickBtn(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/regect') && (status === '0' || status === '2')"
                size="small"
                link
                type="primary"
                :disabled="(row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中') || row.decisionItem === 3"
                @click="clickBtn(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/refuse') && (status === '0' || status === '2')"
                size="small"
                link
                type="danger"
                :disabled="(row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中') || row.decisionItem === 1 || row.decisionItem === 2"
                @click="clickBtn(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/edit') && (status === '1' || status === '6' || (status === '5' && row.approvalStatusName === '未通过-驳回'))"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '编辑')"
              >
                编辑
              </el-button>
              <el-button
                v-if="status === '1' || status === '6'"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/cancel') && (status === '0' || status === '3')"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatusName !== '审批中'"
                @click="clickBtn(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <el-button
                v-if="proxy.hasPerm('/train/plan/approve/delete') && (status !== '4' && status !== '5')"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                @click="clickBtn(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

