<template>
  <div id="my_index">
    <div class="viewBar">
      <div v-for="item in list">
        <div class="item">
          <div class="title"
            >{{ item.title }}<span>{{ item.unit }}</span></div
          >
          <div class="count">{{ item.count }}</div>
        </div>
        <div class="icon">
          <img :src="item.icon" />
        </div>
      </div>
    </div>
    <div>
        <el-row :gutter="16" class="mb-10">
            <el-col :span="12">
                <el-card shadow="always" class="box-card">
                    <div slot="header" class="clearfix">
                        <span>场站月用煤量对比</span>
                    </div>
                    <div class="grid-content">
                        <chart-bar-line
                            :xAxisData="monthCoalData.xAxisData"
                            :barSeries="monthCoalData.barSeries"
                            barYAxisName="车"
                            height="280px"
                        />
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" class="box-card">
                    <div slot="header" class="clearfix">
                        <span>场站日用煤量对比</span>
                    </div>
                    <div class="grid-content">
                        <chart-bar-line
                            :xAxisData="dayCoalData.xAxisData"
                            :barSeries="dayCoalData.barSeries"
                            barYAxisName="车"
                            height="280px"
                        />
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="16" class="mb-10">
            <el-col :span="12">
                <el-card shadow="always" class="box-card">
                    <div slot="header" class="clearfix">
                        <span>场站月拉灰量对比</span>
                    </div>
                    <div class="grid-content">
                        <chart-bar-line
                            :xAxisData="monthGreyData.xAxisData"
                            :barSeries="monthGreyData.barSeries"
                            barYAxisName="车"
                            height="280px"
                        />
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" class="box-card">
                    <div slot="header" class="clearfix">
                        <span>场站日拉灰量对比</span>
                    </div>
                    <div class="grid-content">
                        <chart-bar-line
                            :xAxisData="dayGreyData.xAxisData"
                            :barSeries="dayGreyData.barSeries"
                            barYAxisName="车"
                            height="280px"
                        />
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-row :gutter="16" class="mb-10">
            <el-col :span="12">
                <el-card shadow="always" class="box-card">
                    <div slot="header" class="clearfix">
                        <span>场站月拉渣量对比</span>
                    </div>
                    <div class="grid-content">
                        <chart-bar-line
                            :xAxisData="monthSlagData.xAxisData"
                            :barSeries="monthSlagData.barSeries"
                            barYAxisName="车"
                            height="280px"
                        />
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card shadow="always" class="box-card">
                    <div slot="header" class="clearfix">
                        <span>场站日拉渣量对比</span>
                    </div>
                    <div class="grid-content">
                        <chart-bar-line
                            :xAxisData="daySlagData.xAxisData"
                            :barSeries="daySlagData.barSeries"
                            barYAxisName="车"
                            height="280px"
                        />
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
  </div>
</template>

<script>
import indexApi from '@/api/main/index.js';
import chartBarLine from '@/components/ChartBarLine/index.vue';

  const  COAL_WAREHOUSE_MAP = {
    '2008474572461486082': '5#场站',
    '2064887500559134721': '6#场站',
    '2064887643979165697': '7#场站'
  };

  const GREY_WAREHOUSE_MAP = {
    '2008475053149696001': '5#场站',
    '2008475191167463426': '6#场站',
    '2008475309006434305': '7#场站'
  };

  const COAL_STATION_KEYS = ['2008474572461486082', '2064887500559134721', '2064887643979165697'];

  const GREY_STATION_KEYS = ['2008475053149696001', '2008475191167463426', '2008475309006434305'];

  // 各图表颜色配置
  const CHART_COLORS = {
    monthCoal:  ['#3876f1', '#f8cd5d', '#5cd07b'],
    dayCoal:    ['#5e5e5e', '#f7cd5c', '#00a1f1'],
    monthGrey:  ['#979797', '#5df9f5', '#5cd07b'],
    dayGrey:    ['#98aa00', '#5df9f5', '#5cd07b'],
    monthSlag:  ['#7ca7ff', '#fef538', '#b6b6b6'],
    daySlag:    ['#39496b', '#ff7b00', '#b6b6b6']
  };

  export default {
    components: { chartBarLine },
    data() {
      return {
        list: [
          {
            title: '来煤累计数',
            key: 'coalInbound',
            count: '',
            icon: require('../../../assets/index/Vector@2x.png')
          },
          {
            title: '用煤累计数',
            unit: '',
            key: 'coalConsumption',
            count: '',
            icon: require('../../../assets/index/Vector@2x.png')
          },
          {
            title: '煤库存数',
            count: '',
            key: 'coalInventory',
            icon: require('../../../assets/index/Vector@2x.png')
          },
        ],
        // 图表数据
        monthCoalData: { xAxisData: [], barSeries: [], lineSeries: [] },
        dayCoalData:   { xAxisData: [], barSeries: [], lineSeries: [] },
        monthGreyData: { xAxisData: [], barSeries: [], lineSeries: [] },
        dayGreyData:   { xAxisData: [], barSeries: [], lineSeries: [] },
        monthSlagData: { xAxisData: [], barSeries: [], lineSeries: [] },
        daySlagData:   { xAxisData: [], barSeries: [], lineSeries: [] }
      };
    },
    computed: {},

    mounted() {
        this.init();
        this.monthCoalStatistics();
        this.dayCoalStatistics();
        this.monthGreyStatistics();
        this.dayGreyStatistics();
        this.monthSlagStatistics();
        this.daySlagStatistics();
    },
    methods: {
        async init() {
        let data = await indexApi.coalStatistics();
        this.list.forEach((item) => {
          item.count = data[item.key];
        });
      },
      /* 将接口数据转为图表格式
       * records: API 返回的数组
       * timeKey: 时间字段 'month' | 'dayTime'
       * colors: 颜色数组 [5#, 6#, 7#]
       * stationKeys: 场站 ID 顺序数组
       * warehouseMap: warehouseId → 场站名称映射
       */
      _formatChartData(records, timeKey, colors, stationKeys, warehouseMap) {
        // 生成完整的时间轴（key 用于数据匹配，label 用于显示）
        const now = new Date();
        const slots = timeKey === 'month'
          ? Array.from({ length: 12 }, (_, i) => {
              const m = String(i + 1).padStart(2, '0');
              return { key: `${now.getFullYear()}-${m}`, label: `${i + 1}月` };
            })
          : (() => {
              const y = now.getFullYear();
              const m = String(now.getMonth() + 1).padStart(2, '0');
              const lastDay = new Date(y, +m, 0).getDate();
              return Array.from({ length: lastDay }, (_, i) => {
                const d = String(i + 1).padStart(2, '0');
                return { key: `${y}-${m}-${d}`, label: `${i + 1}` };
              });
            })();
        const timeKeys = slots.map((s) => s.key);
        const xAxisData = slots.map((s) => s.label);
        // 按时间分组汇总
        const byTime = {};
        records.forEach((r) => {
          const t = r[timeKey];
          if (!t) return;
          if (!byTime[t]) byTime[t] = {};
          byTime[t][r.warehouseId] = (byTime[t][r.warehouseId] || 0) + parseFloat(r.totalQuantity || 0);
        });
        const barSeries = [];
        stationKeys.forEach((wid, idx) => {
          const name = warehouseMap[wid];
          const data = timeKeys.map((t) => +(byTime[t]?.[wid] || 0).toFixed(2));
          const color = colors[idx];
          barSeries.push({ name, data, color });
        });
        return { xAxisData, barSeries, lineSeries: [] };
      },
      // 宇信煤的月度统计
      async monthCoalStatistics() {
        const data = await indexApi.monthCoalStatistics();
        this.monthCoalData = this._formatChartData(data, 'month', CHART_COLORS.monthCoal, COAL_STATION_KEYS, COAL_WAREHOUSE_MAP);
      },
      // 宇信煤的日统计
      async dayCoalStatistics() {
        const data = await indexApi.dayCoalStatistics();
        this.dayCoalData = this._formatChartData(data, 'dayTime', CHART_COLORS.dayCoal, COAL_STATION_KEYS, COAL_WAREHOUSE_MAP);
      },
      // 宇信灰的月度统计
      async monthGreyStatistics() {
        const data = await indexApi.greyMonthStatistics();
        this.monthGreyData = this._formatChartData(data, 'month', CHART_COLORS.monthGrey, GREY_STATION_KEYS, GREY_WAREHOUSE_MAP);
      },
      // 宇信灰的日统计
      async dayGreyStatistics() {
        const data = await indexApi.greyDayStatistics();
        this.dayGreyData = this._formatChartData(data, 'dayTime', CHART_COLORS.dayGrey, GREY_STATION_KEYS, GREY_WAREHOUSE_MAP);
      },
      // 宇信渣的月度统计
      async monthSlagStatistics() {
        const data = await indexApi.slagMonthStatistics();
        this.monthSlagData = this._formatChartData(data, 'month', CHART_COLORS.monthSlag, GREY_STATION_KEYS, GREY_WAREHOUSE_MAP);
      },
      // 宇信渣的日统计
      async daySlagStatistics() {
        const data = await indexApi.slagDayStatistics();
        this.daySlagData = this._formatChartData(data, 'dayTime', CHART_COLORS.daySlag, GREY_STATION_KEYS, GREY_WAREHOUSE_MAP);
      },
    }
  };
</script>

<style lang="scss" scoped>
#my_index {
    // height: calc(100vh - 96px);
    display: flex;
    width: 100%;
    padding: 10px;
    flex-direction: column;
    box-sizing: border-box;
    // background-color: #dbdbdb;
    .viewBar {
      height: 90px;
      width: 100%;
      display: flex;
      margin-bottom: 10px;
      justify-content: space-around;
      > div {
        // flex: 1;
        width: 25%;
        margin-left: 10px;
        background: linear-gradient(to right, #2d80ee 100%, #e9f2ff 50%);
        border-radius: 8px;
        display: flex;
        padding: 0 20px;
        box-sizing: border-box;
        .item {
          flex: 1;
          display: flex;
          flex-direction: column;
          .title {
            flex: 1;
            display: flex;
            align-items: center;
            font-size: 16px;
            color: rgba(255, 255, 255, 1);
            > span {
              font-size: 12px;
            }
          }
          .count {
            flex: 1;
            display: flex;
            align-items: center;
            font-size: 28px;
            color: rgba(255, 255, 255, 1);
          }
        }
        .icon {
          width: 50px;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          > img {
            height: 50px;
            width: 50px;
          }
        }
      }
      > div:first-child {
        margin-left: 0;
      }
    }
    .mb-10 {
        margin-bottom: 10px;
    }
  }
</style>
