import type { FinanceInvoiceSettingFormState } from '../../types';

/**
 * 文件职责：发票设置保存与确认动作。
 */
import type { FinanceInvoiceSettingDto } from '#/api/finance';

import { saveFinanceInvoiceSettingApi } from '#/api/finance';

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

import {
  buildSettingSavePayload,
  cloneSettingsForm,
  isSettingsChanged,
} from './helpers';

interface SettingsActionOptions {
  applySettingsResult: (result: FinanceInvoiceSettingDto) => void;
  canManageSettings: { value: boolean };
  isSettingsConfirmModalOpen: { value: boolean };
  isSettingsSaving: { value: boolean };
  settingForm: FinanceInvoiceSettingFormState;
  settingSnapshot: { value: FinanceInvoiceSettingFormState };
}

/** 创建发票设置动作。 */
export function createSettingsActions(options: SettingsActionOptions) {
  function setSettingsConfirmModalOpen(value: boolean) {
    options.isSettingsConfirmModalOpen.value = value;
  }

  function resetSettings() {
    Object.assign(options.settingForm, cloneSettingsForm(options.settingSnapshot.value));
  }

  function hasSettingsChanged() {
    return isSettingsChanged(options.settingForm, options.settingSnapshot.value);
  }

  function validateSettings() {
    if (!options.settingForm.companyName.trim()) {
      message.warning('请输入企业名称');
      return false;
    }

    if (!options.settingForm.taxpayerNumber.trim()) {
      message.warning('请输入纳税人识别号');
      return false;
    }

    if (
      !options.settingForm.enableElectronicNormalInvoice &&
      !options.settingForm.enableElectronicSpecialInvoice
    ) {
      message.warning('请至少启用一种发票类型');
      return false;
    }

    if (options.settingForm.enableAutoIssue) {
      const maxAmount = Number(options.settingForm.autoIssueMaxAmount || 0);
      if (!Number.isFinite(maxAmount) || maxAmount <= 0) {
        message.warning('自动开票最大金额必须大于 0');
        return false;
      }
    }

    return true;
  }

  function openSettingsConfirmModal() {
    if (!options.canManageSettings.value) {
      message.warning('当前账号暂无发票设置权限');
      return;
    }

    if (!validateSettings()) {
      return;
    }

    if (!hasSettingsChanged()) {
      message.info('未检测到设置变更');
      return;
    }

    options.isSettingsConfirmModalOpen.value = true;
  }

  async function submitSettings() {
    if (!options.canManageSettings.value) {
      message.warning('当前账号暂无发票设置权限');
      return;
    }

    if (!validateSettings()) {
      return;
    }

    options.isSettingsSaving.value = true;
    try {
      const result = await saveFinanceInvoiceSettingApi(
        buildSettingSavePayload(options.settingForm),
      );
      options.applySettingsResult(result);
      options.isSettingsConfirmModalOpen.value = false;
      message.success('发票设置已保存');
    } finally {
      options.isSettingsSaving.value = false;
    }
  }

  return {
    hasSettingsChanged,
    openSettingsConfirmModal,
    resetSettings,
    setSettingsConfirmModalOpen,
    submitSettings,
    validateSettings,
  };
}
