<template>
  <BasicDialog ref="basicDialogRef" :title="dialogTitle" @close="refreshFormData">
    <template #form>
      <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig" />
    </template>
    <template #footer>
      <el-button @click="basicDialogRef?.closeDialog">取消</el-button>
      <el-button type="primary" @click="handleSubmit">提交</el-button>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicDialog from '@/components/BasicDialog.vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { SUPPLY_REQUEST_FORM_CONFIG, SUPPLY_REQUEST_FORM_DATA, SUPPLY_REQUEST_FORM_RULES } from '../config';
  import { createSupplyRequest, updateSupplyRequest } from '@/api/emergency-supplier';
  import type { SupplyRequestListItem } from '@/types/emergency-supplier';

  const emits = defineEmits<{
    (e: 'success'): void;
  }>();

  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const basicFormRef = ref<InstanceType<typeof BasicForm>>();
  const isEditMode = ref(false);
  const editId = ref<number | undefined>(undefined);
  const requestInfo = ref<SupplyRequestListItem | undefined>(undefined);

  const { ruleFormConfig, ruleFormData, formRules } = useFormConfigHook(
    SUPPLY_REQUEST_FORM_CONFIG,
    SUPPLY_REQUEST_FORM_DATA,
    SUPPLY_REQUEST_FORM_RULES,
  );

  // 对话框标题
  const dialogTitle = computed(() => {
    return isEditMode.value ? '编辑申领计划' : '创建申领计划';
  });

  // 打开对话框（创建模式）
  const openAddDialog = () => {
    isEditMode.value = false;
    editId.value = undefined;
    basicDialogRef.value?.openDialog();
  };

  // 打开对话框（编辑模式）
  const openEditDialog = async (row: SupplyRequestListItem) => {
    isEditMode.value = true;
    requestInfo.value = row;
    editId.value = requestInfo.value?.id;
    ruleFormData.planName = requestInfo.value?.planName || '';
    ruleFormData.purchaseDate = requestInfo.value?.purchaseDate || '';
    basicDialogRef.value?.openDialog();
  };

  // 提交表单
  const handleSubmit = async () => {
    const validate = await basicFormRef.value?.validateForm();
    if (!validate) return;

    try {
      const submitData = ruleFormData.purchaseDate
        ? {
            planName: ruleFormData.planName,
            purchaseDate: ruleFormData.purchaseDate,
          }
        : {
            planName: ruleFormData.planName,
          };

      if (isEditMode.value && editId.value) {
        await updateSupplyRequest({
          id: editId.value,
          ...submitData,
          totalPrice: requestInfo.value?.totalPrice,
          status: requestInfo.value?.status,
        });
        ElMessage.success('编辑成功');
      } else {
        await createSupplyRequest(submitData);
        ElMessage.success('创建成功');
      }

      basicDialogRef.value?.closeDialog();
      // 触发父组件刷新列表
      emits('success');
    } catch (error) {
      console.error('提交失败:', error);
    }
  };

  // 刷新表单数据
  const refreshFormData = () => {
    basicFormRef.value?.clearValidate();
    ruleFormData.planName = '';
    ruleFormData.purchaseDate = '';
  };

  defineExpose({
    openAddDialog,
    openEditDialog,
  });
</script>

<style scoped lang="scss"></style>
