<template>
  <BasicDialog ref="basicDialogRef" title="发起采购" @refresh="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 } 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 { START_PURCHASE_FORM_CONFIG, START_PURCHASE_FORM_DATA, START_PURCHASE_FORM_RULES } from '../config';
  import { updateSupplyRequest } from '@/api/emergency-supplier';
  import { SUPPLY_REQUEST_STATUS } from '../constant';
  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 requestId = ref<number | undefined>(undefined);

  // 保留一份申领计划信息
  const requestInfo = ref<SupplyRequestListItem | undefined>(undefined);

  const { ruleFormConfig, ruleFormData, formRules } = useFormConfigHook(
    START_PURCHASE_FORM_CONFIG,
    START_PURCHASE_FORM_DATA,
    START_PURCHASE_FORM_RULES,
  );

  // 打开对话框
  const openDialog = (row: SupplyRequestListItem) => {
    requestInfo.value = row;
    requestId.value = requestInfo.value?.id;
    // 先设置采购日期，再打开对话框
    // 如果有已有采购日期，则反显
    ruleFormData.purchaseDate = requestInfo.value?.purchaseDate || '';
    basicDialogRef.value?.openDialog();
  };

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

    if (!requestId.value) {
      ElMessage.error('缺少必要参数');
      return;
    }

    try {
      await updateSupplyRequest({
        id: requestId.value,
        planName: requestInfo.value?.planName,
        purchaseDate: ruleFormData.purchaseDate,
        totalPrice: requestInfo.value?.totalPrice,
        status: SUPPLY_REQUEST_STATUS.PURCHASING,
      });
      ElMessage.success('发起采购成功');
      basicDialogRef.value?.closeDialog();
      // 清理数据
      requestId.value = undefined;
      ruleFormData.purchaseDate = '';
      // 触发父组件刷新列表
      emits('success');
    } catch (error) {
      console.error('发起采购失败:', error);
      ElMessage.error('发起采购失败');
    }
  };

  // 刷新表单数据（在对话框打开时调用，用于清除验证状态）
  const refreshFormData = () => {
    basicFormRef.value?.clearValidate();
  };

  defineExpose({
    openDialog,
  });
</script>

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