import type {
  FinanceInvoiceRecordListQuery,
  FinanceInvoiceSettingDto,
  FinanceInvoiceStatusFilter,
  FinanceInvoiceTypeFilter,
} from '#/api/finance';
import type {
  FinanceInvoiceFilterState,
  FinanceInvoicePaginationState,
  FinanceInvoiceSettingFormState,
} from '../../types';

/**
 * 文件职责：发票管理页面纯函数工具。
 */

function formatDate(date: Date) {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, '0');
  const day = `${date.getDate()}`.padStart(2, '0');
  return `${year}-${month}-${day}`;
}

function normalizeStatus(
  status: FinanceInvoiceStatusFilter,
): Exclude<FinanceInvoiceStatusFilter, 'all'> | undefined {
  return status === 'all' ? undefined : status;
}

function normalizeInvoiceType(
  invoiceType: FinanceInvoiceTypeFilter,
): Exclude<FinanceInvoiceTypeFilter, 'all'> | undefined {
  return invoiceType === 'all' ? undefined : invoiceType;
}

/** 获取今天日期字符串（yyyy-MM-dd）。 */
export function getTodayDateString() {
  return formatDate(new Date());
}

/** 获取当月第一天日期字符串（yyyy-MM-dd）。 */
export function getMonthFirstDateString() {
  const now = new Date();
  return formatDate(new Date(now.getFullYear(), now.getMonth(), 1));
}

/** 构建发票记录列表查询参数。 */
export function buildInvoiceListQuery(
  filters: FinanceInvoiceFilterState,
  pagination: FinanceInvoicePaginationState,
): FinanceInvoiceRecordListQuery {
  return {
    page: pagination.page,
    pageSize: pagination.pageSize,
    startDate: filters.startDate || undefined,
    endDate: filters.endDate || undefined,
    status: normalizeStatus(filters.status),
    invoiceType: normalizeInvoiceType(filters.invoiceType),
    keyword: filters.keyword.trim() || undefined,
  };
}

/** 判断日期范围是否合法。 */
export function isDateRangeInvalid(filters: FinanceInvoiceFilterState) {
  if (!filters.startDate || !filters.endDate) {
    return false;
  }
  return filters.startDate > filters.endDate;
}

/** 货币格式化（人民币）。 */
export function formatCurrency(value: number) {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(Number.isFinite(value) ? value : 0);
}

/** 发票类型标签颜色。 */
export function resolveInvoiceTypeTagColor(type: string) {
  if (type === 'normal') return 'blue';
  if (type === 'special') return 'purple';
  return 'default';
}

/** 发票状态标签颜色。 */
export function resolveInvoiceStatusTagColor(status: string) {
  if (status === 'pending') return 'orange';
  if (status === 'issued') return 'green';
  if (status === 'voided') return 'default';
  return 'default';
}

/** 是否为待开票状态。 */
export function isPendingInvoice(status: string) {
  return status === 'pending';
}

/** 是否为已开票状态。 */
export function isIssuedInvoice(status: string) {
  return status === 'issued';
}

/** 应用设置 DTO 到表单。 */
export function applySettingDtoToForm(
  target: FinanceInvoiceSettingFormState,
  source: FinanceInvoiceSettingDto,
) {
  target.companyName = source.companyName || '';
  target.taxpayerNumber = source.taxpayerNumber || '';
  target.registeredAddress = source.registeredAddress || '';
  target.registeredPhone = source.registeredPhone || '';
  target.bankName = source.bankName || '';
  target.bankAccount = source.bankAccount || '';
  target.enableElectronicNormalInvoice = Boolean(
    source.enableElectronicNormalInvoice,
  );
  target.enableElectronicSpecialInvoice = Boolean(
    source.enableElectronicSpecialInvoice,
  );
  target.enableAutoIssue = Boolean(source.enableAutoIssue);
  target.autoIssueMaxAmount = Number(source.autoIssueMaxAmount || 0);
}

/** 深拷贝设置表单快照。 */
export function cloneSettingsForm(
  source: FinanceInvoiceSettingFormState,
): FinanceInvoiceSettingFormState {
  return {
    companyName: source.companyName,
    taxpayerNumber: source.taxpayerNumber,
    registeredAddress: source.registeredAddress,
    registeredPhone: source.registeredPhone,
    bankName: source.bankName,
    bankAccount: source.bankAccount,
    enableElectronicNormalInvoice: source.enableElectronicNormalInvoice,
    enableElectronicSpecialInvoice: source.enableElectronicSpecialInvoice,
    enableAutoIssue: source.enableAutoIssue,
    autoIssueMaxAmount: source.autoIssueMaxAmount,
  };
}

/** 比较设置表单是否发生变化。 */
export function isSettingsChanged(
  current: FinanceInvoiceSettingFormState,
  snapshot: FinanceInvoiceSettingFormState,
) {
  return JSON.stringify(current) !== JSON.stringify(snapshot);
}

/** 生成保存设置请求体。 */
export function buildSettingSavePayload(form: FinanceInvoiceSettingFormState) {
  return {
    companyName: form.companyName.trim(),
    taxpayerNumber: form.taxpayerNumber.trim(),
    registeredAddress: form.registeredAddress.trim() || undefined,
    registeredPhone: form.registeredPhone.trim() || undefined,
    bankName: form.bankName.trim() || undefined,
    bankAccount: form.bankAccount.trim() || undefined,
    enableElectronicNormalInvoice: form.enableElectronicNormalInvoice,
    enableElectronicSpecialInvoice: form.enableElectronicSpecialInvoice,
    enableAutoIssue: form.enableAutoIssue,
    autoIssueMaxAmount: Number(form.autoIssueMaxAmount || 0),
  };
}

/** 文本转空值。 */
export function toOptionalTrimmed(value: string) {
  const normalized = value.trim();
  return normalized ? normalized : undefined;
}
