import type {
  FinanceInvoiceIssueResultDto,
  FinanceInvoiceRecordDetailDto,
  FinanceInvoiceRecordListItemDto,
} from '#/api/finance';
import type {
  FinanceInvoiceIssueFormState,
  FinanceInvoiceVoidFormState,
} from '../../types';

/**
 * 文件职责：发票管理页面抽屉与弹窗动作。
 */
import {
  getFinanceInvoiceRecordDetailApi,
  issueFinanceInvoiceRecordApi,
  voidFinanceInvoiceRecordApi,
} from '#/api/finance';

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

import { isPendingInvoice, toOptionalTrimmed } from './helpers';

interface DrawerActionOptions {
  canIssue: { value: boolean };
  canVoid: { value: boolean };
  detail: { value: FinanceInvoiceRecordDetailDto | null };
  isDetailDrawerOpen: { value: boolean };
  isDetailLoading: { value: boolean };
  isIssueDetailLoading: { value: boolean };
  isIssueDrawerOpen: { value: boolean };
  isIssueResultModalOpen: { value: boolean };
  isIssueSubmitting: { value: boolean };
  isVoidModalOpen: { value: boolean };
  isVoidSubmitting: { value: boolean };
  issueDetail: { value: FinanceInvoiceRecordDetailDto | null };
  issueForm: FinanceInvoiceIssueFormState;
  issueResult: { value: FinanceInvoiceIssueResultDto | null };
  issueTargetRecord: { value: FinanceInvoiceRecordListItemDto | null };
  reloadRecordList: () => Promise<void>;
  voidForm: FinanceInvoiceVoidFormState;
  voidTargetRecord: { value: FinanceInvoiceRecordListItemDto | null };
}

/** 创建抽屉与弹窗动作。 */
export function createDrawerActions(options: DrawerActionOptions) {
  async function loadDetail(recordId: string) {
    const result = await getFinanceInvoiceRecordDetailApi({ recordId });
    options.detail.value = result;
    return result;
  }

  function setDetailDrawerOpen(value: boolean) {
    options.isDetailDrawerOpen.value = value;
    if (!value) {
      options.detail.value = null;
    }
  }

  function setIssueDrawerOpen(value: boolean) {
    options.isIssueDrawerOpen.value = value;
    if (!value) {
      options.issueTargetRecord.value = null;
      options.issueDetail.value = null;
      options.issueForm.contactEmail = '';
      options.issueForm.issueRemark = '';
    }
  }

  function setVoidModalOpen(value: boolean) {
    options.isVoidModalOpen.value = value;
    if (!value) {
      options.voidTargetRecord.value = null;
      options.voidForm.voidReason = '';
    }
  }

  function setIssueResultModalOpen(value: boolean) {
    options.isIssueResultModalOpen.value = value;
    if (!value) {
      options.issueResult.value = null;
    }
  }

  async function openDetail(recordId: string) {
    if (!recordId) {
      return;
    }

    options.isDetailDrawerOpen.value = true;
    options.isDetailLoading.value = true;
    try {
      await loadDetail(recordId);
    } finally {
      options.isDetailLoading.value = false;
    }
  }

  async function openIssue(record: FinanceInvoiceRecordListItemDto) {
    if (!options.canIssue.value) {
      message.warning('当前账号暂无开票权限');
      return;
    }

    if (!isPendingInvoice(record.status)) {
      message.warning('仅待开票记录可执行开票');
      return;
    }

    options.issueTargetRecord.value = record;
    options.issueForm.contactEmail = '';
    options.issueForm.issueRemark = '';
    options.issueDetail.value = null;
    options.isIssueDrawerOpen.value = true;

    options.isIssueDetailLoading.value = true;
    try {
      const detail = await getFinanceInvoiceRecordDetailApi({
        recordId: record.recordId,
      });
      options.issueDetail.value = detail;
      options.issueForm.contactEmail = detail.contactEmail ?? '';
    } finally {
      options.isIssueDetailLoading.value = false;
    }
  }

  async function refreshOpenDetailAfterMutation(recordId: string) {
    if (!options.isDetailDrawerOpen.value) {
      return;
    }

    if (options.detail.value?.recordId !== recordId) {
      return;
    }

    options.isDetailLoading.value = true;
    try {
      await loadDetail(recordId);
    } finally {
      options.isDetailLoading.value = false;
    }
  }

  async function submitIssue() {
    if (!options.canIssue.value) {
      message.warning('当前账号暂无开票权限');
      return;
    }

    const target = options.issueTargetRecord.value;
    if (!target?.recordId) {
      message.warning('请选择待开票记录');
      return;
    }

    if (!isPendingInvoice(target.status)) {
      message.warning('当前记录状态不可开票');
      return;
    }

    const email = options.issueForm.contactEmail.trim();
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      message.warning('请填写正确的邮箱地址');
      return;
    }

    options.isIssueSubmitting.value = true;
    try {
      const result = await issueFinanceInvoiceRecordApi({
        recordId: target.recordId,
        contactEmail: toOptionalTrimmed(options.issueForm.contactEmail),
        issueRemark: toOptionalTrimmed(options.issueForm.issueRemark),
      });

      options.issueResult.value = result;
      options.isIssueDrawerOpen.value = false;
      options.isIssueResultModalOpen.value = true;
      message.success('发票开具成功');

      await options.reloadRecordList();
      await refreshOpenDetailAfterMutation(target.recordId);
    } finally {
      options.isIssueSubmitting.value = false;
    }
  }

  function openVoid(record: FinanceInvoiceRecordListItemDto) {
    if (!options.canVoid.value) {
      message.warning('当前账号暂无作废权限');
      return;
    }

    options.voidTargetRecord.value = record;
    options.voidForm.voidReason = '';
    options.isVoidModalOpen.value = true;
  }

  async function submitVoid() {
    if (!options.canVoid.value) {
      message.warning('当前账号暂无作废权限');
      return;
    }

    const target = options.voidTargetRecord.value;
    if (!target?.recordId) {
      message.warning('请选择需要作废的发票');
      return;
    }

    const reason = options.voidForm.voidReason.trim();
    if (!reason) {
      message.warning('请填写作废原因');
      return;
    }

    options.isVoidSubmitting.value = true;
    try {
      const detail = await voidFinanceInvoiceRecordApi({
        recordId: target.recordId,
        voidReason: reason,
      });

      message.success('发票已作废');
      options.isVoidModalOpen.value = false;
      options.voidTargetRecord.value = null;
      options.voidForm.voidReason = '';

      if (
        options.isDetailDrawerOpen.value &&
        options.detail.value?.recordId === detail.recordId
      ) {
        options.detail.value = detail;
      }

      await options.reloadRecordList();
    } finally {
      options.isVoidSubmitting.value = false;
    }
  }

  return {
    openDetail,
    openIssue,
    openVoid,
    setDetailDrawerOpen,
    setIssueDrawerOpen,
    setIssueResultModalOpen,
    setVoidModalOpen,
    submitIssue,
    submitVoid,
  };
}
