<script lang="ts" setup>
import type { EnergyStationConfigApi } from '#/api/energy/station-config';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createStationConfig,
  updateStationConfig,
} from '#/api/energy/station-config';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emit = defineEmits(['success']);
const formData = ref<EnergyStationConfigApi.Config>();
const isUpdate = computed(() => !!formData.value?.id);

const getTitle = computed(() => {
  return isUpdate.value
    ? $t('ui.actionTitle.edit', ['站点配置'])
    : $t('ui.actionTitle.create', ['站点配置']);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 120,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    const data = (await formApi.getValues()) as EnergyStationConfigApi.Config;
    try {
      await (isUpdate.value
        ? updateStationConfig(data)
        : createStationConfig(data));
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    const data = modalApi.getData<EnergyStationConfigApi.Config>();
    if (!data || !data.id) {
      return;
    }
    modalApi.lock();
    try {
      formData.value = data;
      await formApi.setValues(formData.value);
      // 编辑时禁用加氢站选择
      await formApi.updateSchema([
        {
          fieldName: 'stationId',
          componentProps: { disabled: true },
        },
      ]);
    } finally {
      modalApi.unlock();
    }
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-2/3">
    <Form class="mx-4" />
    <div class="mx-4 mb-4 rounded bg-blue-50 px-3 py-2 text-sm text-blue-600">
      此配置仅对预充值模式客户生效，月结算客户不涉及账户扣款
    </div>
  </Modal>
</template>
