<!-- 我的任务列表 -->
<script name="TaskMeasureMyTaskList" lang="ts" setup>
import { getCurrentInstance, ref } from 'vue'
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import RollbackDialog from '../myTask/dialog/rollbackDialog.vue'
import type { IList, IListQuery } from './certificate-interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { exportFile } from '@/utils/exportUtils'
import { getDictByCode } from '@/api/system/dict'
// import { getMyMeasureList, getTaskDetail, myExecutiveDone, myExecutiveReceive } from '@/api/business/schedule/task'
import type { dictType } from '@/global'
import type { IMenu } from '@/components/buttonBox/buttonBox'
const buttonBoxActive = 'businessCertificate' // 存储在sessionstorage里面的字段名，用于记录右上角buttonbox点击状态
const { proxy } = getCurrentInstance() as any
const $router = useRouter()
const menu = ref<IMenu[]>([]) // 右上角审批状态按钮组合
const active = ref('') // 选中的按钮
// 查询条件
const timeRange = ref<[DateModelType, DateModelType]>(['', ''])
const listQuery: Ref<IListQuery> = ref({
  certificateReportCode: '', // 证书报告编号
  certificateReportCodeName: '', // 证书报告名称
  equipmentNo: '', // 被检设备统一编号
  measureCategory: '', // 检校类别
  measurePersonName: '', // 检定员
  startTime: '', // 检定时间-开始
  endTime: '', // 检定时间-结束
  approvalStatus: '', // 审批状态
  offset: 1,
  limit: 20,
})
const operateWidth = ref('150') // 操作栏的宽度

const columns = ref<TableColumn[]>([ // 表头
  { text: '证书报告编号', value: 'certificateReportCode', width: '160', align: 'center' },
  { text: '证书报告名称', value: 'certificateReportCodeName', align: 'center' },
  { text: '被检设备统一编号', value: 'equipmentNo', align: 'center' },
  { text: '被检设备名称', value: 'equipmentName', align: 'center' },
  { text: '规格型号', value: 'model', align: 'center', width: '180' },
  { text: '检校类别', value: 'measureCategory', align: 'center', width: '55px' },
  { text: '检定员', value: 'measurePersonName', align: 'center' },
  { text: '检定时间', value: 'mesureDate', align: 'center' },
])
const list = ref<IList[]>([]) // 表格数据
const total = ref(0) // 总数
const loadingTable = ref(false) // 表格加载状态
const checkoutList = ref<IList[]>([]) // 选中的内容

// --------------------------------------------字典--------------------------------------
const measureCategoryList = ref<dictType[]>([])// 检校类别
const isUrgentList = ref<dictType[]>([])// 是否加急
const isUrgentMap = ref({}) as any // 是否加急{1: 是}

async function getDict() {
  // 审批状态
  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}`,
      })
    }
  })
  // 是否加急
  getDictByCode('isUrgent').then((response) => {
    isUrgentList.value = response.data
    response.data.forEach((item: any) => {
      isUrgentMap.value[`${item.value}`] = item.name
    })
  })
  // 检校类别
  getDictByCode('measureCategory').then((response) => {
    measureCategoryList.value = response.data
  })
}

// -----------------------------------------表格数据--------------------------------------------

// 数据查询
function fetchData(isNowPage = false) {
  // loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // getMyMeasureList(listQuery.value).then((res) => {
  //   list.value = res.data.rows.map((item: ITaskList) => {
  //     item.isUrgentName = item.isUrgent == 1 ? '是' : '否'
  //     return item
  //   })
  //   total.value = res.total
  //   loadingTable.value = false
  // })
  list.value = [{
    id: 'test', // 主键
    certificateReportCode: 'test', // 证书报告编号
    certificateReportCodeName: 'test', // 证书报告名称
    equipmentNo: 'test', // 被检设备统一编号
    equipmentName: 'test', // 被检设备名称
    model: 'test', // 规格型号
    measureCategory: 'test', // 检校类别
    measurePersonName: 'test', // 检定员
    mesureDate: 'test', // 检定时间
    approvalStatusName: '全部', // 审批状态名称
    approvalStatus: 'test', // 审批状态
  }]
}

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

// 点击搜索
const searchList = () => {
  fetchData(true)
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    certificateReportCode: '', // 证书报告编号
    certificateReportCodeName: '', // 证书报告名称
    equipmentNo: '', // 被检设备统一编号
    measureCategory: '', // 检校类别
    measurePersonName: '', // 检定员
    startTime: '', // 检定时间-开始
    endTime: '', // 检定时间-结束
    approvalStatus: '', // 审批状态
    offset: 1,
    limit: 20,
  }
  timeRange.value = ['', '']
  fetchData(false)
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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 changeCurrentButton = (val: string) => {
  active.value = val
  window.sessionStorage.setItem(buttonBoxActive, val)
  clearList()
}
// ----------------------------------------------操作---------------------------------------------------
const handleEdit = (row: IList, type: string) => {
  if (type === 'edit' || type === 'detail') {
    $router.push({
      path: `/certificate/${type}/${row.id}`,
      query: {
        // id: row.id,
      },
    })
  }
}
// --------------------------------------按钮（表格上方）--------------------------------------------------------
// 导出
const exportAll = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const param = {
      certificateReportCode: listQuery.value.certificateReportCode, // 证书报告编号
      certificateReportCodeName: listQuery.value.certificateReportCodeName, // 证书报告名称
      equipmentNo: listQuery.value.equipmentNo, // 被检设备统一编号
      measureCategory: listQuery.value.measureCategory, // 检校类别
      measurePersonName: listQuery.value.measurePersonName, // 检定员
      startTime: listQuery.value.startTime, // 检定时间-开始
      endTime: listQuery.value.endTime, // 检定时间-结束
      approvalStatus: listQuery.value.approvalStatus, // 审批状态
      offset: 1,
      limit: 20,
      ids: checkoutList.value,
    }
    // exportFileListPage(param).then((res) => {
    //   exportFile(res.data, '我的任务')
    //   loading.close()
    //   searchQuery.ids = []
    // })
    //   .catch((_) => {
    //     loading.close()
    //   })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}
// 新建
const add = () => {
  $router.push({ path: '/certificate/add' })
}
// ---------------------------------------钩子-------------------------------------------------------
watch(timeRange, (val) => { // 监听时间变化
  if (val) {
    listQuery.value.startTime = `${val[0]}`
    listQuery.value.endTime = `${val[1]}`
  }
  else {
    listQuery.value.startTime = ''
    listQuery.value.endTime = ''
  }
})

onMounted(async () => {
  getDict().then(() => {
    if (window.sessionStorage.getItem(buttonBoxActive) != null) {
      active.value = window.sessionStorage.getItem(buttonBoxActive) as string
    }
    else {
      active.value = menu.value.find(item => item.name === '全部')!.id as string
    }
    fetchData(true)
  })
})
</script>

<template>
  <app-container>
    <button-box :active="active" :menu="menu" @change-current-button="changeCurrentButton" />
    <search-area
      :need-clear="true"
      @search="searchList" @clear="clearList"
    >
      <search-item>
        <el-input
          v-model.trim="listQuery.certificateReportCode"
          placeholder="证书报告编号"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.certificateReportCodeName"
          placeholder="证书报告名称"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.equipmentNo"
          placeholder="被检设备统一编号"
          clearable
          class="short-input"
        />
      </search-item>
      <search-item>
        <el-select
          v-model="listQuery.measureCategory"
          placeholder="检校类别"
          class="short-input"
          filterable
        >
          <el-option v-for="item in measureCategoryList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.measurePersonName"
          placeholder="检定员"
          class="short-input"
          clearable
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="timeRange"
          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="导出" @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 #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"
                @click="handleEdit(row, 'change')"
              >
                修改
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '待审批'"
                size="small"
                link
                type="primary"
                @click="handleEdit(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="row.approvalStatusName === '待审批' && row.decisionItem !== 3"
                size="small"
                link
                type="primary"
                @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"
                @click="handleEdit(row, '取消')"
              >
                取消
              </el-button>
              <el-button
                v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回' && row.approvalStatusName !== '审批中' && row.approvalStatusName !== '待审批'"
                size="small"
                link
                type="danger"
                @click="handleEdit(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
.short-input {
  width: 160px;
}
</style>

