import type { StoreListItemDto } from '#/api/store';
import type {
  StoredCardPlanCardViewModel,
  StoredCardTabKey,
} from '#/views/member/stored-card/types';

import { computed, onMounted, reactive, ref, watch } from 'vue';

import { useAccessStore } from '@vben/stores';

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

import { exportMemberStoredCardRechargeRecordApi } from '#/api/member/stored-card';

import {
  createDefaultStoredCardPlanEditorForm,
  createDefaultStoredCardPlanStats,
  createDefaultStoredCardRecordFilterForm,
  createDefaultStoredCardRecordPager,
} from '../types';
import {
  createDefaultRecordDateRange,
  MEMBER_STORED_CARD_MANAGE_PERMISSION,
  MEMBER_STORED_CARD_VIEW_PERMISSION,
  STORED_CARD_TAB_OPTIONS,
} from './stored-card-page/constants';
import { createDataActions } from './stored-card-page/data-actions';
import { createDrawerActions } from './stored-card-page/drawer-actions';
import {
  downloadBase64File,
  mapRecordFilterToQuery,
} from './stored-card-page/helpers';
import { createPlanActions } from './stored-card-page/plan-actions';

export function useMemberStoredCardPage() {
  const accessStore = useAccessStore();

  const stores = ref<StoreListItemDto[]>([]);
  const selectedStoreId = ref('');
  const isStoreLoading = ref(false);

  const activeTab = ref<StoredCardTabKey>('plans');

  const planRows = ref<StoredCardPlanCardViewModel[]>([]);
  const planStats = ref(createDefaultStoredCardPlanStats());
  const isPlanLoading = ref(false);

  const recordFilterForm = reactive(createDefaultStoredCardRecordFilterForm());
  recordFilterForm.dateRange = createDefaultRecordDateRange();
  const recordPager = ref(createDefaultStoredCardRecordPager());
  const isRecordLoading = ref(false);
  const isExporting = ref(false);

  const drawerMode = ref<'create' | 'edit'>('create');
  const form = reactive(createDefaultStoredCardPlanEditorForm());
  const isDrawerOpen = ref(false);
  const isDrawerLoading = ref(false);
  const isDrawerSubmitting = ref(false);

  const accessCodeSet = computed(
    () => new Set((accessStore.accessCodes ?? []).map(String)),
  );
  const canManage = computed(() =>
    accessCodeSet.value.has(MEMBER_STORED_CARD_MANAGE_PERMISSION),
  );
  const canView = computed(
    () =>
      canManage.value ||
      accessCodeSet.value.has(MEMBER_STORED_CARD_VIEW_PERMISSION),
  );

  const hasStore = computed(() => stores.value.length > 0);

  const storeOptions = computed(() =>
    stores.value.map((item) => ({
      label: item.name,
      value: item.id,
    })),
  );

  const drawerTitle = computed(() =>
    drawerMode.value === 'create' ? '添加充值方案' : '编辑充值方案',
  );

  const drawerSubmitText = computed(() => '保存');

  const { loadPlanList, loadRecordList, loadStores } = createDataActions({
    stores,
    selectedStoreId,
    isStoreLoading,
    isPlanLoading,
    planRows,
    planStats,
    isRecordLoading,
    recordFilterForm,
    recordPager,
  });

  const {
    openCreateDrawer,
    openEditDrawer,
    setDrawerOpen,
    setFormGiftAmount,
    setFormRechargeAmount,
    setFormSortOrder,
    setFormStatus,
    submitDrawer,
  } = createDrawerActions({
    canManage,
    drawerMode,
    form,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    selectedStoreId,
    loadPlanList,
    loadRecordList,
  });

  const { removePlan, toggleStatus } = createPlanActions({
    canManage,
    selectedStoreId,
    loadPlanList,
    loadRecordList,
  });

  function setSelectedStoreId(value: string) {
    selectedStoreId.value = value;
  }

  function setActiveTab(value: StoredCardTabKey) {
    activeTab.value = value;
  }

  function setRecordKeyword(value: string) {
    recordFilterForm.keyword = value;
  }

  function setRecordDateRange(value: [any, any] | null) {
    if (!value) {
      recordFilterForm.dateRange = null;
      return;
    }

    if (value.length === 2) {
      recordFilterForm.dateRange = value;
    }
  }

  async function applyRecordFilters() {
    recordPager.value = {
      ...recordPager.value,
      page: 1,
    };
    await loadRecordList();
  }

  async function resetRecordFilters() {
    recordFilterForm.keyword = '';
    recordFilterForm.dateRange = createDefaultRecordDateRange();
    recordPager.value = {
      ...recordPager.value,
      page: 1,
    };
    await loadRecordList();
  }

  async function handleRecordPageChange(page: number, pageSize: number) {
    recordPager.value = {
      ...recordPager.value,
      page,
      pageSize,
    };
    await loadRecordList();
  }

  async function exportRecords() {
    if (!selectedStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    isExporting.value = true;
    try {
      const query = mapRecordFilterToQuery(recordFilterForm);
      const result = await exportMemberStoredCardRechargeRecordApi({
        storeId: selectedStoreId.value,
        ...query,
      });
      downloadBase64File(result.fileName, result.fileContentBase64);
      message.success(`导出成功，共 ${result.totalCount} 条`);
    } catch (error) {
      console.error(error);
      message.error('导出失败');
    } finally {
      isExporting.value = false;
    }
  }

  watch(selectedStoreId, async () => {
    recordPager.value = {
      ...recordPager.value,
      page: 1,
      pageSize: 8,
    };
    await Promise.all([loadPlanList(), loadRecordList()]);
  });

  onMounted(async () => {
    await loadStores();
    if (selectedStoreId.value) {
      await Promise.all([loadPlanList(), loadRecordList()]);
    }
  });

  return {
    activeTab,
    applyRecordFilters,
    canManage,
    canView,
    drawerMode,
    drawerSubmitText,
    drawerTitle,
    exportRecords,
    form,
    handleRecordPageChange,
    hasStore,
    isDrawerLoading,
    isDrawerOpen,
    isDrawerSubmitting,
    isExporting,
    isPlanLoading,
    isRecordLoading,
    isStoreLoading,
    openCreateDrawer,
    openEditDrawer,
    planRows,
    planStats,
    recordFilterForm,
    recordPager,
    removePlan,
    resetRecordFilters,
    selectedStoreId,
    setActiveTab,
    setDrawerOpen,
    setFormGiftAmount,
    setFormRechargeAmount,
    setFormSortOrder,
    setFormStatus,
    setRecordDateRange,
    setRecordKeyword,
    setSelectedStoreId,
    storeOptions,
    submitDrawer,
    tabOptions: STORED_CARD_TAB_OPTIONS,
    toggleStatus,
  };
}
