<!-- 设备状态列表 -->
<script lang="ts" setup name="DeviceStatusList">
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ApprovalDialog from './ApprovalDialog.vue'
import { cancelStatus, deleteStatus, detailStatus, editStatus, getListPage, submitStatus } from '@/api/eqpt/status/index'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
const $props = defineProps({
  //  审批状态  全部 审批等
  statusName: {
    type: String,
    default: '',
  },
  // 设备状态  封存 启封等
  statusType: {
    type: String,
    default: '',
  },
})
const applyDict = ref<{ [key: string]: string }>({
  审批: '',
  草稿箱: '1',
  审批中: '3',
  已通过: '4',
  未通过: '5',
  已取消: '6',
})
const statusDict = ref<{ [key: string]: string }>({
  1: 'sealpage', // 封存
  2: 'unsealpage', // 启封
  3: 'disablepage', // 禁用
  4: 'scrappage', // 报废
  5: 'sdelaypage', // 延用
})
const formIdDict = ref<{ [key: string]: string }>({
  1: SCHEDULE.EQUIPMENT_SEALED_APPROVAL,
  2: SCHEDULE.EQUIPMENT_UNSEALED_APPROVAL,
  3: SCHEDULE.EQUIPMENT_DISABLE_APPROVAL,
  4: SCHEDULE.EQUIPMENT_SCRAP_APPROVAL,
  5: SCHEDULE.EQUIPMENT_DELAY_APPROVAL,
})
const { proxy } = getCurrentInstance() as any
const listQuery = reactive({
  approvalNo: '',
  approvalStatus: '',
  approvalType: $props.statusType,
  equipmentName: '',
  equipmentNo: '',
  formId: formIdDict.value[Number($props.statusType)],
  offset: 1,
  limit: 20,
})

const columns = ref([
  {
    text: '登记表编号',
    value: 'approvalNo',
    align: 'center',
  },
  {
    text: '登记表名称',
    value: 'approvalName',
    align: 'center',
  },
  {
    text: '统一编号',
    value: 'equipmentNo',
    align: 'center',
  },
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '规格型号',
    value: 'model',
    align: 'center',
  },
  {
    text: '所在单位',
    value: 'companyName',
    align: 'center',
  },
  {
    text: '申请人',
    value: 'createUserName',
    align: 'center',
  },
  {
    text: '申请时间',
    value: 'createTime',
    align: 'center',
  },
])
const list = ref([])
const total = ref(0)
const listLoading = ref(true)

// 获取列表数据
const fetchData = (isNowPage = true) => {
  list.value = []
  total.value = 0
  listLoading.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.offset = 1
  }
  getListPage(listQuery, $props.statusName).then((response) => {
    list.value = response.data.rows
    total.value = parseInt(response.data.total)
    listLoading.value = false
  }).catch(() => {
    listLoading.value = false
  })
}
// 查询数据
const search = () => {
  fetchData(false)
}
// 重置
const reset = () => {
  listQuery.approvalNo = ''
  listQuery.equipmentName = ''
  listQuery.equipmentNo = ''
  listQuery.offset = 1
  listQuery.limit = 20
  search()
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size: number; page: number }) => {
  if (val && val.size) {
    listQuery.limit = val.size
  }
  if (val && val.page) {
    listQuery.offset = val.page
  }
  fetchData()
}

const $router = useRouter()
// 新建编辑操作
const handler = (row: any, type: string) => {
  $router.push({
    path: `${statusDict.value[$props.statusType]}/${type}`,
    query: {
      row: JSON.stringify(row),
      id: row.id,
      statusName: $props.statusName,
      statusType: $props.statusType,
    },
  })
}
// 详情
const detail = (row: any) => {
  if ($props.statusName === '草稿箱' || $props.statusName === '未通过' || $props.statusName === '已取消') {
    handler(row, 'update')
  }
  else {
    $router.push({
      path: `${statusDict.value[$props.statusType]}/${'detail'}`,
      query: {
        row: JSON.stringify(row),
        id: row.id,
        statusName: $props.statusName,
        statusType: $props.statusType,
      },
    })
  }
}
// 删除
const delHandler = (row: any) => {
  ElMessageBox.confirm(
    '确认删除此申请吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    deleteStatus(row.id).then((res) => {
      ElMessage.success('操作成功')
      search()
    })
  })
}
// 取消
const canHandler = (row: any) => {
  ElMessageBox.confirm(
    '确认取消此申请吗?',
    '确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelStatus({ id: row.id, processInstanceId: row.processId, comments: '' }).then((res) => {
      ElMessage.success('操作成功')
      search()
    })
  })
}
// 提交
const submit = (row: any) => {
  ElMessageBox.confirm(
    '确认提交吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then((res) => {
    submitStatus({ id: row.id, formId: formIdDict.value[Number($props.statusType)] }).then((res) => {
      ElMessage.success('已提交')
      search()
    })
  })
}
// 同意拒绝
const approvalDialogRef = ref()
const approveHandler = (row: any, type: string) => {
  approvalDialogRef.value.initDialog(type, row.taskId, row.processId, row.id)
}
// 审批状态发生变化
watch(() => $props.statusName, (newVal) => {
  if (newVal) {
    listQuery.approvalStatus = applyDict.value[newVal] as string
    fetchData()
  }
},
{
  deep: true,
  immediate: true,
})
const permUrl = ref({
  edit: '/tested/pmetering/plan/edit',
  del: '/tested/pmetering/plan/delete',
  submit: '/tested/pmetering/plan/submit',
  cancel: '/tested/pmetering/plan/cancel',
  agree: '/tested/pmetering/plan/agree',
  reject: '/tested/pmetering/plan/reject',
})
</script>

<template>
  <app-container>
    <!-- 审批弹窗 -->
    <approval-dialog ref="approvalDialogRef" @on-success="search" />
    <!-- 筛选条件 -->
    <search-area :need-clear="true" @search="search" @clear="reset">
      <search-item>
        <el-input v-model.trim="listQuery.approvalNo" placeholder="登记表编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.equipmentNo" placeholder="统一编号" clearable />
      </search-item>
      <search-item>
        <el-input v-model.trim="listQuery.equipmentName" placeholder="设备名称" clearable />
      </search-item>
    </search-area>
    <table-container>
      <template v-if="$props.statusName === '全部'" #btns-right>
        <icon-button icon="icon-add" title="新增" @click="handler({}, 'create')" />
      </template>
      <!-- 普通表格 -->
      <normal-table
        :data="list" :total="total" :columns="columns" :query="listQuery"
        :list-loading="listLoading" :is-showmulti-select="true" @change="changePage"
      >
        <template #columns>
          <el-table-column v-if="$props.statusName !== '全部'" label="审批状态" align="center">
            <template #default=" scope ">
              {{ scope.row.approvalStatusName }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" align="center">
            <template #default=" scope ">
              <el-button link type="primary" size="small" @click="detail(scope.row)">
                查看
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.edit.if({ approvalStatusName: $props.statusName }, permUrl.edit) && $props.statusName !== '全部'" link type="primary" size="small"
                @click="handler(scope.row, 'update')"
              >
                编辑
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.agree.if({ approvalStatusName: $props.statusName }, permUrl.agree)" link type="primary" size="small"
                @click="approveHandler(scope.row, 'agree')"
              >
                同意
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.reject.if({ approvalStatusName: $props.statusName }, permUrl.reject)" link type="primary" size="small"
                @click="approveHandler(scope.row, 'refuse')"
              >
                拒绝
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.submit.if({ approvalStatusName: $props.statusName }, permUrl.submit)" link type="primary" size="small"
                @click="submit(scope.row)"
              >
                提交
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.cancel.if({ approvalStatusName: $props.statusName }, permUrl.cancel)" link type="primary" size="small"
                @click="canHandler(scope.row)"
              >
                取消
              </el-button>
              <el-button
                v-if="proxy.buttonPerm.delete.if({ approvalStatusName: $props.statusName }, permUrl.del) && $props.statusName !== '全部'" link type="danger" size="small"
                @click="delHandler(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </template>
      </normal-table>
    </table-container>
  </app-container>
</template>

<style lang="scss" scoped>
.nortable-header {
  ::v-deep(.el-table__body-wrapper) {
    display: none;
  }
}
</style>

