/**
 * 财务看板 Store
 */
import { defineStore } from 'pinia';
import {
  getFinanceDashboardSummary,
  getCommissionDetail,
  getProfitShareDetail,
  getFinanceTrendData,
  getTodayFinanceData,
  getYesterdayFinanceData
} from '@/api/finance/dashboard';
import type {
  FinanceDashboardData,
  FinanceDashboardParam,
  CommissionItem,
  ProfitShareItem,
  FinanceTrendData
} from '@/api/finance/dashboard/model';

export type TimeTabType = 'today' | 'yesterday' | 'custom';

export interface FinanceDashboardState {
  // 当前选中的时间维度
  activeTab: TimeTabType;
  // 自定义日期
  customDate: string | null;
  // 财务数据
  dashboardData: FinanceDashboardData | null;
  // 佣金明细列表
  commissionList: CommissionItem[];
  // 分润明细列表
  profitShareList: ProfitShareItem[];
  // 趋势数据
  trendData: FinanceTrendData | null;
  // 加载状态
  loading: boolean;
  // 明细加载状态
  detailLoading: boolean;
  // 趋势加载状态
  trendLoading: boolean;
  // 最后更新时间
  lastUpdateTime: number | null;
  // 自动刷新定时器
  refreshTimer: number | null;
}

export const useFinanceDashboardStore = defineStore('financeDashboard', {
  state: (): FinanceDashboardState => ({
    activeTab: 'today',
    customDate: null,
    dashboardData: null,
    commissionList: [],
    profitShareList: [],
    trendData: null,
    loading: false,
    detailLoading: false,
    trendLoading: false,
    lastUpdateTime: null,
    refreshTimer: null
  }),

  getters: {
    /**
     * 获取产生佣金
     */
    commissionAmount: (state): number => {
      return state.dashboardData?.commissionAmount || 0;
    },

    /**
     * 获取分润金额
     */
    profitShareAmount: (state): number => {
      return state.dashboardData?.profitShareAmount || 0;
    },

    /**
     * 获取佣金趋势
     */
    commissionTrend: (state): number => {
      return state.dashboardData?.commissionTrend || 0;
    },

    /**
     * 获取分润趋势
     */
    profitShareTrend: (state): number => {
      return state.dashboardData?.profitShareTrend || 0;
    },

    /**
     * 获取订单数量
     */
    orderCount: (state): number => {
      return state.dashboardData?.orderCount || 0;
    },

    /**
     * 获取交易用户数
     */
    userCount: (state): number => {
      return state.dashboardData?.userCount || 0;
    },

    /**
     * 获取对比文本
     */
    compareText: (state): string => {
      switch (state.activeTab) {
        case 'today':
          return '昨日';
        case 'yesterday':
          return '前日';
        case 'custom':
          return '上期';
        default:
          return '上期';
      }
    },

    /**
     * 获取当前日期文本
     */
    currentDateText: (state): string => {
      const today = new Date().toISOString().split('T')[0];
      switch (state.activeTab) {
        case 'today':
          return '今日';
        case 'yesterday':
          return '昨日';
        case 'custom':
          return state.customDate || today;
        default:
          return '今日';
      }
    },

    /**
     * 获取查询日期
     */
    queryDate: (state): string => {
      const today = new Date().toISOString().split('T')[0];
      switch (state.activeTab) {
        case 'today':
          return today;
        case 'yesterday':
          return new Date(Date.now() - 86400000).toISOString().split('T')[0];
        case 'custom':
          return state.customDate || today;
        default:
          return today;
      }
    }
  },

  actions: {
    /**
     * 获取财务看板数据
     */
    async fetchDashboardData() {
      this.loading = true;
      try {
        let data: FinanceDashboardData;

        switch (this.activeTab) {
          case 'today':
            data = await getTodayFinanceData();
            break;
          case 'yesterday':
            data = await getYesterdayFinanceData();
            break;
          case 'custom':
          default:
            const params: FinanceDashboardParam = {
              date: this.queryDate,
              type: this.activeTab
            };
            data = await getFinanceDashboardSummary(params);
            break;
        }

        this.dashboardData = data;
        this.lastUpdateTime = Date.now();
        return data;
      } catch (error) {
        console.error('获取财务看板数据失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 获取佣金明细
     */
    async fetchCommissionDetail(page = 1, limit = 10) {
      this.detailLoading = true;
      try {
        const params: FinanceDashboardParam = {
          date: this.queryDate,
          type: this.activeTab,
          page,
          limit
        };
        const result = await getCommissionDetail(params);
        this.commissionList = result.list || [];
        return result;
      } catch (error) {
        console.error('获取佣金明细失败:', error);
        throw error;
      } finally {
        this.detailLoading = false;
      }
    },

    /**
     * 获取分润明细
     */
    async fetchProfitShareDetail(page = 1, limit = 10) {
      this.detailLoading = true;
      try {
        const params: FinanceDashboardParam = {
          date: this.queryDate,
          type: this.activeTab,
          page,
          limit
        };
        const result = await getProfitShareDetail(params);
        this.profitShareList = result.list || [];
        return result;
      } catch (error) {
        console.error('获取分润明细失败:', error);
        throw error;
      } finally {
        this.detailLoading = false;
      }
    },

    /**
     * 获取趋势数据
     */
    async fetchTrendData(days = 7) {
      this.trendLoading = true;
      try {
        const endDate = this.queryDate;
        const startDate = new Date(Date.now() - days * 86400000)
          .toISOString()
          .split('T')[0];

        const params: FinanceDashboardParam = {
          startDate,
          endDate,
          type: this.activeTab
        };
        const data = await getFinanceTrendData(params);
        this.trendData = data;
        return data;
      } catch (error) {
        console.error('获取趋势数据失败:', error);
        throw error;
      } finally {
        this.trendLoading = false;
      }
    },

    /**
     * 切换时间维度
     */
    async switchTab(tab: TimeTabType) {
      this.activeTab = tab;
      await this.fetchDashboardData();
    },

    /**
     * 设置自定义日期
     */
    async setCustomDate(date: string) {
      this.customDate = date;
      this.activeTab = 'custom';
      await this.fetchDashboardData();
    },

    /**
     * 刷新所有数据
     */
    async refreshAllData() {
      await Promise.all([
        this.fetchDashboardData(),
        this.fetchTrendData()
      ]);
    },

    /**
     * 开始自动刷新
     * @param interval 刷新间隔（毫秒），默认5分钟
     */
    startAutoRefresh(interval = 5 * 60 * 1000) {
      this.stopAutoRefresh();
      this.refreshTimer = window.setInterval(() => {
        this.fetchDashboardData().catch(console.error);
      }, interval);
    },

    /**
     * 停止自动刷新
     */
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    },

    /**
     * 重置状态
     */
    reset() {
      this.activeTab = 'today';
      this.customDate = null;
      this.dashboardData = null;
      this.commissionList = [];
      this.profitShareList = [];
      this.trendData = null;
      this.lastUpdateTime = null;
      this.stopAutoRefresh();
    }
  }
});
