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

import type {
  MemberDaySettingDto,
  MemberTierListItemDto,
  SaveMemberTierPayload,
} from '#/api/member';

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

import {
  deleteMemberTierApi,
  getMemberTierDetailApi,
  saveMemberDaySettingApi,
  saveMemberTierApi,
} from '#/api/member';

import { buildTierSavePayload, createTierEditorForm } from './helpers';

interface TierActionOptions {
  canManage: { value: boolean };
  daySetting: { value: MemberDaySettingDto | null };
  daySettingSaving: { value: boolean };
  loadTierData: () => Promise<void>;
  tierEditorLoading: { value: boolean };
  tierEditorOpen: { value: boolean };
  tierEditorSubmitting: { value: boolean };
  tierForm: { value: MemberTierEditorForm | null };
  tiers: { value: MemberTierListItemDto[] };
}

/**
 * 文件职责：等级体系与会员日动作。
 */
export function createTierActions(options: TierActionOptions) {
  function setTierEditorOpen(value: boolean) {
    options.tierEditorOpen.value = value;
    if (!value) {
      options.tierForm.value = null;
    }
  }

  async function openCreateTier() {
    if (!options.canManage.value) {
      message.warning('暂无编辑权限');
      return;
    }

    options.tierEditorOpen.value = true;
    options.tierEditorLoading.value = true;
    options.tierForm.value = null;
    try {
      const detail = await getMemberTierDetailApi({});
      options.tierForm.value = createTierEditorForm(detail);
    } finally {
      options.tierEditorLoading.value = false;
    }
  }

  async function openEditTier(tierId: string) {
    if (!options.canManage.value) {
      message.warning('暂无编辑权限');
      return;
    }

    options.tierEditorOpen.value = true;
    options.tierEditorLoading.value = true;
    options.tierForm.value = null;
    try {
      const detail = await getMemberTierDetailApi({ tierId });
      options.tierForm.value = createTierEditorForm(detail);
    } finally {
      options.tierEditorLoading.value = false;
    }
  }

  async function submitTier(form: MemberTierEditorForm) {
    if (!options.canManage.value) {
      message.warning('暂无编辑权限');
      return;
    }

    const payload: SaveMemberTierPayload = buildTierSavePayload(form);
    options.tierEditorSubmitting.value = true;
    try {
      await saveMemberTierApi(payload);
      message.success('等级保存成功');
      options.tierEditorOpen.value = false;
      options.tierForm.value = null;
      await options.loadTierData();
    } finally {
      options.tierEditorSubmitting.value = false;
    }
  }

  async function deleteTier(tierId: string) {
    if (!options.canManage.value) {
      message.warning('暂无编辑权限');
      return;
    }

    const row = options.tiers.value.find((item) => item.tierId === tierId);
    if (!row || !row.canDelete) {
      message.warning('该等级暂不允许删除');
      return;
    }

    await new Promise<void>((resolve, reject) => {
      Modal.confirm({
        title: '确认删除该等级吗？',
        content: '删除后无法恢复，请确认当前等级下没有会员。',
        okText: '确认删除',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          try {
            await deleteMemberTierApi({ tierId });
            message.success('等级已删除');
            await options.loadTierData();
            resolve();
          } catch (error) {
            reject(error);
          }
        },
        onCancel: () => resolve(),
      });
    });
  }

  async function saveDaySetting(payload: MemberDaySettingDto) {
    if (!options.canManage.value) {
      message.warning('暂无编辑权限');
      return;
    }

    options.daySettingSaving.value = true;
    try {
      options.daySetting.value = await saveMemberDaySettingApi(payload);
      message.success('会员日配置已保存');
    } finally {
      options.daySettingSaving.value = false;
    }
  }

  return {
    deleteTier,
    openCreateTier,
    openEditTier,
    saveDaySetting,
    setTierEditorOpen,
    submitTier,
  };
}
