<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> 奖品领取审核列表 </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div style="position: relative">
            <!-- <el-button plain class="search-table-container--button" @click="handleImport">
              导入
            </el-button>
            <el-button plain class="search-table-container--button" @click="handleDownload">
              导出
            </el-button> -->
          </div>

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>奖品名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.stuffName"
                  placeholder="搜索奖品名称"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>部门名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.deptName"
                  placeholder="搜索部门名称"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select v-model="tableQuery.queryParam.status" placeholder="请选择状态" clearable>
                  <el-option
                    v-for="item in ADMIN_RECEIPT_RECORD_STATUS_OPTIONS"
                    :key="String(item.value)"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #status="scope">
              <span>{{ ADMIN_RECEIPT_RECORD_STATUS_LABEL[String(scope.row.status)] ?? '-' }}</span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <!-- 0 待审核：审核、查看 -->
                <template v-if="Number(scope.row.status) === 0">
                  <ActionButton text="审核" @click="handleAudit(scope.row.id, scope.row.approvalOrder)" />
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
                <!-- 1 审核通过、-1 审核不通过、2 已领取：查看 -->
                <template v-else>
                  <ActionButton text="查看" @click="handleView(scope.row.id)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="下载模板"
      :show-template="false"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
  </div>
  <BasicDialog ref="basicDialogRef" title="审核" @refresh="closeDialog">
    <template #form>
      <el-form ref="formRef" :model="formData" style="width: 100%">
        <el-form-item label="审核：" prop="approvalStatus" :rules="[{ required: true, message: '请选择审核状态' }]">
          <el-radio-group v-model="formData.approvalStatus">
            <el-radio :value="APPROVAL_STATUS.APPROVED">通过</el-radio>
            <el-radio :value="APPROVAL_STATUS.REJECTED">退回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="formData.approvalStatus === APPROVAL_STATUS.REJECTED"
          label="退回原因："
          prop="rejectReason"
          :rules="[{ required: true, message: '请输入退回原因' }]"
        >
          <el-input v-model="formData.rejectReason" placeholder="请输入退回原因" type="textarea" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button type="primary" @click="handleApprovalSubmit">提交</el-button>
      <el-button @click="basicDialogRef?.closeDialog">返回</el-button>
    </template>
  </BasicDialog>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import BasicTable from '@/components/BasicTable.vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, ADMIN_RECEIPT_RECORD_TABLE_COLUMNS } from './configs/tables';
  import { ADMIN_RECEIPT_RECORD_STATUS_OPTIONS, ADMIN_RECEIPT_RECORD_STATUS_LABEL } from './configs/status';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryClaimItemsApprovalPage,
    deleteClaimItemsLog,
    exportClaimItemsLog,
    submitReceiptRecordApproval,
  } from '@/api/receiptRecord';
  import { downloadByData } from '@/utils/file/download';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { ElMessage, type ElForm } from 'element-plus';
  import { APPROVAL_STATUS } from '@/views/emergency/emergency-plan/src/constant';

  const router = useRouter();

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(ADMIN_RECEIPT_RECORD_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableData = ref<any[]>([]);

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const formRef = ref<InstanceType<typeof ElForm>>();
  const formData = reactive({
    approvalStatus: APPROVAL_STATUS.APPROVED,
    rejectReason: '',
  });
  const currentId = ref<number>();
  const currentOrder = ref<number>();

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      stuffName: '',
      deptName: '',
      status: undefined as number | undefined, // 0 待审核, 1 审核通过, -1 审核不通过, 2 已领取
    },
  });

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await queryClaimItemsApprovalPage(tableQuery);
      if (res) {
        // 映射返回数据字段到表格字段,并处理可能的null或undefined值
        tableData.value = res.records.map((item) => {
          if (item && typeof item === 'object') {
            return {
              id: item.id,
              itemName: item.stuffName, // 奖品名称
              outboundDate: item.outStoreTime, // 出库日期
              outboundQuantity: item.claimQty, // 取出数量
              remainingQuantity: item.surplusQty, // 结余数量
              receiptNumber: item.orderNumber, // 单号
              department: item.deptName, // 部门
              recipient: item.userName, // 领取人
              status: item.status, // 0 待审核 1 审核通过 -1 审核不通过 2 已领取
              approvalOrder: item.approvalOrder, // 审批顺序
            };
          }
        });
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取奖品领取记录列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.stuffName = '';
    tableQuery.queryParam.deptName = '';
    tableQuery.queryParam.status = undefined;
    handleSearch();
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/claimItemsLog/importClaimItemsLog'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/import-receipt-record-template.xlsx');

  const handleImport = () => {
    batchImportVisible.value = true;
  };

  const handleUpdate = () => {
    batchImportVisible.value = false;
    getTableData();
  };

  const handleDownload = async () => {
    try {
      const exportParams = {
        stuffName: tableQuery.queryParam.stuffName || undefined,
        deptName: tableQuery.queryParam.deptName || undefined,
        status: tableQuery.queryParam.status,
      };
      const response = await exportClaimItemsLog(exportParams);
      if (response) {
        const fileName = `奖品领取记录_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出奖品领取记录失败:', e);
      ElMessage.error(e?.message || e?.data || '导出失败，请重试');
    }
  };

  const handleEdit = (id: number) => {
    router.push({
      name: 'ReceiptRecordItem',
      query: {
        id,
        operate: 'receiptRecord-edit',
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteClaimItemsLog(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除奖品领取记录失败:', e);
      ElMessage.error(e?.message || e?.data || '删除失败，请重试');
    }
  };

  const handleView = (id: number) => {
    router.push({
      name: 'ReceiptRecordItem',
      query: {
        id,
        operate: 'receiptRecord-view',
      },
    });
  };

  const handleAudit = (id: number, approvalOrder: number) => {
    currentId.value = id;
    currentOrder.value = approvalOrder;
    basicDialogRef.value?.openDialog();
  };

  const closeDialog = () => {
    formRef.value?.resetFields();
    basicDialogRef.value?.closeDialog();
  };

  const handleApprovalSubmit = () => {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        if (!currentId.value || !currentOrder.value) return;
        await submitReceiptRecordApproval({
          planId: currentId.value,
          approvalOrder: currentOrder.value,
          approvalStatus: formData.approvalStatus,
          returnReason: formData.rejectReason,
        });
        ElMessage.success('审核成功');
        basicDialogRef.value?.closeDialog();
        getTableData();
      }
    });
  };

  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;
</style>
