<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import { DictEnum } from '@vben/constants';

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

import {
  addStationInfo,
  getStationInfoDetail,
  selectAllSysStationAreaList,
  updateStationInfo,
} from '#/api/system/infoEntry/stationInfo/stationInfo';

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

const props = defineProps<{
  areaOptions?: any[];
}>();

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

const confirmLoading = ref(false);
const isUpdateRef = ref<boolean>(false);
const localAreaOptions = ref<any[]>([]);
const formSchema = ref(drawerFormSchema());

const [Form, formApi] = useVbenForm({
  showDefaultActions: false,
  schema: formSchema.value,
  autoSubmitOnEnter: false,
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onOpenChange(isOpen) {
    if (!isOpen) {
      return;
    }
    try {
      drawerApi.drawerLoading(true);
      const { id, isUpdate } = drawerApi.getData();
      isUpdateRef.value = isUpdate;

      await loadAreaOptions();

      if (isUpdate && id) {
        const res = await getStationInfoDetail(id);
        await formApi.setValues(res);
      } else {
        await formApi.resetForm();
        await nextTick();
        await formApi.setValueByField('status', '1'); // 统一使用字符串类型1);
      }
    } catch (error) {
      console.error('获取场站详情失败:', error);
    } finally {
      drawerApi.drawerLoading(false);
    }
  },

  async onConfirm() {
    try {
      confirmLoading.value = true;
      const { valid } = await formApi.validate();
      if (!valid) {
        return;
      }
      const data = await formApi.getValues();
      await (isUpdateRef.value
        ? updateStationInfo(data)
        : addStationInfo(data));
      emit('reload');
      drawerApi.close();
    } catch (error) {
      console.error('保存场站信息失败:', error);
    } finally {
      confirmLoading.value = false;
    }
  },

  onClosed() {
    formApi.resetForm();
  },
});

const loadAreaOptions = async () => {
  try {
    if (props.areaOptions && props.areaOptions.length > 0) {
      localAreaOptions.value = props.areaOptions;
    } else {
      const resp = await selectAllSysStationAreaList();
      const data = resp?.data || resp || [];
      localAreaOptions.value = Array.isArray(data)
        ? data.map((item: any) => ({
            label: item.areaName,
            value: item.id,
          }))
        : [];
    }

    const areaField = formSchema.value.find(
      (item) => item.fieldName === 'areaId',
    );
    if (areaField) {
      areaField.componentProps.options = localAreaOptions.value || [];
    }
  } catch (error) {
    console.error('加载片区选项失败:', error);
  }
};

</script>

<template>
  <Drawer
    :title="isUpdateRef ? '编辑场站' : '新增场站'"
    :confirm-loading="confirmLoading"
  >
    <Form />
  </Drawer>
</template>
