<template>
  <div class="app-container" v-loading="loading">
    <!-- 统计卡片行 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="4" v-for="(stat, index) in statisticsData" :key="index">
        <div class="stat-card" :style="{ '--bg-color': stat.bgColor }">
          <div class="stat-header">
            <i :class="stat.icon" :style="{ color: stat.chartColor }"></i>
            <span class="stat-title">{{ stat.label }}</span>
            <el-tooltip v-if="stat.tip" :content="stat.tip" placement="top">
              <i class="el-icon-question"></i>
            </el-tooltip>
          </div>
          <div class="stat-body">
            <div class="stat-value">
              <template v-if="stat.isMoney">¥ {{ formatNumber(mockDetail[stat.field]) }}</template>
              <template v-else>{{ mockDetail[stat.field] || '0' }}{{ stat.suffix }}</template>
            </div>
            <div class="stat-trend" v-if="stat.today !== undefined">
              今日 
              <span :class="['trend-value', stat.today > 0 ? 'up' : 'down']">
                <template v-if="stat.isMoney">¥ {{ formatNumber(Math.abs(stat.today)) }}</template>
                <template v-else>{{ Math.abs(stat.today) }}</template>
                <i :class="stat.today > 0 ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"></i>
              </span>
            </div>
          </div>
          <div class="stat-chart" v-if="stat.chartData">
            <mini-line 
              :data="stat.chartData" 
              :color="stat.chartColor"
              :title="stat.label"
              :prefix="stat.isMoney ? '¥ ' : ''"
              :suffix="stat.suffix || ''"
              :tooltip-formatter="(data) => formatTooltip(data, stat)"
            />
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 第二行：待办事项和图表 -->
    <el-row :gutter="20" class="dashboard-content">
      <!-- 待办事项 -->
      <el-col :span="6">
        <el-card class="todo-card" shadow="never">
          <div slot="header">
            <span>待办事项</span>
          </div>
          <div class="todo-list">
            <div v-for="(item, index) in todoItems" :key="index" class="todo-item">
              <div class="item-left">
                <i :class="item.icon" :style="{color: item.color}"></i>
                <span>{{ item.title }}</span>
              </div>
              <div class="item-right">
                <span :style="{color: item.count > 0 ? '#409EFF' : '#909399'}">{{ item.count }}</span>
                <span>条</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 支付对账 -->
      <el-col :span="9">
        <el-card class="chart-card" shadow="never">
          <div slot="header">
            <span>支付对账</span>
            <el-date-picker
              v-model="paymentDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              :picker-options="pickerOptions"
            />
          </div>
          <div class="chart-container">
            <line-chart :data="paymentChartData" height="300px" />
          </div>
        </el-card>
      </el-col>

      <!-- 收入及成本 -->
      <el-col :span="9">
        <el-card class="chart-card" shadow="never">
          <div slot="header">
            <span>收入及成本</span>
            <el-date-picker
              v-model="incomeDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              size="small"
              :picker-options="pickerOptions"
            />
          </div>
          <div class="chart-container">
            <line-chart :data="incomeChartData" height="300px" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行：每日充值提现 -->
    <el-row :gutter="20" class="dashboard-content">
      <el-col :span="24">
        <el-card class="chart-card" shadow="never">
          <div slot="header">
            <span>每日充值提现</span>
            <el-date-picker
              v-model="dailyTransactionDate"
              type="date"
              placeholder="选择日期"
              size="small"
              :picker-options="pickerOptions"
            />
          </div>
          <div class="chart-container">
            <line-chart 
              :data="dailyTransactionData" 
              height="300px"
              :y-axis-interval="100"
              :show-hours="true"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第四行：店铺地图分布 -->
    <el-row :gutter="20" class="dashboard-content">
      <el-col :span="24">
        <el-card class="map-card" shadow="never">
          <div slot="header">
            <span>店铺分布</span>
          </div>
          <div class="map-container" id="storeMap"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import MiniLine from '@/components/Charts/MiniLine'
import LineChart from '@/components/Charts/LineChart'
import AMapLoader from "@amap/amap-jsapi-loader"
import globalConfig from '@/utils/config/globalConfig'

export default {
  name: 'Dashboard',
  components: {
    MiniLine,
    LineChart
  },
  data() {
    return {
      loading: false,
      map: null,
      markers: [],
      mockDetail: {
        deviceCount: 2576,
        orderCount: 52829,
        balance: 15680.50,
        totalIncome: 807357.19,
        userDeviceCount: 1360,
        merchantBalance: 57721.81
      },
      // 统计卡片数据
      statisticsData: [
        {
          label: '设备总数',
          field: 'deviceCount',
          icon: 'el-icon-monitor',
          chartColor: '#409EFF',
          bgColor: '#ECF5FF',
          today: 96,
          chartData: [2200, 2300, 2400, 2500, 2576]
        },
        {
          label: '订单总数',
          field: 'orderCount',
          today: 96,
          chartData: [51220, 51382, 51591, 51834, 52290, 52733, 52829],
          chartColor: '#67C23A',
          tip: '系统中的所有订单数量',
          icon: 'el-icon-s-order',
          bgColor: 'rgba(103, 194, 58, 0.1)',
          suffix: ' 单'
        },
        {
          label: '账户余额',
          field: 'balance',
          isMoney: true,
          today: 1471.60,
          chartData: [15150, 15232, 15401, 15454, 15590, 15630, 15680.50],
          chartColor: '#E6A23C',
          icon: 'el-icon-wallet',
          bgColor: 'rgba(230, 162, 60, 0.1)'
        },
        {
          label: '订单金额',
          field: 'totalIncome',
          isMoney: true,
          today: 1471.60,
          chartData: [801320, 802332, 803301, 804334, 805390, 805885.59, 807357.19],
          chartColor: '#F56C6C',
          icon: 'el-icon-money',
          bgColor: 'rgba(245, 108, 108, 0.1)'
        },
        {
          label: '用户设备数',
          field: 'userDeviceCount',
          today: 15,
          chartData: [1220, 1282, 1291, 1334, 1345, 1345, 1360],
          chartColor: '#909399',
          tip: '用户持有的设备总数',
          icon: 'el-icon-mobile',
          bgColor: 'rgba(144, 147, 153, 0.1)',
          suffix: ' 台'
        },
        {
          label: '商户余额',
          field: 'merchantBalance',
          isMoney: true,
          today: 366.51,
          chartData: [55150, 55232, 56201, 56454, 56990, 57355.30, 57721.81],
          chartColor: '#9B59B6',
          tip: '商户账户当前余额',
          icon: 'el-icon-bank-card',
          bgColor: 'rgba(155, 89, 182, 0.1)'
        }
      ],
      // 待办事项数据
      todoItems: [
        {
          icon: 'el-icon-s-shop',
          title: '商家加盟',
          count: 0,
          color: '#409EFF'
        },
        {
          icon: 'el-icon-money',
          title: '提现申请',
          count: 0,
          color: '#67C23A'
        },
        {
          icon: 'el-icon-warning',
          title: '风控审核',
          count: 0,
          color: '#E6A23C'
        },
        {
          icon: 'el-icon-monitor',
          title: '到期设备',
          count: 2576,
          color: '#F56C6C'
        },
        {
          icon: 'el-icon-s-shop',
          title: '店铺审核',
          count: 2,
          color: '#909399'
        },
        {
          icon: 'el-icon-warning-outline',
          title: '待处理故障信息',
          count: 37,
          color: '#F56C6C'
        }
      ],
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 支付对账数据
      paymentDateRange: [new Date('2025-01-04'), new Date('2025-01-10')],
      paymentChartData: {
        labels: ['01-04', '01-05', '01-06', '01-07', '01-08', '01-09', '01-10'],
        datasets: [
          {
            label: '支付金额',
            data: [10000, 9500, 8000, 7500, 9000, 8500, 2000],
            color: '#409EFF'
          },
          {
            label: '退款金额',
            data: [2000, 1500, 2000, 1000, 1200, 1000, 800],
            color: '#67C23A'
          },
          {
            label: '实收金额',
            data: [8000, 8000, 6000, 6500, 7800, 7500, 1200],
            color: '#E6A23C'
          }
        ]
      },
      // 收入及成本数据
      incomeDateRange: [new Date('2025-01-04'), new Date('2025-01-10')],
      incomeChartData: {
        labels: ['01-04', '01-05', '01-06', '01-07', '01-08', '01-09', '01-10'],
        datasets: [
          {
            label: '订单服务费收入',
            data: [100, 95, 85, 75, 90, 85, 20],
            color: '#409EFF'
          },
          {
            label: '提现服务费收入',
            data: [40, 45, 40, 35, 20, 15, 10],
            color: '#67C23A'
          },
          {
            label: '月租收入',
            data: [20, 18, 16, 14, 12, 10, 8],
            color: '#E6A23C'
          },
          {
            label: '订单手机号收入',
            data: [10, 8, 6, 4, 2, 0, 0],
            color: '#F56C6C'
          },
          {
            label: '运营成本',
            data: [25, 20, 15, 18, 20, 22, 15],
            color: '#909399'
          }
        ]
      },
      // 每日充值提现数据
      dailyTransactionDate: new Date('2025-01-10'),
      dailyTransactionData: {
        labels: ['0:00', '2:00', '4:00', '6:00', '8:00', '10:00', '12:00', 
                '14:00', '16:00', '18:00', '20:00', '22:00'],
        datasets: [
          {
            label: '充值 (元)',
            data: [250, 420, 450, 450, 450, 480, 30, 0, 0, 0, 0, 0],
            color: '#409EFF'
          },
          {
            label: '提现 (元)',
            data: [220, 0, 0, 0, 0, 180, 0, 0, 0, 0, 0, 0],
            color: '#67C23A'
          }
        ]
      },
      // 店铺位置数据
      storeLocations: [
        { id: 1, name: '测试店铺1', address: '北京市朝阳区', lng: 116.481488, lat: 39.990464, status: 1 },
        { id: 2, name: '测试店铺2', address: '北京市海淀区', lng: 116.310316, lat: 39.991228, status: 1 },
        { id: 3, name: '测试店铺3', address: '北京市西城区', lng: 116.366794, lat: 39.915309, status: 2 }
      ]
    }
  },
  mounted() {
    this.initMap()
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
    }
  },
  methods: {
    formatNumber(num) {
      return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
    },
    formatTooltip(data, stat) {
      const date = new Date()
      const day = date.getDate() - (6 - data.dataIndex)
      const month = date.getMonth() + 1
      const year = date.getFullYear()
      const formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
      
      let value = data.value
      if (stat.isMoney) {
        value = '¥ ' + this.formatNumber(value)
      }
      if (stat.suffix) {
        value += stat.suffix
      }

      return `
        <div style="text-align: center;">
          <div style="color: rgba(255, 255, 255, 0.8); font-size: 12px; margin-bottom: 4px;">
            ${formattedDate}
          </div>
          <div style="color: #fff; font-size: 14px;">
            ${stat.label} ${value}
          </div>
        </div>
      `
    },
    async initMap() {
      try {
        await AMapLoader.load({
          key: globalConfig.aMap.key,
          version: "2.0",
          plugins: [
            "AMap.ToolBar",
            "AMap.Scale",
            "AMap.HeatMap",
            "AMap.MarkerCluster"
          ],
        });

        this.map = new AMap.Map('storeMap', {
          zoom: 11,
          center: [116.397428, 39.90923],
          viewMode: '3D'
        });

        // 添加工具条和比例尺
        this.map.addControl(new AMap.ToolBar({
          position: 'RB'
        }));
        this.map.addControl(new AMap.Scale());

        // 添加店铺标记
        this.addStoreMarkers();

      } catch (e) {
        console.error('地图初始化失败:', e);
      }
    },
   
  addStoreMarkers() {
    // 清除现有标记
    this.markers.forEach(marker => marker.remove());
    this.markers = [];

    // 添加新标记
    this.storeLocations.forEach(store => {
      const markerContent = document.createElement('div');
      markerContent.className = 'custom-marker';
      markerContent.innerHTML = `<i class="${this.getMarkerIcon(store.status)}"></i>`;

      const marker = new AMap.Marker({
        position: new AMap.LngLat(store.lng, store.lat),
        title: store.name,
        content: markerContent
      });

      const infoWindow = new AMap.InfoWindow({
        content: `
          <div class="map-info-window">
            <h4>${store.name}</h4>
            <p>${store.address}</p>
            <p>状态: ${this.getStatusText(store.status)}</p>
          </div>
        `,
        offset: new AMap.Pixel(0, -30)
      });

      marker.on('click', () => {
        infoWindow.open(this.map, marker.getPosition());
      });

      this.markers.push(marker);
    });

    // 将所有标记添加到地图
    this.map.add(this.markers);

    // 调整视图以包含所有标记
    if (this.markers.length > 0) {
      this.map.setFitView();
    }
  },
    getMarkerIcon(status) {
    // 使用 Element UI 的图标
    switch (status) {
      case 1:
        return 'el-icon-s-shop';
      case 2:
        return 'el-icon-warning';
      default:
        return 'el-icon-s-shop';
    }
  },

  getStatusText(status) {
    const statusMap = {
      1: '正常营业',
      2: '暂停营业'
    };
    return statusMap[status] || '未知状态';
  }
  }
}
</script>

<style lang="scss" scoped>
.statistics-cards {
  .stat-card {
    background: #fff;
    border-radius: 4px;
    padding: 20px;
    height: 180px;
    position: relative;
    overflow: hidden;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
    
    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: var(--bg-color);
      opacity: 0.1;
    }
    
    .stat-header {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      position: relative;
      z-index: 1;
      
      i:first-child {
        font-size: 20px;
        margin-right: 8px;
      }
      
      .stat-title {
        font-size: 14px;
        color: #909399;
      }
      
      .el-icon-question {
        margin-left: 4px;
        color: #909399;
        cursor: pointer;
      }
    }
    
    .stat-body {
      position: relative;
      z-index: 1;
      
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
      }
      
      .stat-trend {
        font-size: 12px;
        color: #909399;
        
        .trend-value {
          margin-left: 4px;
          
          &.up {
            color: #f56c6c;
          }
          
          &.down {
            color: #67c23a;
          }
          
          i {
            margin-left: 2px;
          }
        }
      }
    }
    
    .stat-chart {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 50px;
      z-index: 1;
    }
  }
}

.dashboard-content {
  margin-top: 20px;
  
  .todo-card {
    height: 400px;
    
    .todo-list {
      .todo-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid #EBEEF5;
        
        &:last-child {
          border-bottom: none;
        }
        
        .item-left {
          display: flex;
          align-items: center;
          
          i {
            font-size: 16px;
            margin-right: 8px;
          }
        }
        
        .item-right {
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }
  
  .chart-card {
    height: 400px;
    
    :deep(.el-card__header) {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      height: 300px;
    }
  }

  .map-card {
    height: 500px;
    
    .map-container {
      width: 100%;
      height: 420px;
    }
  }
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #EBEEF5;
  font-size: 14px;
  font-weight: 500;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.map-info-window) {
  padding: 8px 12px;
  
  h4 {
    margin: 0 0 8px;
    font-size: 16px;
    color: #303133;
  }
  
  p {
    margin: 4px 0;
    font-size: 14px;
    color: #606266;
  }
}

:deep(.echarts-tooltip) {
  background: #fff !important;
  border: 1px solid #eee !important;
  border-radius: 4px !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
  padding: 0 !important;
}
</style>