<!-- 证书/报告补充或更换申请单列表 -->
<script name="BusinessCertManageApplyList" lang="ts" setup>
import type { Ref } from 'vue'
import { getCurrentInstance, onMounted, ref, watch } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IList, IListQuery } from './applt-interface'
import { getEquipmentList } from '@/api/equipment/info/book'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import type { deptType, dictType } from '@/global'
import buttonBox from '@/components/buttonBox/buttonBox.vue'
import { exportFile } from '@/utils/exportUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import { cancelApproval } from '@/api/approval'
import { UploadFile } from '@/api/file'
import { getDeptTreeList } from '@/api/system/dept'
import { getUserList } from '@/api/system/user'
import { toTreeList } from '@/utils/structure'
import type { IMenu } from '@/components/buttonBox/buttonBox'
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const active = ref('')
const operateWidth = ref('150') // 操作栏的宽度
const buttonBoxActive = 'businessCertManageApply' // 存储在sessionstorage里面的字段名，用于记录右上角buttonbox点击状态
const approvalDialog = ref() // 审批对话ref
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  approvalStatus: '', // 审批状态
  sqdbh: '', // 申请单编号
  ghzsbh: '', // 更换证书编号
  ghzsbgmc: '', // 更换证书/报告名称
  bglx: '', // 变更类型
  createUserId: '', // 创建人id
  createUserName: '', // 创建人名称
  startTime: '', // 创建时间(开始)
  endTime: '', // 创建时间(结束)
  offset: 1,
  limit: 20,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading
const menu = ref<IMenu[]>([]) // 审批状态按钮组合
// 表头
const columns = ref<TableColumn[]>([
  { text: '申请单编号', value: 'sqdbh', align: 'center', width: '160' },
  { text: '申请单名称', value: 'sqdmc', align: 'center' },
  { text: '更换证书编号', value: 'ghzsbh', align: 'center' },
  { text: '更换证书/报告名称', value: 'ghzsbgmc', align: 'center' },
  { text: '变更类型', value: 'bglx', align: 'center' },
  { text: '创建人', value: 'createUserName', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180' },
])
const list = ref<IList[]>([]) // 表格数据
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])// 筛选时间段数据
const checkoutList = ref<string[]>([])// 选中的内容

// -----------------------------------------字典--------------------------------------------------------------
const userList = ref<{ [key: string]: string }[]>([]) // 用户列表

// 查询字典
const getDict = async () => {
  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 制作右上角的菜单
  const tempMenu = ['全部', '已审批', '待审批', '审批', '草稿箱', '审批中', '已通过', '未通过', '已取消']
  tempMenu.forEach((item) => {
    const tempFindData = res.data.find((e: { name: string; value: string }) => e.name === item)
    if (tempFindData) {
      menu.value.push({
        name: tempFindData.name,
        id: `${tempFindData.value}`,
      })
    }
  })
  // 获取用户列表
  getUserList({ offset: 1, limit: 999999 }).then((res: any) => {
    userList.value = res.data.rows
  })
}
// -------------------------------------------------------------------------------------------------------
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // getEquipmentList(listQuery.value).then((response) => {
  //   list.value = response.data.rows.map((item: { estimateSignDate: string; agreementAmount: number }) => {
  //     return {
  //       ...item,
  //       estimateSignDate: item.estimateSignDate ? dayjs(item.estimateSignDate).format('YYYY-MM-DD') : item.estimateSignDate,
  //       agreementAmount: calc(Number(item.agreementAmount), 100, '/'),
  //     }
  //   })
  //   total.value = parseInt(response.data.total)
  //   loadingTable.value = false
  // }).catch(() => {
  loadingTable.value = false
  // })
  list.value = [
    {
      id: 'test', // 主键
      sqdbh: 'test', // 申请单编号
      sqdmc: 'test', // 申请单名称
      ghzsbh: 'test', // 更换证书编号
      ghzsbgmc: 'test', // 更换证书/报告名称
      bglx: 'test', // 变更类型
      createUserId: 'test', // 创建人id
      createUserName: 'test', // 创建人名称
      createTime: 'test', // 创建时间
    },
  ]
}
// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const clearList = () => {
  listQuery.value = {
    approvalStatus: '', // 审批状态
    sqdbh: '', // 申请单编号
    ghzsbh: '', // 更换证书编号
    ghzsbgmc: '', // 更换证书/报告名称
    bglx: '', // 变更类型
    createUserId: '', // 创建人id
    createUserName: '', // 创建人名称
    startTime: '', // 创建时间(开始)
    endTime: '', // 创建时间(结束)
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

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

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}

// ------------------------------------审批---------------------------------------------------------------------
// 切换tab状态
const changeCurrentButton = (val: string) => {
  active.value = val // 此时的tab
  window.sessionStorage.setItem(buttonBoxActive, val) // 记录tab状态
  clearList() // 刷新
}
// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}
// -------------------------------------表格上方工具栏-----------------------------------
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const params = {
      approvalStatus: listQuery.value.approvalStatus, // 审批状态
      sqdbh: listQuery.value.sqdbh, // 申请单编号
      ghzsbh: listQuery.value.ghzsbh, // 更换证书编号
      ghzsbgmc: listQuery.value.ghzsbgmc, // 更换证书/报告名称
      bglx: listQuery.value.bglx, // 变更类型
      createUserId: listQuery.value.createUserId, // 创建人id
      createUserName: listQuery.value.createUserName, // 创建人名称
      startTime: listQuery.value.startTime, // 创建时间(开始)
      endTime: listQuery.value.endTime, // 创建时间(结束)
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    // exportOrderList(params).then((res) => {
    //   const blob = new Blob([res.data])
  // loading.close()
    //   exportFile(blob, '任务单列表.xlsx')
    // })
  }
  else {
    loading.close()
    ElMessage.warning('无数据可导出数据')
  }
}

// 新建
const add = () => {
  $router.push({ path: '/apply/add' })
}
// ----------------------------------------------扫描----------------------------------------------------
// 点击扫描
const scan = () => {}

// ----------------------------------------------操作---------------------------------------------------
const handleEdit = (row: IList, type: string) => {
  if (type === 'edit' || type === 'detail') {
    $router.push({
      path: `/apply/${type}/${row.id}`,
      query: {
        // id: row.id,
      },
    })
  }
}
// ----------------------------------------------钩子------------------------------------------------------
watch(dateRange, (val) => {
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})
onMounted(async () => {
  await getDict()
  if (window.sessionStorage.getItem(buttonBoxActive)) {
    active.value = window.sessionStorage.getItem(buttonBoxActive)!
  }
  else {
    active.value = menu.value.find(item => item.name === '全部')!.id as string // 全部
  }
})
</script>

<template>
  <app-container>
    <search-area :need-clear="true" @search="searchList" @clear="clearList">
      <search-item>
        <el-input v-model.trim="listQuery.sqdbh" placeholder="申请单编号" class="short-input" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.ghzsbh" placeholder="更换证书编号" class="short-input" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.ghzsbgmc" placeholder="更换证书/报告名称" class="short-input" clearable />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.createUserId"
          placeholder="创建人"
          class="short-input"
          filterable
        >
          <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </search-item>
      <search-item>
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          start-placeholder="创建时间(开始)"
          end-placeholder="创建时间(结束)"
        />
      </search-item>
    </search-area>

    <table-container>
      <template #btns-right>
        <!-- 只有全部和新建可以导出 -->
        <icon-button icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button icon="icon-export" title="导出" type="primary" @click="exportAll" />
      </template>
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery" :list-loading="loadingTable"
        is-showmulti-select @change="changePage" @multi-select="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"
            fixed="right"
            :width="operateWidth"
          >
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleEdit(row, 'detail')"
              >
                详情
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '待审批'"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '待审批' && row.decisionItem !== 3"
                size="small"
                link
                type="primary"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '待审批' && row.decisionItem !== 2"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '未通过-驳回' || row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '提交')"
              >
                提交
              </el-button>

              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="row.approvalStatusName === '审批中'"
                size="small"
                link
                type="info"
                :disabled="row.approvalStatusName !== '审批中'"
                @click="handleEdit(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <!-- <el-button
                v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                 @click="handleEdit(row, '删除')"
              >
                删除
              </el-button> -->
              <!-- ---------------------------审批中的删除按钮暂时去掉------------------------ -->
              <el-button
                v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回' && row.approvalStatusName !== '审批中' && row.approvalStatusName !== '待审批'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                @click="handleEdit(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- 右上角按钮集合 -->
    <button-box :active="active" :menu="menu" @change-current-button="changeCurrentButton" />
  </app-container>
</template>

<style lang="ts" scoped>

</style>

