<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title">物资申领</div>
    </div>
    <div class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <el-button
            type="primary"
            class="search-table-container--button"
            :icon="Plus"
            @click="handleCreateRequest"
            v-if="supplyRequestManagePermission"
          >
            创建申领计划
          </el-button>
          <BasicSearch
            :searchConfig="SUPPLY_REQUEST_SEARCH_CONFIG"
            :searchData="searchData"
            @update:search-data="handleSearch"
          >
            <template #planName>
              <el-input
                v-model="searchData.planName"
                placeholder="请输入物资申领计划"
                clearable
                @keyup.enter="handleSearch"
              />
            </template>
          </BasicSearch>
        </header>
        <BasicTable
          :tableData="tableData"
          :tableConfig="tableConfig"
          @update:page-size="handleSizeChange"
          @update:page-number="handleCurrentChange"
        >
          <template #status="scope">
            <span>{{ getStatusText(scope.row.status) }}</span>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton text="详情" @click="handleViewDetail(scope.row.id)" />
              <template v-if="scope.row.status === SUPPLY_REQUEST_STATUS.APPLYING && supplyRequestManagePermission">
                <ActionButton text="发起采购" @click="handleStartPurchase(scope.row)" />
                <ActionButton text="编辑" @click="handleEdit(scope.row)" />
                <ActionButton
                  text="删除"
                  :popconfirm="{
                    title: '确定删除？',
                  }"
                  @confirm="handleDelete(scope.row.id)"
                />
              </template>
              <template
                v-else-if="
                  scope.row.status === SUPPLY_REQUEST_STATUS.PURCHASING ||
                  scope.row.status === SUPPLY_REQUEST_STATUS.RECEIVING
                "
              >
                <ActionButton text="编辑" @click="handleEdit(scope.row)" v-if="supplyRequestManagePermission" />
              </template>
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
  </div>
  <SupplyRequestForm ref="supplyRequestFormRef" @success="handleFormSuccess" />
  <StartPurchaseForm ref="startPurchaseFormRef" @success="handleFormSuccess" />
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import { useRouter } from 'vue-router';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import SupplyRequestForm from './src/components/SupplyRequestForm.vue';
  import StartPurchaseForm from './src/components/StartPurchaseForm.vue';
  import {
    SUPPLY_REQUEST_SEARCH_CONFIG,
    SUPPLY_REQUEST_TABLE_COLUMNS,
    SUPPLY_REQUEST_TABLE_OPTIONS,
    SUPPLY_REQUEST_TABLE_MAX_HEIGHT_DEFAULT,
  } from './src/config';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { EMERGENCY_PERMISSIONS } from '@/views/emergency/src/constant';
  import { SUPPLY_REQUEST_STATUS, SUPPLY_REQUEST_STATUS_MAP } from './src/constant';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { SupplyRequestListQuery, SupplyRequestListItem } from '@/types/emergency-supplier';
  import { getSupplyRequestList, deleteSupplyRequest, getSupplyRequestDetail } from '@/api/emergency-supplier';

  const router = useRouter();
  const { permissions } = useUserInfoHook();

  const supplyRequestManagePermission = ref<Boolean>(false);

  const { tableConfig, pagination } = useTableConfig(SUPPLY_REQUEST_TABLE_COLUMNS, SUPPLY_REQUEST_TABLE_OPTIONS);
  let supplyRequestListQuery: QueryPageRequest<SupplyRequestListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };

  const tableData = ref<SupplyRequestListItem[]>([]);
  const searchData = reactive({
    planName: '',
    status: SUPPLY_REQUEST_STATUS.ALL,
  });

  const supplyRequestFormRef = ref<InstanceType<typeof SupplyRequestForm>>();
  const startPurchaseFormRef = ref<InstanceType<typeof StartPurchaseForm>>();

  // 获取状态文本
  const getStatusText = (status: number) => {
    return SUPPLY_REQUEST_STATUS_MAP[status] || '';
  };

  // 搜索处理
  const handleSearch = () => {
    supplyRequestListQuery.queryParam = {};
    if (searchData.planName) {
      supplyRequestListQuery.queryParam.planName = searchData.planName;
    }
    if (searchData.status !== null && searchData.status !== SUPPLY_REQUEST_STATUS.ALL) {
      supplyRequestListQuery.queryParam.status = searchData.status;
    }
    getTableData();
  };

  // 获取表格数据
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getSupplyRequestList(supplyRequestListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };

  // 分页处理
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    supplyRequestListQuery.pageSize = value;
    getTableData();
  };

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

  // 创建申领计划
  const handleCreateRequest = () => {
    supplyRequestFormRef.value?.openAddDialog();
  };
  // 查看详情
  const handleViewDetail = (id: number) => {
    router.push({
      name: 'supply-request-detail',
      params: {
        id,
      },
    });
  };

  // 发起采购
  const handleStartPurchase = async (row: SupplyRequestListItem) => {
    if (!row.id) return;
    const res = await getSupplyRequestDetail(row.id);
    if (res.length === 0 || res.some((item) => item.detailList.length === 0)) {
      ElMessage.error('此计划详情内没有物资，无法发起采购');
      return;
    }
    startPurchaseFormRef.value?.openDialog(row);
  };

  // 编辑
  const handleEdit = (row: SupplyRequestListItem) => {
    supplyRequestFormRef.value?.openEditDialog(row);
  };

  // 表单提交成功回调
  const handleFormSuccess = () => {
    getTableData();
  };

  // 删除
  const handleDelete = async (id: number) => {
    await deleteSupplyRequest(id);
    await getTableData();
    ElMessage.success('删除成功');
  };

  onMounted(() => {
    getTableData();
    tableConfig.maxHeight = SUPPLY_REQUEST_TABLE_MAX_HEIGHT_DEFAULT;
    supplyRequestManagePermission.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.SUPPLY_REQUEST_MANAGE),
    );
  });
</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 './src/styles/page-common.scss' as *;
</style>
