import { defineStore } from 'pinia';
import { dashboardAPI } from '../services/api.js';

export const useDashboardStore = defineStore('dashboard', {
  state: () => ({
    // 概览数据
    overview: {
      totalCattle: 0,
      totalFarms: 0,
      totalValue: 0,
      monthlyGrowth: 0,
      loading: false,
    },

    // 实时数据
    realtime: {
      activeTransactions: 0,
      onlineUsers: 0,
      systemStatus: 'normal',
      lastUpdate: null,
      loading: false,
    },

    // 地图数据
    mapData: {
      regions: [],
      selectedRegion: null,
      loading: false,
    },

    // 各模块统计数据
    statistics: {
      cattle: null,
      finance: null,
      trading: null,
      government: null,
      mall: null,
      loading: false,
    },

    // 错误状态
    error: null,
  }),

  getters: {
    // 获取总览卡片数据
    overviewCards: (state) => [
      {
        title: '总牛只数量',
        value: state.overview.totalCattle,
        unit: '头',
        icon: 'cattle',
        trend: 'up',
        change: '+12%',
      },
      {
        title: '注册牧场',
        value: state.overview.totalFarms,
        unit: '个',
        icon: 'farm',
        trend: 'up',
        change: '+8%',
      },
      {
        title: '总产值',
        value: state.overview.totalValue,
        unit: '万元',
        icon: 'money',
        trend: 'up',
        change: '+15%',
      },
      {
        title: '月增长率',
        value: state.overview.monthlyGrowth,
        unit: '%',
        icon: 'growth',
        trend: 'up',
        change: '+2.3%',
      },
    ],

    // 地图区域数据
    mapRegions: (state) => state.mapData.regions,

    // 选中的区域详情
    selectedRegionDetail: (state) => state.mapData.selectedRegion,

    // 系统状态指示器
    systemStatus: (state) => ({
      status: state.realtime.systemStatus,
      color: state.realtime.systemStatus === 'normal' ? 'green' : 
             state.realtime.systemStatus === 'warning' ? 'orange' : 'red',
      text: state.realtime.systemStatus === 'normal' ? '正常' :
            state.realtime.systemStatus === 'warning' ? '警告' : '异常',
    }),
  },

  actions: {
    // 加载概览数据
    async loadOverview() {
      this.overview.loading = true;
      try {
        const response = await dashboardAPI.getOverview();
        if (response.success) {
          this.overview = {
            ...this.overview,
            ...response.data,
            loading: false,
          };
        }
      } catch (error) {
        console.error('加载概览数据失败:', error);
        this.error = '加载概览数据失败';
      } finally {
        this.overview.loading = false;
      }
    },

    // 加载实时数据
    async loadRealtime() {
      this.realtime.loading = true;
      try {
        const response = await dashboardAPI.getRealtime();
        if (response.success) {
          this.realtime = {
            ...this.realtime,
            ...response.data,
            lastUpdate: new Date(),
            loading: false,
          };
        }
      } catch (error) {
        console.error('加载实时数据失败:', error);
        this.error = '加载实时数据失败';
      } finally {
        this.realtime.loading = false;
      }
    },

    // 加载地图数据
    async loadMapData() {
      this.mapData.loading = true;
      try {
        const response = await dashboardAPI.getMapRegions();
        if (response.regions) {
          this.mapData.regions = response.regions;
        }
      } catch (error) {
        console.error('加载地图数据失败:', error);
        this.error = '加载地图数据失败';
      } finally {
        this.mapData.loading = false;
      }
    },

    // 选择地图区域
    async selectRegion(regionId) {
      try {
        const response = await dashboardAPI.getRegionDetail(regionId);
        this.mapData.selectedRegion = response;
      } catch (error) {
        console.error('加载区域详情失败:', error);
        this.error = '加载区域详情失败';
      }
    },

    // 加载统计数据
    async loadStatistics() {
      this.statistics.loading = true;
      try {
        const [cattle, finance, trading, government, mall] = await Promise.all([
          dashboardAPI.getFarmData(),
          dashboardAPI.getFinanceData(),
          dashboardAPI.getTradingData(),
          dashboardAPI.getGovernmentData(),
          dashboardAPI.getMallData(),
        ]);

        this.statistics = {
          cattle: cattle.data,
          finance: finance.data,
          trading: trading.data,
          government: government.data,
          mall: mall.data,
          loading: false,
        };
      } catch (error) {
        console.error('加载统计数据失败:', error);
        this.error = '加载统计数据失败';
      } finally {
        this.statistics.loading = false;
      }
    },

    // 初始化大屏数据
    async initDashboard() {
      await Promise.all([
        this.loadOverview(),
        this.loadRealtime(),
        this.loadMapData(),
        this.loadStatistics(),
      ]);
    },

    // 定时刷新数据
    startAutoRefresh(interval = 30000) {
      // 每30秒刷新一次实时数据
      setInterval(() => {
        this.loadRealtime();
      }, interval);

      // 每5分钟刷新一次统计数据
      setInterval(() => {
        this.loadStatistics();
      }, interval * 10);
    },

    // 清除错误
    clearError() {
      this.error = null;
    },
  },
});