<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { useVbenDrawer, useVbenForm } from '@vben/common-ui';

import {
  addRival,
  getRivalDetail,
  updateRival,
} from '#/api/oilstation/rival/rival';
import { getDictOptions } from '#/utils/dict';

import { drawerFormSchema } from './rival-data';

const emit = defineEmits<{
  reload: [];
}>();

// 字典标识常量
const DICT_KEYS = {
  // 竞争关系字典标识
  COMPETITIVE_RELATION: 'competitive_relation',
  // 油站性质字典标识
  GAS_STATION: 'gas_station',
};

// 获取字典选项函数
const getDictOptionsByKey = (key: string) => getDictOptions(key);

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
    // labelClass: 'w-2/7',
    labelWidth: 120,
  },
  schema: drawerFormSchema(),
});

// 获取初始字典数据，确保表单加载时有默认选项
onMounted(() => {
  getDictOptionsByKey(DICT_KEYS.COMPETITIVE_RELATION);
  getDictOptionsByKey(DICT_KEYS.GAS_STATION);
});

const isUpdateRef = ref<boolean>(false);

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { id, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;
      if (isUpdate && id) {
        const res = await getRivalDetail(id);
        console.log('获取竞争对手详情数据:', res);
        // 确保从正确的响应结构中获取数据
        const detailData = res?.data || res;

        // 处理表单数据
        const formData = {
          ...detailData,
        };

        await formApi.setValues(formData);
      }
    } catch (error) {
      console.error('获取竞争对手详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      this.confirmLoading = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();

      // 确保使用正确的字段名提交数据
      const submitData = {
        ...data,
      };

      console.log('提交数据:', submitData);
      await (isUpdateRef.value
        ? updateRival(submitData)
        : addRival(submitData));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存竞争对手信息失败:', error);
    } finally {
      this.confirmLoading = false;
    }
  },

  onClosed() {
    formApi.resetForm();
  },
});
</script>

<template>
  <Drawer :title="isUpdateRef ? '编辑竞争对手' : '新增竞争对手'">
    <Form />
  </Drawer>
</template>
