/**
 * 统计数据 store
 */
import { defineStore } from 'pinia';
import { pageUsers } from '@/api/system/user';
import { pageShopOrder, shopOrderTotal } from '@/api/shop/shopOrder';
import {
  addCmsStatistics,
  listCmsStatistics,
  updateCmsStatistics
} from '@/api/cms/cmsStatistics';
import { CmsStatistics } from '@/api/cms/cmsStatistics/model';
import { safeNumber, hasValidId } from '@/utils/type-guards';

export interface StatisticsState {
  // 统计数据
  statistics: CmsStatistics | null;
  // 加载状态
  loading: boolean;
  // 最后更新时间
  lastUpdateTime: number | null;
  // 缓存有效期（毫秒）- 统计数据缓存时间较短
  cacheExpiry: number;
  // 自动刷新定时器
  refreshTimer: number | null;
}

export const useStatisticsStore = defineStore({
  id: 'statistics',
  state: (): StatisticsState => ({
    statistics: null,
    loading: false,
    lastUpdateTime: null,
    // 默认缓存5分钟
    cacheExpiry: 5 * 60 * 1000,
    refreshTimer: null
  }),

  getters: {
    /**
     * 获取用户总数
     */
    userCount: (state): number => {
      return safeNumber(state.statistics?.userCount);
    },

    /**
     * 获取订单总数
     */
    orderCount: (state): number => {
      return safeNumber(state.statistics?.orderCount);
    },

    /**
     * 获取总销售额
     */
    totalSales: (state): number => {
      return safeNumber(state.statistics?.totalSales);
    },

    /**
     * 获取今日销售额
     */
    todaySales: (state): number => {
      return safeNumber(state.statistics?.todaySales);
    },

    /**
     * 获取本月销售额
     */
    monthSales: (state): number => {
      return safeNumber(state.statistics?.monthSales);
    },

    /**
     * 获取今日订单数
     */
    todayOrders: (state): number => {
      return safeNumber(state.statistics?.todayOrders);
    },

    /**
     * 获取今日新增用户
     */
    todayUsers: (state): number => {
      return safeNumber(state.statistics?.todayUsers);
    },

    /**
     * 检查缓存是否有效
     */
    isCacheValid: (state): boolean => {
      if (!state.lastUpdateTime) return false;
      const now = Date.now();
      return now - state.lastUpdateTime < state.cacheExpiry;
    }
  },

  actions: {
    /**
     * 获取统计数据
     * @param forceRefresh 是否强制刷新
     */
    async fetchStatistics(forceRefresh = false) {
      // 如果缓存有效且不强制刷新，直接返回缓存数据
      if (!forceRefresh && this.isCacheValid && this.statistics) {
        return this.statistics;
      }

      this.loading = true;
      try {
        // 并行获取各种统计数据，使用Promise.allSettled确保部分失败不影响整体
        const [usersResult, ordersResult, totalResult, statisticsResult] =
          await Promise.allSettled([
            pageUsers({}),
            pageShopOrder({}),
            shopOrderTotal(),
            listCmsStatistics({})
          ]);

        // 安全提取结果
        const users =
          usersResult.status === 'fulfilled' ? usersResult.value : null;
        const orders =
          ordersResult.status === 'fulfilled' ? ordersResult.value : null;
        const total =
          totalResult.status === 'fulfilled' ? totalResult.value : null;
        const statisticsData =
          statisticsResult.status === 'fulfilled'
            ? statisticsResult.value
            : null;

        // 记录失败的API调用
        if (usersResult.status === 'rejected') {
          console.error('❌ 用户API调用失败:', usersResult.reason);
        }
        if (ordersResult.status === 'rejected') {
          console.error('❌ 订单API调用失败:', ordersResult.reason);
        }
        if (totalResult.status === 'rejected') {
          console.error('❌ 订单总额API调用失败:', totalResult.reason);
        }
        if (statisticsResult.status === 'rejected') {
          console.error('❌ 统计数据API调用失败:', statisticsResult.reason);
        }

        // 添加调试日志
        console.log('🔍 统计数据获取结果:', {
          users: users,
          orders: orders,
          total: total,
          statisticsData: statisticsData
        });

        let statistics: CmsStatistics;

        // 安全获取用户数量，添加更详细的验证
        const userCount = (() => {
          if (!users) {
            console.warn('⚠️ 用户API返回空数据');
            return 0;
          }
          if (typeof users === 'object' && 'count' in users) {
            const count = users.count;
            console.log('✅ 用户数量:', count);
            return safeNumber(count);
          }
          console.warn('⚠️ 用户API返回数据格式不正确:', users);
          return 0;
        })();

        // 安全获取订单数量
        const orderCount = (() => {
          if (!orders) {
            console.warn('⚠️ 订单API返回空数据');
            return 0;
          }
          if (typeof orders === 'object' && 'count' in orders) {
            const count = orders.count;
            console.log('✅ 订单数量:', count);
            return safeNumber(count);
          }
          console.warn('⚠️ 订单API返回数据格式不正确:', orders);
          return 0;
        })();

        // 安全获取总销售额，处理数组情况
        const totalSales = (() => {
          if (!total) {
            console.warn('⚠️ 订单总额API返回空数据');
            return 0;
          }
          if (Array.isArray(total)) {
            // 如果是数组，计算总金额
            const sum = total.reduce((acc, order) => {
              const amount = order.payPrice || order.totalPrice || 0;
              return acc + safeNumber(amount);
            }, 0);
            console.log('✅ 总销售额(数组计算):', sum);
            return sum;
          }
          const amount = safeNumber(total);
          console.log('✅ 总销售额(直接值):', amount);
          return amount;
        })();

        if (statisticsData && statisticsData.length > 0) {
          // 更新现有统计数据
          const existingStatistics = statisticsData[0];

          // 确保数据存在且有有效的 ID
          if (hasValidId(existingStatistics)) {
            const updateData: Partial<CmsStatistics> = {
              id: existingStatistics.id,
              userCount: userCount,
              orderCount: orderCount,
              totalSales: totalSales
            };

            // 异步更新数据库
            setTimeout(() => {
              updateCmsStatistics(updateData).catch((error) => {
                console.error('更新统计数据失败:', error);
              });
            }, 1000);

            // 更新本地数据
            statistics = { ...existingStatistics, ...updateData };
          } else {
            // 如果现有数据无效，使用基础数据
            statistics = {
              userCount: userCount,
              orderCount: orderCount,
              totalSales: totalSales
            };
          }
        } else {
          // 创建新的统计数据
          statistics = {
            userCount: userCount,
            orderCount: orderCount,
            totalSales: totalSales
          };

          // 异步保存到数据库
          setTimeout(() => {
            addCmsStatistics(statistics).catch((error) => {
              console.error('保存统计数据失败:', error);
            });
          }, 1000);
        }

        this.statistics = statistics;
        this.lastUpdateTime = Date.now();

        return statistics;
      } catch (error) {
        console.error('获取统计数据失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 更新统计数据
     */
    updateStatistics(statistics: Partial<CmsStatistics>) {
      if (this.statistics) {
        this.statistics = { ...this.statistics, ...statistics };
        this.lastUpdateTime = Date.now();
      }
    },

    /**
     * 清除缓存
     */
    clearCache() {
      this.statistics = null;
      this.lastUpdateTime = null;
    },

    /**
     * 强制刷新统计数据
     */
    async forceRefresh() {
      console.log('🔄 强制刷新统计数据...');
      this.clearCache();
      return await this.fetchStatistics(true);
    },

    /**
     * 设置缓存有效期
     */
    setCacheExpiry(expiry: number) {
      this.cacheExpiry = expiry;
    },

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

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