<template>
  <BasicDialog ref="basicDialogRef" title="物资领用" width="500px" @refresh="refreshFormData">
    <template #form>
      <div class="claim-dialog-content">
        <div class="claim-dialog-label">请选择领用存放信息</div>
        <el-select
          v-model="selectedSupplyId"
          placeholder="请选择需求部门"
          filterable
          style="width: 100%"
          :loading="supplyListLoading"
        >
          <el-option
            v-for="item in supplyList"
            :key="item.id"
            :label="`${item.supplyName} | ${getLocation(item.location)} | ${item.keeperName}`"
            :value="item.id"
          />
        </el-select>
      </div>
    </template>
    <template #footer>
      <el-button @click="basicDialogRef?.closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">提交</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicDialog from '@/components/BasicDialog.vue';
  import { getEmergencySuppliesInfoList } from '@/api/command-center';
  import type { QueryEmergencySuppliesInfoListRes } from '@/api/command-center';
  import { receiveSupplyRequestDetail } from '@/api/emergency-supplier';
  import { useEmergencySuppliesHook } from '@/views/emergency/emergency-supplies/src/hook';

  const { getLocationDict, getLocation } = useEmergencySuppliesHook();

  interface Emits {
    (e: 'success'): void;
  }

  const emit = defineEmits<Emits>();

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const selectedSupplyId = ref<number | null>(null);
  const supplyList = ref<QueryEmergencySuppliesInfoListRes[]>([]);
  const supplyListLoading = ref(false);
  const submitLoading = ref(false);

  // 当前领用的数据
  const currentSupplyName = ref('');
  const currentQuantity = ref(0);
  const currentDetailId = ref(0);
  const currentPlanId = ref(0);

  // 打开对话框
  const openDialog = (supplyName: string, quantity: number, detailId: number, planId: number) => {
    currentSupplyName.value = supplyName;
    currentQuantity.value = quantity;
    currentDetailId.value = detailId;
    currentPlanId.value = planId;
    if (supplyName) {
      loadSupplyList(supplyName);
    }
    basicDialogRef.value?.openDialog();
  };

  // 刷新表单数据
  const refreshFormData = () => {
    selectedSupplyId.value = null;
    supplyList.value = [];
  };

  // 加载应急物资列表
  const loadSupplyList = async (supplyName: string) => {
    if (!supplyName) {
      return;
    }
    supplyListLoading.value = true;
    try {
      const res = await getEmergencySuppliesInfoList({
        supplyName,
      });
      supplyList.value = res || [];
      if (supplyList.value.length === 0) {
        ElMessage.warning('未找到匹配的应急物资信息');
      }
    } catch (error) {
      console.error('获取应急物资列表失败:', error);
      ElMessage.error('获取应急物资列表失败');
    } finally {
      supplyListLoading.value = false;
    }
  };

  // 提交领用
  const handleSubmit = async () => {
    if (!selectedSupplyId.value) {
      ElMessage.warning('请选择领用存放信息');
      return;
    }

    submitLoading.value = true;
    try {
      await receiveSupplyRequestDetail({
        supplyId: selectedSupplyId.value,
        quantity: currentQuantity.value,
        detailId: currentDetailId.value,
        planId: currentPlanId.value,
      });
      ElMessage.success('领用操作成功');
      basicDialogRef.value?.closeDialog();
      emit('success');
    } catch (error) {
      console.error('领用失败:', error);
      ElMessage.error('领用操作失败');
    } finally {
      submitLoading.value = false;
    }
  };

  defineExpose({
    openDialog,
  });

  onMounted(() => {
    getLocationDict('all');
  });
</script>

<style scoped lang="scss">
  .claim-dialog-content {
    padding: 20px 0;
  }

  .claim-dialog-label {
    margin-bottom: 12px;
    font-size: 14px;
    color: #606266;
  }
</style>
