<script lang="ts" setup name="ApplyList">
import { ref } from 'vue'
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import type { IlistQuery, IlistType } from '@/views/device/receive/receive'
import ButtonBox from '@/views/device/receive/buttonBox.vue'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { exportFile } from '@/utils/exportUtils'
import { printJSON } from '@/utils/printUtils'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import {
  delReceiveApplyList,
  exportReceiveApplyList,
  getReceiveApplyList,
  submitReceiveApplyList,
} from '@/api/device/receive'
import { submitApproval } from '@/api/approval'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import type { userType } from '@/views/system/user/user-interface'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
import { getUserList } from '@/api/system/user'

const loadingTable = ref(false) // 表格loading
const active = ref('0') // 选中的按钮
const approvalDialog = ref() // 审批对话框显隐
const usePersonList = ref<userType[]>([]) // 申请人列表（用户）
const useDeptList = ref<deptType[]>([]) // 部门列表

// 查询条件
const listQuery: Ref<IlistQuery> = ref({
  applyNo: '', // 申请编号
  applyName: '', // 申请名称
  applyUnit: '', // 申请部门id
  applyUnitName: '', // 申请部门名称
  applyPerson: '', // 申请人id
  applyPersonName: '', // 申请人姓名
  startTime: '', // 领用开始日期
  endTime: '', // 领用结束日期
  approvalStatus: '', // 	审批状态
  processResult: '', // 	处置结果
  applyType: '1', // 申请类型 领用1
  createUser: '', // 创建人
  formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL,
  offset: 1,
  limit: 20,
})
// 审批状态字典
const approvalStatusMap: { [key: string]: string } = {
  1: '草稿箱',
  2: '待审批',
  3: '审批中',
  4: '已通过',
  5: '未通过',
  6: '已取消',
  7: '非草稿',
  8: '未通过-驳回',
}
// 审批状态字典
const approvalStatusReserveMap: { [key: string]: string } = {
  '草稿箱': '1',
  '待审批': '2',
  '审批中': '3',
  '已通过': '4',
  '未通过': '5',
  '已取消': '6',
  '非草稿': '7',
  '未通过-驳回': '8',
}
// 表格数据
const list = ref<IlistType[]>([])
const { proxy } = getCurrentInstance() as any
// 总数
const total = ref(20)
// 表头
const columns = ref<TableColumn[]>([
  { text: '申请编号', value: 'applyNo', align: 'center' },
  { text: '申请名称', value: 'applyName', align: 'center' },
  { text: '申请部门', value: 'applyUnitName', align: 'center' },
  { text: '申请人', value: 'applyPersonName', align: 'center' },
  { text: '领用时间', value: 'time', align: 'center' },
  { text: '审批状态', value: 'approvalStatus', align: 'center' },
])
// 选中的内容
const checkoutList = ref<string[]>([])
// 筛选时间段数据
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])

// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  listQuery.value.startTime = timeRange.value[0] as string || ''
  listQuery.value.endTime = timeRange.value[1] as string || ''
  listQuery.value.approvalStatus = active.value
  getReceiveApplyList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: IlistType) => {
      return {
        ...item,
        approvalStatus: approvalStatusMap[item.approvalStatus],
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  })
}

// 重置
const clearList = () => {
  listQuery.value = {
    applyNo: '', // 申请编号
    applyName: '', // 申请名称
    applyUnit: '', // 申请部门
    applyPerson: '', // 申请人
    startTime: '', // 申请开始日期
    endTime: '', // 申请结束日期
    approvalStatus: '', // 	审批状态
    processResult: '', // 	处置结果
    applyType: '1', // 申请类型 领用1
    createUser: '', // 创建人
    formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL,
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(true)
}

// 搜索
const searchList = () => {
  fetchData(true)
}

// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
const $router = useRouter()

// 新建
const add = () => {
  $router.push({ path: '/receive/add', query: { typeValue: 'add' } })
}

// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      applyNo: listQuery.value.applyNo, // 申请编号
      applyName: listQuery.value.applyName, // 申请名称
      applyUnit: listQuery.value.applyUnit, // 申请部门
      applyPerson: listQuery.value.applyPerson, // 申请人
      startTime: listQuery.value.startTime, // 申请开始日期
      endTime: listQuery.value.endTime, // 申请结束日期
      approvalStatus: listQuery.value.approvalStatus, // 	审批状态
      processResult: listQuery.value.processResult, // 	处置结果
      applyType: listQuery.value.applyType, // 申请类型 领用0
      createUser: listQuery.value.createUser, // 创建人
      formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL,
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    // 调导出接口
    exportReceiveApplyList(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)
}

// 打印列表
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: IlistType) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '设备领用申请列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

// 操作
const handleEdit = (row: IlistType, val: string, title = '') => {
  if (val === '取消') {
    const params = {
      taskId: row.taskId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        submitApproval('revoke', params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
        })
        fetchData(true)
      })
  }
  else if (val === '删除') {
    ElMessageBox.confirm(
      '确认删除该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        delReceiveApplyList({ id: row.id, taskId: row.taskId }).then((res) => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '提交') {
    ElMessageBox.confirm(
      '确认提交该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        submitReceiveApplyList({ id: row.id, formId: SCHEDULE.DEVICE_CONSUMING_APPROVAL }).then((res) => {
          ElMessage({
            type: 'success',
            message: '已提交',
          })
        })
        fetchData(true)
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', row.taskId)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', row.taskId)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', row.taskId)
  }
  else if (val === '查看' || val === '编辑') {
    $router.push({
      path: `/receive/${title}`,
      query: {
        typeValue: title,
        approvalStatus: approvalStatusReserveMap[row.approvalStatus],
        id: row.id,
        taskId: row.taskId,
        processId: row.processId, // 查询审批记录使用
      },
    })
  }
}
// 按钮切换
const changeCurrentButton = (val: string) => {
  active.value = val
  clearList()
}

// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}

// 获取用户列表(增加模糊查询)
const fetchUserList = () => {
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    usePersonList.value = res.data.rows
  })
}

// 获取使用部门
const fetchDeptTreeList = () => {
  getDeptTreeList().then((res: any) => {
    if (res.data) { // 将列表转树结构
      useDeptList.value = toTreeList(res.data, '0', true)
    }
  })
}

onMounted(() => {
  fetchData(true)
  // 获取使用部门
  fetchDeptTreeList()
  fetchUserList()
})
</script>

<template>
  <app-container>
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.applyNo"
          placeholder="申请编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.applyName"
          placeholder="申请名称"
          clearable
        />
      </search-item>
      <search-item>
        <dept-select v-model="listQuery.applyUnit" placeholder="请选择申请部门" :data="useDeptList" />
      </search-item>
      <search-item>
        <el-select v-model="listQuery.applyPerson" placeholder="请选择申请人" style="width: 100%;">
          <el-option v-for="item in usePersonList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          range-separator="到"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          start-placeholder="领用开始日期"
          end-placeholder="领用结束日期"
        />
      </search-item>
    </search-area>

    <table-container>
      <template #btns-right>
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/export')" icon="icon-export" title="导出" type="primary" @click="exportAll" />
        <icon-button v-if="proxy.hasPerm('/device/receive/applyList/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="220" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row, '查看', 'detail')"
              >
                查看
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/agree') && (active === '0' || active === '2')"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatus !== '待审批' && row.approvalStatus !== '审批中'"
                @click="handleEdit(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/reject') && (active === '0' || active === '2')"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatus !== '待审批' && row.approvalStatus !== '审批中'"
                @click="handleEdit(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/refuse') && (active === '0' || active === '2')"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatus !== '待审批' && row.approvalStatus !== '审批中'"
                @click="handleEdit(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/edit') && (active === '1' || active === '6')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '编辑', 'edit')"
              >
                编辑
              </el-button>
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/edit') && (active === '1' || active === '6')"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/cancle') && (active === '0' || active === '3')"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatus !== '审批中'"
                @click="handleEdit(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <el-button
                v-if="proxy.hasPerm('/device/receive/applyList/delete') && (active !== '4' && active !== '5')"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatus === '未通过' || row.approvalStatus === '已通过'"
                @click="handleEdit(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <button-box :active="active" @changeCurrentButton="changeCurrentButton" />
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>

