<!-- 状态管理公共列表组件 -->
<script lang="ts" setup>
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { ISearchQuery, ITableRow, managerStateItem } from './status-interface'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { cancelApproval, submitApproval } from '@/api/approval'
import {
  deleteStatus,
  exportStatus,
  getStatusList,
  submitStatus,
} from '@/api/device/stateManage'
import { printJSON } from '@/utils/printUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { SCHEDULE } from '@/utils/scheduleDict'
import { exportFile } from '@/utils/exportUtils'
import { getDeptTreeList } from '@/api/system/dept'
import { toTreeList } from '@/utils/structure'
import { keepSearchParams, renewSearchParams } from '@/utils/keepQuery'
import type { deptType } from '@/views/device/standingBook/standingBook-interface'
// 选中的按钮
const props = defineProps({
  name: {
    type: String,
    default: '',
  },
  title: {
    type: String,
    default: '',
  },
  type: {
    type: String, // 当前状态
    default: '',
  },
  applyType: {
    type: String, // 设备申请类型
    default: '',
  },
  formCode: {
    type: String, // 表单formCode
    default: '',
  },
})

const permUrl = {
  edit: '/device/unusedApply/edit', // 编辑
  agree: '/device/unusedApply/agree', // 同意
  reject: '/device/unusedApply/reject', // 驳回 拒绝
  cancel: '/device/unusedApply/cancle', // 取消
  delete: '/device/unusedApply/delete', // 删除
}
const approvalStatusVal = ref<string>(props.type)

// const approvalStatusMap = ref({}) as any// 审批状态字典{1：草稿箱}
// const approvalStatusReserveMap = ref({}) as any// 审批状态字典{草稿箱: 1}
const $router = useRouter()
// 查询参数
let searchQuery = reactive<ISearchQuery>({
  applyNo: '', // 申请编号
  applyStatus: '', // 申请状态
  applyUnit: '', // 申请单位
  approvalStatus: approvalStatusVal.value, // 审批状态
  createUser: '', // 创建人
  equipmentName: '', // 设备名称
  equipmentNo: '', // 设备编号
  limit: 20,
  offset: 1,
  applyType: props.applyType, // 申请类型
  formId: SCHEDULE[props.formCode as keyof typeof SCHEDULE],
})
// 页面跳转之前保存参数
onBeforeRouteLeave((to: any) => {
  keepSearchParams(to.path, `device-stateManage-${props.name}`, searchQuery)
})
// 重新赋值
searchQuery = reactive(renewSearchParams(`device-stateManage-${props.name}`) || {
  applyNo: '', // 申请编号
  applyStatus: '', // 申请状态
  applyUnit: '', // 申请单位
  approvalStatus: approvalStatusVal.value, // 审批状态
  createUser: '', // 创建人
  equipmentName: '', // 设备名称
  equipmentNo: '', // 设备编号
  limit: 20,
  offset: 1,
  applyType: props.applyType, // 申请类型
  formId: SCHEDULE[props.formCode as keyof typeof SCHEDULE],
})
const loadingTable = ref<boolean>(false) // 表格loading
const total = ref<number>(0) // 数据总条数
const columns = ref<TableColumn[]>([
  {
    text: '申请编号',
    value: 'applyNo',
    align: 'center',
    width: '160',
  },
  {
    text: '申请类型',
    value: 'applyTypeName',
    align: 'center',
    width: '120',
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
    width: '160',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: '设备状态',
    value: 'managerStateName',
    align: 'center',
    width: 120,
  },
  {
    text: '申请单位',
    value: 'applyUnitName',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPersonName',
    align: 'center',
  },
  {
    text: `${props.name.substring(2, 4)}时间`,
    value: 'time',
    align: 'center',
    width: '180',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
    width: '110',
  },
]) // 表格
const list = ref([]) // 表格数据
const applyUnitList = ref<deptType[]>([]) // 状态数据
const approvalDialog = ref()
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
const { proxy } = getCurrentInstance() as any
const useDeptListNoTree = ref([]) // 使用部门列表非树结构
const clearSearch = () => {
  searchQuery.equipmentName = ''
  searchQuery.applyNo = ''
  searchQuery.applyStatus = ''
  searchQuery.applyUnit = ''
  searchQuery.approvalStatus = '0'
  searchQuery.createUser = ''
  searchQuery.equipmentNo = ''
  searchQuery.ids = []
  searchQuery.limit = 20
  searchQuery.offset = 1
  searchQuery.applyType = props.applyType
  searchQuery.formId = SCHEDULE[props.formCode as keyof typeof SCHEDULE]
}

// 获取数据列表
const getList = (isNowPage = false) => {
  loadingTable.value = true
  // if (!isNowPage) {
  //   // 是否显示当前页，否则跳转第一页
  //   searchQuery.offset = 1
  // }
  if (!searchQuery.approvalStatus) {
    searchQuery.approvalStatus = '0'
  }
  getStatusList(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows
      total.value = res.data.total
    }
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    searchQuery.limit = val.size
  }
  if (val && val.page) {
    searchQuery.offset = val.page
  }
  getList()
}
// 详情
const detail = (row: ITableRow) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'detail',
      id: row.id,
    },
    query: {
      title: '详情',
      name: props.name,
      applyType: props.applyType,
      approvalStatusName: row.approvalStatusName,
      decisionItem: `${row.decisionItem}`, // 同意、驳回、拒绝
      taskId: row.taskId,
    },
  })
}
// 编辑
const update = (row: ITableRow) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'edit',
      id: row.id,
    },
    query: {
      title: '编辑',
      name: props.name,
      applyType: props.applyType,
      approvalStatusName: row.approvalStatusName,

    },
  })
}
// 删除
const remove = (row: ITableRow) => {
  const { id } = row
  ElMessageBox.confirm(`确认删除${row.equipmentName}吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteStatus({ id }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getList()
      }
    })
  })
}
// 同意
const agree = (row: ITableRow) => {
  approvalDialog.value.initDialog('agree', row.taskId, row.decisionItem)
}
// 驳回
const reject = (row: ITableRow) => {
  approvalDialog.value.initDialog('reject', row.taskId, row.decisionItem)
}
// 拒绝
const refuse = (row: ITableRow) => {
  approvalDialog.value.initDialog('refuse', row.taskId)
}

// 审批结束回调
const approvalSuccess = () => {
  getList()
}
// 取消
const cancel = (row: ITableRow) => {
  const params = {
    processInstanceId: row.processId!,
    comments: '',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      cancelApproval(params).then((res) => {
        ElMessage({
          type: 'success',
          message: '取消成功',
        })
        getList()
      })
    })
}

// 提交
const submit = (row: ITableRow) => {
  const { id, processId } = row
  const postData = {
    id,
    formId: searchQuery.formId,
    processId,
    // ...row.approvalStatusName === '已取消' && { processId },
  }
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitStatus(postData).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        getList()
      }
    })
  })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  clearSearch()
  getList()
}
// 新增
const add = () => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
      applyType: props.applyType,
      formId: searchQuery.formId,
    },
  })
}
// 表格被选中的行
const selectList = ref<ITableRow[]>([])
// 表格多选
const multiSelect = (row: ITableRow[]) => {
  selectList.value = row
}
// 打印
function printList() {
  const selectIds = selectList.value.map(item => item.id)
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (selectIds.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, props.name)
  }
  else if (selectIds.length > 0) {
    const printList = list.value.filter((item: ITableRow) =>
      selectIds.includes(item.id),
    )
    printJSON(printList, properties, props.name)
  }
  else {
    ElMessage('无可打印内容')
  }
}

const getApplyUnitList = () => {
  // 获取部门列表
  getDeptTreeList().then((res) => {
    // 转成树结构
    applyUnitList.value = toTreeList(res.data, '0', true)
    useDeptListNoTree.value = res.data
  })
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}

onMounted(() => {
  // 获取申请单位
  getApplyUnitList()
  nextTick(() => {
    getList()
  })
})
</script>

<template>
  <!-- 筛选条件 -->
  <search-area :need-clear="true" @search="search" @clear="reset">
    <search-item>
      <el-input
        v-model="searchQuery.applyNo"
        placeholder="申请编号"
        clearable
        class="short-input"
      />
    </search-item>
    <search-item>
      <el-input
        v-model="searchQuery.equipmentNo"
        placeholder="设备编号"
        clearable
        class="short-input"
      />
    </search-item>
    <search-item>
      <el-input
        v-model="searchQuery.equipmentName"
        placeholder="设备名称"
        clearable
        class="short-input"
      />
    </search-item>
    <search-item>
      <dept-select v-model="searchQuery.applyUnit" :data="applyUnitList" placeholder="申请单位" />
    </search-item>
  </search-area>
  <table-container>
    <!-- 表头区域 -->
    <template #btns-right>
      <icon-button v-if="proxy.hasPerm('/device/unusedApply/add')" icon="icon-add" title="新建" @click="add" />
      <icon-button v-if="proxy.hasPerm('/device/unusedApply/print')" icon="icon-print" title="打印" @click="printList" />
    </template>
    <!-- 表格区域 -->
    <normal-table
      id="print"
      :data="list"
      :total="total"
      :columns="columns"
      :is-showmulti-select="true"
      :query="{ limit: searchQuery.limit, offset: searchQuery.offset }"
      :list-loading="loadingTable"
      :is-multi="true"
      @change="changePage"
      @multi-select="multiSelect"
    >
      <template #preColumns>
        <el-table-column label="序号" width="55" align="center">
          <template #default="scope">
            {{ (searchQuery.offset - 1) * searchQuery.limit + scope.$index + 1 }}
          </template>
        </el-table-column>
      </template>
      <template #columns>
        <el-table-column
          label="操作"
          align="center"
          :width="(title === '全部') ? 150 : (title === '草稿箱' || title === '已取消') ? 150 : (title === '已通过' || title === '未通过' || title === '审批中') ? 100 : 150"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              link
              @click="detail(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.edit.if(row, permUrl.edit)"
              size="small"
              type="primary"
              link
              @click="update(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.submit.if(row)"
              size="small"
              type="primary"
              link
              @click="submit(row)"
            >
              提交
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.agree.if(row, permUrl.agree)"
              size="small"
              type="primary"
              link
              :disabled="proxy.buttonPerm.agree.disabled(row)"
              @click="agree(row)"
            >
              同意
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.reject.if(row, permUrl.reject)"
              size="small"
              type="primary"
              link
              :disabled="proxy.buttonPerm.reject.disabled(row)"
              @click="reject(row)"
            >
              驳回
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.refuse.if(row, permUrl.reject)"
              size="small"
              type="danger"
              link
              :disabled="proxy.buttonPerm.refuse.disabled(row)"
              @click="refuse(row)"
            >
              拒绝
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.cancel.if(row, permUrl.cancel)"
              size="small"
              type="info"
              link
              :disabled="proxy.buttonPerm.cancel.disabled(row)"
              @click="cancel(row)"
            >
              取消
            </el-button>
            <el-button
              v-if="proxy.buttonPerm.delete.if(row, permUrl.delete)"
              :disabled="proxy.buttonPerm.delete.disabled(row)"
              size="small"
              type="danger"
              link
              @click="remove(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </template>
    </normal-table>
  </table-container>
  <!-- 审批操作组件 -->
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>
