<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 type="primary" class="search-table-container--button" @click="handleCreate">
              添加
            </el-button>
          </div> -->

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>申请人：</span>
                <el-input
                  v-model="tableQuery.queryParam.name"
                  placeholder="请输入申请人"
                  class="act-search-input"
                  clearable
                />
              </div>
              <!-- <div class="select-box--item">
                <span>状态：</span>
                <el-select
                  v-model="tableQuery.queryParam.approvalStatus"
                  placeholder="请选择状态"
                  clearable
                  class="act-search-input"
                >
                  <el-option label="待审核" :value="1" />
                  <el-option label="审核通过" :value="2" />
                  <el-option label="审核不通过" :value="3" />
                </el-select>
              </div> -->
              <div class="select-box--item">
                <span>申请部门：</span>
                <el-input
                  v-model="tableQuery.queryParam.applyDeptName"
                  placeholder="请输入申请部门名称"
                  class="act-search-input"
                  clearable
                />
              </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>
                {{ scope.row.statusName || getStatusText(scope.row.approvalStatus) }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <!-- 待审核：查看、审核 -->
                <template v-if="scope.row.approvalStatus === 1 || scope.row.approvalStatus === '1'">
                  <ActionButton text="查看" @click="handleView(scope.row.id!, scope.row)" />
                  <ActionButton text="审核" @click="handleAudit(scope.row.id!, scope.row)" />
                </template>
                <!-- 审核通过：查看 -->
                <template v-else-if="scope.row.approvalStatus === 2 || scope.row.approvalStatus === '2'">
                  <ActionButton text="查看" @click="handleView(scope.row.id!, scope.row)" />
                </template>
                <!-- 审核不通过：编辑、删除、查看 -->
                <template v-else-if="scope.row.approvalStatus === 3 || scope.row.approvalStatus === '3'">
                  <!-- <ActionButton text="编辑" @click="handleEdit(scope.row.id!, scope.row)" />
                  <ActionButton
                    text="删除"
                    :popconfirm="{ title: '确定要删除该申请吗？' }"
                    @confirm="handleDelete(scope.row.id!)"
                  /> -->
                  <ActionButton text="查看" @click="handleView(scope.row.id!, scope.row)" />
                </template>
                <template v-else>
                  <ActionButton text="查看" @click="handleView(scope.row.id!, scope.row)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, PURCHASE_APPLY_TABLE_COLUMNS } from './configs/tablesTow';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    queryPurchaseApplyListAdmin,
    deletePurchaseApply,
    type PpePurchaseApply,
    type QueryPurchaseApplyPageReq,
  } from '@/api/production-safety/personal-protective-equipment-purchase-apply';
  import { template } from 'lodash-es';

  const router = useRouter();
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

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

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

  const tableQuery = reactive<QueryPageRequest<QueryPurchaseApplyPageReq>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      name: '',
      status: 1,
      applyDeptCode: '',
      applyDeptName: '',
    },
  });

  function getStatusText(approvalStatus: number | string | undefined) {
    if (approvalStatus === 1 || approvalStatus === '1') return '待审核';
    if (approvalStatus === 2 || approvalStatus === '2') return '审核通过';
    if (approvalStatus === 3 || approvalStatus === '3') return '审核不通过';
    return '-';
  }

  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 queryPurchaseApplyListAdmin(tableQuery);
      // if (res) {
      //   tableData.value = (res?.records ?? res?.list ?? []) as PpePurchaseApply[];
      //   pagination.total = res?.totalRow ?? res?.total ?? 0;
      // }
      const res = await queryPurchaseApplyListAdmin(tableQuery);
      const resWithExtra = res as (typeof res & {
        list?: PpePurchaseApply[],
        total?: number
      });
      if (resWithExtra) {
        tableData.value = (resWithExtra?.records ?? resWithExtra?.list ?? []) as PpePurchaseApply[];
        pagination.total = resWithExtra?.totalRow ?? resWithExtra?.total ?? 0;
      }
    } 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.name = '';
    tableQuery.queryParam.approvalStatus = undefined;
    tableQuery.queryParam.applyDeptCode = '';
    tableQuery.queryParam.applyDeptName = '';
    handleSearch();
  };

  const handleCreate = () => {
    router.push({
      name: 'laborProductsPurchaseApplyManageItem',
      query: { operate: 'inventory-create' },
    });
  };

  const handleEdit = (id: number, row?: PpePurchaseApply) => {
    router.push({
      name: 'laborProductsPurchaseApplyManageItem',
      query: {
        id: String(id),
        operate: 'inventory-edit',
        ...(row && {
          applyCode: String(row.applyCode ?? ''),
          applicantName: row.applicantName ?? '',
          deptName: row.deptName ?? '',
          templateId: row.templateId ?? '',
          rejectReason: row.ppeDescription ?? '',
          approvalStatus: row.approvalStatus ?? '',
        }),
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await deletePurchaseApply(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除失败:', e);
      ElMessage.error('删除失败，请重试');
    }
  };

  const handleView = (id: number, row?: PpePurchaseApply) => {
    router.push({
      name: 'laborProductsPurchaseApplyManageItem',
      query: {
        id: String(id),
        operate: 'inventory-view',
        ...(row && {
          applyCode: String(row.applyCode ?? ''),
          applicantName: row.applicantName ?? '',
          deptName: row.deptName ?? '',
          templateId: row.templateId ?? '',
          rejectReason: row.ppeDescription ?? '',
          approvalStatus: row.approvalStatus ?? '',
        }),
      },
    });
  };

  const handleAudit = (id: number, row?: PpePurchaseApply) => {
    router.push({
      name: 'laborProductsPurchaseApplyManageItem',
      query: {
        id: String(id),
        operate: 'audit',
        ...(row && {
          applyCode: String(row.applyCode ?? ''),
          applicantName: row.applicantName ?? '',
          deptName: row.deptName ?? '',
          approvalOrder: row.approvalOrder ?? '',
          templateId: row.templateId ?? '',
          rejectReason: row.ppeDescription ?? '',
          approvalStatus: row.approvalStatus ?? '',
        }),
      },
    });
  };

  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>
