<!-- 状态管理公共列表组件 -->
<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 {
  cancelStatus,
  deleteStatus,
  exportStatus,
  getStatusList,
  submitStatus,
} from '@/api/device/stateManage'
import { getDictByCode } from '@/api/system/dict'
import { printJSON } from '@/utils/printUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { SCHEDULE } from '@/utils/scheduleDict'
import type { dictType } from '@/views/device/receive/receive'
import { exportFile } from '@/utils/exportUtils'

// 选中的按钮
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 activeTitle = ref<string>(props.title) // 状态按钮选中
const approvalStatusMap = ref({}) as any// 审批状态字典{1：草稿箱}
const approvalStatusReserveMap = ref({}) as any// 审批状态字典{草稿箱: 1}
const $router = useRouter()
// 查询参数
const searchQuery = reactive<ISearchQuery>({
  applyNo: '', // 申请编号
  applyStatus: '', // 申请状态
  applyUnit: '', // 申请单位
  approvalStatus: '0', // 审批状态
  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',
  },
  {
    text: '申请类型',
    value: 'applyTypeName',
    align: 'center',
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: '设备状态',
    value: 'managerStateName',
    align: 'center',
  },
  {
    text: '申请单位',
    value: 'applyUnitName',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'applyPersonName',
    align: 'center',
  },
  {
    text: `${props.name.substring(2, 4)}时间`,
    value: 'time',
    align: 'center',
  },
  {
    text: '审批状态',
    value: 'approvalStatusName',
    align: 'center',
  },
]) // 表格
const list = ref([]) // 表格数据
const managerStateList = ref<managerStateItem[]>([]) // 状态数据
const approvalDialog = ref()
const dialogVisible = ref<boolean>(false) // 添加组件的显示与隐藏
const { proxy } = getCurrentInstance() as any

const clearSearch = () => {
  searchQuery.equipmentName = ''
  searchQuery.applyNo = ''
  searchQuery.applyStatus = ''
  searchQuery.applyUnit = ''
  searchQuery.approvalStatus = ''
  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]
}

// 获取字典值
async function getDict() {
  managerStateList.value = []
  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 审批状态字典 {1：草稿箱}
  res.data.forEach((item: any) => {
    approvalStatusMap.value[`${item.value}`] = item.name
  })

  // 审批状态字典 {草稿箱: 1}
  res.data.forEach((item: any) => {
    approvalStatusReserveMap.value[item.name] = `${item.value}`
  })

  // 制作右上角的菜单
  res.data.forEach((item: dictType) => {
    if (item.name === '全部' || item.name === '草稿箱'
      || item.name === '待审批' || item.name === '审批中'
      || item.name === '已通过' || item.name === '未通过'
      || item.name === '已取消') {
      managerStateList.value.push({
        name: item.name,
        value: item.name,
        id: `${item.value}`,
      })
    }
  })
}

// 获取数据列表
const getList = () => {
  getDict()
  loadingTable.value = true
  getStatusList(searchQuery).then((res) => {
    if (res.code === 200) {
      list.value = res.data.rows.map((item: ITableRow) => {
        return {
          ...item,
          approvalStatus: approvalStatusMap[item.approvalStatus],
        }
      })
      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,
    },
  })
}
// 编辑
const update = (row: ITableRow) => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'edit',
      id: row.id,
    },
    query: {
      title: '编辑',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 删除
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)
}
// 驳回
const reject = (row: ITableRow) => {
  approvalDialog.value.initDialog('reject', row.taskId)
}
// 拒绝
const refuse = (row: ITableRow) => {
  approvalDialog.value.initDialog('refuse', row.taskId)
}

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

// 提交
const submit = (row: ITableRow) => {
  // 流程id为空
  const { id } = row
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    submitStatus({ id, formId: searchQuery.formId }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        getList()
      }
    })
  })
}
// 搜索
const search = () => {
  getList()
}
// 重置
const reset = () => {
  clearSearch()
  getList()
}
// 模板下载
const templateDownload = () => {}
// 标签识别
const identify = () => {}
// 新增
const add = () => {
  $router.push({
    name: 'stateManageDetail',
    params: {
      type: 'add',
    },
    query: {
      title: '新建',
      name: props.name,
      applyType: props.applyType,
    },
  })
}
// 表格被选中的行
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 exportExcelBtn = () => {
  const loading = ElLoading.service({
    lock: true,
    text: '下载中请稍后',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  if (list.value.length > 0) {
    const selectIds = selectList.value.map(item => item.id)
    const params = {
      applyNo: searchQuery.applyNo, // 申请编号
      applyStatus: searchQuery.applyStatus, // 申请状态
      applyUnit: searchQuery.applyUnit, // 申请部门
      approvalStatus: searchQuery.approvalStatus, // 申请人
      createUser: searchQuery.createUser, // 创建人
      equipmentName: searchQuery.equipmentName, // 设备名称
      equipmentNo: searchQuery.equipmentNo, // 	设备编号
      applyType: searchQuery.applyType, // 申请类型
      formId: SCHEDULE[props.formCode as keyof typeof SCHEDULE],
      ids: selectIds,
    }
    // 调导出接口
    exportStatus(params).then((res) => {
      const blob = new Blob([res.data])
      exportFile(blob, `${props.name}.xlsx`)
    })
  }
  else {
    ElMessage.warning('无数据可导出数据')
  }
  loading.close()
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
  }
}
// 批量导入
const batchImport = () => {
  fileRef.value.click()
}
// 传给子组件的刷新事件
const refreshDta = () => {
  getList()
  dialogVisible.value = false
}

watch(() => searchQuery.applyStatus, (newValue) => {
  if (newValue == '') {
    searchQuery.approvalStatus = '0'
  }
  else {
    searchQuery.approvalStatus = approvalStatusReserveMap.value[newValue]
  }
})

watch(
  () => props.type,
  (newValue) => {
    if (newValue === '0') {
      searchQuery.approvalStatus = ''
    }
    else {
      searchQuery.approvalStatus = newValue
    }
    getList()
  },
  {
    immediate: true,
    deep: true,
  },
)
</script>

<template>
  <div>
    <!-- 审批操作组件 -->
    <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
    <!-- 布局 -->
    <app-container>
      <!-- 筛选条件 -->
      <search-area :need-clear="true" @search="search" @clear="reset">
        <search-item>
          <el-input
            v-model="searchQuery.applyNo"
            placeholder="申请编号"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-input
            v-model="searchQuery.equipmentNo"
            placeholder="设备编号"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-input
            v-model="searchQuery.equipmentName"
            placeholder="设备名称"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-input
            v-model="searchQuery.applyUnit"
            placeholder="申请单位"
            clearable
            class="w-50 m-2"
          />
        </search-item>
        <search-item>
          <el-select
            v-model="searchQuery.applyStatus"
            placeholder="申请状态"
            clearable
          >
            <el-option
              v-for="manager of managerStateList"
              :key="manager.id"
              :label="manager.name"
              :value="manager.value"
            />
          </el-select>
        </search-item>
      </search-area>
      <table-container>
        <!-- 表头区域 -->
        <template #btns-right>
          <input
            v-show="searchQuery.limit === 0"
            ref="fileRef"
            type="file"
            multiple
            @change="onFileChange"
          >
          <icon-button v-if="proxy.hasPerm('/device/unusedApply/add')" icon="icon-add" title="新建" @click="add" />
          <icon-button
            v-if="proxy.hasPerm('/device/unusedApply/export')"
            icon="icon-export"
            title="导出"
            @click="exportExcelBtn"
          />
          <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="230"
              fixed="right"
            >
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="detail(row)"
                >
                  查看
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/edit') && ['草稿箱', '已取消'].includes(activeTitle)"
                  size="small"
                  type="primary"
                  link
                  @click="update(row)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/edit') && ['草稿箱', '已取消'].includes(activeTitle)"
                  size="small"
                  type="primary"
                  link
                  @click="submit(row)"
                >
                  提交
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/agree') && ['全部', '待审批'].includes(activeTitle)"
                  size="small"
                  type="primary"
                  link
                  :disabled="
                    (row.approvalStatus !== '待审批'
                      && row.approvalStatus !== '审批中')
                      || row.decisionItem === 3"
                  @click="agree(row)"
                >
                  同意
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/reject') && ['全部', '待审批'].includes(activeTitle)"
                  size="small"
                  type="primary"
                  link
                  :disabled="
                    (row.approvalStatus !== '待审批'
                      && row.approvalStatus !== '审批中')
                      || row.decisionItem === 3"
                  @click="reject(row)"
                >
                  驳回
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/reject') && ['全部', '待审批'].includes(activeTitle)"
                  size="small"
                  type="danger"
                  link
                  :disabled="
                    (row.approvalStatus !== '待审批'
                      && row.approvalStatus !== '审批中')
                      || row.decisionItem === 1 || row.decisionItem === 2"
                  @click="refuse(row)"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/cancle') && ['全部', '审批中'].includes(activeTitle)"
                  size="small"
                  type="text"
                  link
                  :disabled="row.approvalStatus !== '审批中'"
                  @click="cancel(row)"
                >
                  取消
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/device/unusedApply/delete') && !['未通过', '已通过'].includes(activeTitle)"
                  :disabled="row.approvalStatus === '未通过' || row.approvalStatus === '已通过'"
                  size="small"
                  type="danger"
                  link
                  @click="remove(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
</template>
