<!-- 设备保养验收单列表 -->
<script lang="ts" setup name="ListApproval">
import type { PropType, Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IOptions, IlistApproval, IlistApprovalTypes } from '../checkList_interface'
import type { IButton } from '@/views/measure/source/list_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getApprovalDelete, getDeptTree, getListSubmit, getapprovalList } from '@/api/measure/plan'
import { deleteAcceptanceCheck, exportCheckList, getacceptanceCheckList, submitAcceptanceCheck } from '@/api/device/checkList'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import { cancelApproval } from '@/api/approval'
import { getDictByCode } from '@/api/system/dict'

const props = defineProps({
  status: {
    type: String,
    default: '',
  },
  buttons: {
    type: Array as PropType<IButton[]>,
    default: () => [],
  },
})
// 获取权限
const { proxy } = getCurrentInstance() as any

// 操作列宽度-计算属性
const operationWidth = computed(() => {
  return props.buttons.length * 40 + 24
})
const approvalStatusReserveMap = ref({}) as any// 审批状态字典{草稿箱: 1}

// 查询条件
const listQuery = ref<IlistApprovalTypes>({
  approvalStatus: props.status, // 审批状态
  formId: SCHEDULE.DEVICE_FIX_ACCEPTANCE, // 表单id
  applyName: '', // 审批名称
  applyNo: '', // 审批编号
  applyType: '9', // 审批类型
  businessKeys: [], // 业务主键列表（工作流查询用，不用前端传）
  checkApplyNo: '', // 检修申请编号
  checkEndDate: '', // 检修结束时间
  checkStartDate: '', // 检修开始时间
  createUser: '', //  创建人
  ids: [], // 主键集合
  overhaulPerson: '', // 检修保养人
  offset: 1, // 当前页
  limit: 20, // 一页多少条
})
// 表格数据
const list = ref<IlistApproval[]>([])
// 总数
const total = ref(0)
// 表头
const columns = ref<TableColumn[]>([
  {
    text: '验收单编号',
    value: 'applyNo',
    align: 'center',
    width: '190',
  },
  {
    text: '验收单名称',
    value: 'applyName',
    align: 'center',
  },
  {
    text: '检修申请编号',
    value: 'checkApplyNo',
    align: 'center',
    width: '160',
  },
  {
    text: '检修申请名称',
    value: 'checkApplyName',
    align: 'center',
  },
  {
    text: '检修保养人',
    value: 'overhaulPerson',
    align: 'center',
  },
  {
    text: '检修日期',
    value: 'checkDate',
    align: 'center',
    width: '120',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
    width: '110',
  },
])
// 初始化路由
const $router = useRouter()
// 选中的内容
const checkoutList = ref<string[]>([])
// 装载时间数组
const checkTime = ref<string>('')
const loadingTable = ref(false)
// 时间变更
watch(checkTime, (val) => {
  if (val) {
    listQuery.value.checkStartDate = `${val[0]}`
    listQuery.value.checkEndDate = `${val[1]}`
  }
  else {
    listQuery.value.checkStartDate = ''
    listQuery.value.checkEndDate = ''
  }
})
// 获取数据
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getacceptanceCheckList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: any) => {
      return {
        ...item,
        checkDate: item.checkDate ? dayjs(item.checkDate).format('YYYY-MM-DD') : '',
      }
    })
    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: IlistApproval) => {
  ElMessageBox.confirm(
    '确认删除所选记录吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteAcceptanceCheck({ id: row.id, taskId: row.taskId }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      }
    })
  })
}
// 获取字典值
async function getDict() {
  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 审批状态字典 {草稿箱: 1}
  res.data.forEach((item: any) => {
    approvalStatusReserveMap.value[item.name] = `${item.value}`
  })
}
// 取消
const handleCancel = (row: IlistApproval) => {
  const params = {
    processInstanceId: row.processId!,
    comments: '取消审批',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelApproval(params).then(() => {
      ElMessage.success('取消成功')
      fetchData(true)
    })
  })
}

const approvalDialog = ref()

// 点击搜索
const searchList = () => {
  fetchData(false)
}

// 点击重置
const clearList = () => {
  listQuery.value = {
    approvalStatus: props.status, // 审批状态
    formId: SCHEDULE.DEVICE_FIX_ACCEPTANCE, // 表单id
    applyName: '', // 审批名称
    applyNo: '', // 审批编号
    applyType: '9', // 审批类型
    businessKeys: [], // 业务主键列表（工作流查询用，不用前端传）
    checkApplyNo: '', // 检修申请编号
    checkEndDate: '', // 检修结束时间
    checkStartDate: '', // 检修开始时间
    createUser: '', //  创建人
    ids: [], // 主键集合
    overhaulPerson: '', // 检修保养人
    offset: 1, // 当前页
    limit: 20, // 一页多少条
  }
  checkTime.value = ''
  fetchData(true)
}
// 点击跳转
const add = () => {
  $router.push('maintenanceCheckList/add')
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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: IlistApproval) => {
  $router.push({
    path: `maintenanceCheckList/detail/${row.id}/${row.approvalStatusName}/${row.processId}`,
    query: {
      processId: row.processId, // 流程实例
      decisionItem: `${row.decisionItem}`, // 同意、驳回、拒绝
      taskId: row.taskId,
    },
  },
  )
}

// 提交
const approvalSubmit = (row: IlistApproval) => {
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitAcceptanceCheck({ id: row.id, formId: SCHEDULE.DEVICE_FIX_ACCEPTANCE, processId: row.processId }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        fetchData(true)
      }
    })
  })
}

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

// 点击数据后的操作按钮
const clickBtn = (row: IlistApproval, buttonType: string) => {
  switch (buttonType) {
    case '查看':
      goDetail(row)
      break
    case '提交':
      approvalSubmit(row)
      break
    case '编辑':
      $router.push(`maintenanceCheckList/edit/${row.id}/${row.approvalStatusName}/${row.processId}`)
      // $router.push(`/maintenance/maintenanceCheckList/edit/${row.id}`)
      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
    window.sessionStorage.setItem('maintenceCheckListApprovalMenu', newVal)
    fetchData(false)
  })

// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item: TableColumn) => {
    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: IlistApproval) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '设备检修列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}

const permUrl = {
  edit: '/device/maintenance/check/list/add', // 提交
  submit: '/device/maintenance/checkList/submit', // 提交
  agree: '/device/maintenance/checkList/agree', // 同意
  reject: '/device/maintenance/checkList/reject', // 驳回
  refuse: '/device/maintenance/checkList/refuse', // 拒绝
  cancel: '/device/maintenance/checkList/cancel', // 取消
  delete: '/device/maintenance/checkList/delete', // 删除
}

onMounted(async () => {
  await getDict()
  if (window.sessionStorage.getItem('maintenceCheckListApprovalMenu')) {
    listQuery.value.approvalStatus = window.sessionStorage.getItem('maintenceCheckListApprovalMenu')!
  }
  else {
    listQuery.value.approvalStatus = approvalStatusReserveMap.value['全部']
  }
  fetchData(true)
})
</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>
        <el-input
          v-model.trim="listQuery.checkApplyNo"
          placeholder="检修申请编号"
          clearable
        />
      </search-item>
      <search-item>
        <el-input
          v-model.trim="listQuery.overhaulPerson"
          placeholder="检修保养人"
          clearable
        />
      </search-item>
      <search-item>
        <el-date-picker
          v-model="checkTime"
          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/maintenance/check/list/add')" icon="icon-add" title="新建" type="primary" @click="add" />
        <icon-button v-if="proxy.hasPerm('/device/maintenance/check/list/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" @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" :width="operationWidth" fixed="right">
            <template #default="{ row }">
              <el-button
                size="small"
                type="primary"
                link
                @click="clickBtn(row, '查看')"
              >
                查看
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.agree.if(row, permUrl.agree)"
                size="small"
                link
                type="primary"
                :disabled="proxy.buttonPerm.agree.disabled(row)"
                @click="clickBtn(row, '同意')"
              >
                同意
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.reject.if(row, permUrl.reject)"
                size="small"
                link
                type="primary"
                :disabled="proxy.buttonPerm.reject.disabled(row)"
                @click="clickBtn(row, '驳回')"
              >
                驳回
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.refuse.if(row, permUrl.refuse)"
                size="small"
                link
                type="danger"
                :disabled="proxy.buttonPerm.refuse.disabled(row)"
                @click="clickBtn(row, '拒绝')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.edit.if(row, permUrl.edit)"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '编辑')"
              >
                编辑
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.submit.if(row)"
                size="small"
                link
                type="primary"
                @click="clickBtn(row, '提交')"
              >
                提交
              </el-button>
              <!-- 是发起者且审批中可以取消 -->
              <el-button
                v-if="proxy.buttonPerm.cancel.if(row, permUrl.cancel)"
                size="small"
                link
                type="info"
                :disabled="proxy.buttonPerm.cancel.disabled(row)"
                @click="clickBtn(row, '取消')"
              >
                取消
              </el-button>
              <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
              <el-button
                v-if="proxy.buttonPerm.delete.if(row, permUrl.delete)"
                size="small"
                link
                type="danger"
                :disabled="proxy.buttonPerm.delete.disabled(row)"
                @click="clickBtn(row, '删除')"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

