<template>
  <div class="home-container layout-pd">
    <el-row :gutter="15" class="home-card-one mb15">
      <el-col
          :xs="24"
          :sm="12"
          :md="12"
          :lg="4"
          :xl="4"
          v-for="(v, k) in state.homeOne"
          :key="k"
          :class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }"
      >
        <div class="home-card-item flex">
          <div class="flex-margin flex w100" :class="` home-one-animation${k}`">
            <div class="flex-auto">
              <span class="font30">{{ v.num1 }}</span>
              <!--              <span class="ml5 font16" :style="{ color: v.color1 }">{{ v.num2 }}%</span>-->
              <div class="mt10">{{ v.num3 }}</div>
            </div>
            <!--            <div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">-->
            <!--              <i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>-->
            <!--            </div>-->
          </div>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="15" class="home-card-two mb15">
      <el-col :xs="24" :sm="14" :md="14" :lg="16" :xl="16">
        <div class="home-card-item">
          <div class="w100  trend-header">
            <div style="width: 300px">
              <el-date-picker
                  @change="loadStationStat"
                  value-format="YYYY-MM-DD"
                  v-model="state.dateRange"
                  type="daterange"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  :shortcuts="shortcuts"
              />
            </div>


            <div class="trend-summary">
              总实付服务费:
              <el-tag type="success">{{ u.fmt.fmtMoney(state.homeOneExtra.payServiceAmount) }}元</el-tag>
              总电量:
              <el-tag type="danger">{{ state.homeOneExtra.totalPower }}Kwh</el-tag>
            </div>
          </div>

          <div style="height: 100%;padding: 20px;" ref="homeLineRef"></div>
        </div>
      </el-col>
      <el-col :xs="24" :sm="10" :md="10" :lg="8" :xl="8" class="home-media">
        <div class="home-card-item">
          <div style="height: 100%" ref="homePieRef"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="home">
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

import {markRaw, nextTick, onActivated, onMounted, reactive, ref, watch} from 'vue';
import * as echarts from 'echarts';
import {storeToRefs} from 'pinia';
import {useThemeConfig} from '/@/stores/themeConfig';
import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes';
import {$get} from "/@/utils/request";
import u from "/@/utils/u";
import mittBus from "/@/utils/mitt";
import {Session} from "/@/utils/storage";

// 定义变量内容
const homeLineRef = ref();
const homePieRef = ref();
const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const {themeConfig} = storeToRefs(storesThemeConfig);
const {isTagsViewCurrenFull} = storeToRefs(storesTagsViewRoutes);

const end = new Date()
const start = new Date()
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)

const defaultTime = ref<[Date, Date]>([
  new Date(2000, 1, 1, 12, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59),
])

const state = reactive({
  currentStationId: null,
  dateRange: [u.date.format(start, "YYYY-MM-DD"), u.date.format(end, "YYYY-MM-DD")],
  global: {
    homeChartOne: null,
    homeChartTwo: null,
    homeCharThree: null,
    dispose: [null, '', undefined],
  } as any,
  homeOne: [
    {
      num1: '0',
      num2: '-12.32',
      num3: '今日充电量（kwh）',
      num4: 'fa fa-meetup',
      color1: '#FF6462',
      color2: '--next-color-primary-lighter',
      color3: '--el-color-primary',
    },
    {
      num1: '0',
      num2: '+42.32',
      num3: '今日订单总金额（元）',
      num4: 'iconfont icon-ditu',
      color1: '#6690F9',
      color2: '--next-color-success-lighter',
      color3: '--el-color-success',
    },
    {
      num1: '0',
      num2: '+17.32',
      num3: '今日总电费（元）',
      num4: 'iconfont icon-zaosheng',
      color1: '#6690F9',
      color2: '--next-color-warning-lighter',
      color3: '--el-color-warning',
    },
    {
      num1: '0',
      num2: '-10.01',
      num3: '今日实付总服务费（元）',
      num4: 'fa fa-github-alt',
      color1: '#FF6462',
      color2: '--next-color-danger-lighter',
      color3: '--el-color-danger',
    },
    {
      num1: '0',
      num2: '-10.01',
      num3: '今日充电人数',
      num4: 'fa fa-github-alt',
      color1: '#FF6462',
      color2: '--next-color-danger-lighter',
      color3: '--el-color-danger',
    },
    {
      num1: '0',
      num2: '-10.01',
      num3: '今日充电订单数（笔）',
      num4: 'fa fa-github-alt',
      color1: '#FF6462',
      color2: '--next-color-danger-lighter',
      color3: '--el-color-danger',
    },
  ],
  myCharts: [] as EmptyArrayType,
  charts: {
    theme: '',
    bgColor: '',
    color: '#303133',
  },
  homeOneExtra: {}
});

const shortcuts = [
  {
    text: '近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
  {
    text: '近90天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    },
  },
]

// 折线图
const initLineChart = (dataList: Array<any>) => {
  if (!state.global.dispose.some((b: any) => b === state.global.homeChartOne)) state.global.homeChartOne.dispose();
  state.global.homeChartOne = markRaw(echarts.init(homeLineRef.value, state.charts.theme));

  u.sort(dataList, "statTime")

  let xAxis = dataList.map(k => k.statTime)
  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '充电数据走势图',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    grid: {top: 70, right: 0, bottom: 30, left: 50},
    tooltip: {trigger: 'axis'},
    legend: {data: ['充电量', /*'总金额','电费',*/'实付服务费',], right: 0},
    xAxis: {
      data: xAxis,
      // data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: [
      {
        type: 'value',
        name: '费用/元 充电量/度',
        position: 'left',
        splitLine: {show: true, lineStyle: {type: 'dashed', color: '#f5f5f5'}},
      },
    ],
    series: [
      {
        name: '充电量',
        type: 'bar',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: dataList.map(k => k.totalPower),
        // data: [0, 41.1, 30.4, 65.1, 53.3, 53.3, 53.3, 41.1, 30.4, 65.1, 53.3, 10],
        lineStyle: {color: '#68a7a0'},
        itemStyle: {color: '#68a7a0', borderColor: '#68a7a0', barBorderRadius: 5},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#25b8d2'},
            {offset: 1, color: '#fe9a8b03'},
          ]),
        },
      },
      /*      {
              name: '总金额',
              type: 'line',
              symbolSize: 6,
              symbol: 'circle',
              smooth: true,
              data: dataList.map(k=>u.fmt.fmtMoney(k.totalMoney)),
              lineStyle: {color: '#fe9a8b'},
              itemStyle: {color: '#fe9a8b', borderColor: '#fe9a8b'},
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {offset: 0, color: '#fe9a8bb3'},
                  {offset: 1, color: '#fe9a8b03'},
                ]),
              },
            },
            {
              name: '电费',
              type: 'line',
              symbolSize: 6,
              symbol: 'circle',
              smooth: true,
              data: dataList.map(k=>u.fmt.fmtMoney(k.elecMoney)),
              lineStyle: {color: '#b5fe8b'},
              itemStyle: {color: '#b5fe8b', borderColor: '#b5fe8b'},
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {offset: 0, color: '#b5fe8b'},
                  {offset: 1, color: '#fe9a8b03'},
                ]),
              },
            },*/
      {
        name: '实付服务费',
        type: 'line',
        symbolSize: 6,
        symbol: 'circle',
        smooth: true,
        data: dataList.map(k => u.fmt.fmtMoney(k.payServiceAmount)),
        lineStyle: {color: '#3770ff'},
        itemStyle: {color: '#3770ff', borderColor: '#3770ff'},
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {offset: 0, color: '#9E87FFb3'},
            {offset: 1, color: '#9E87FF03'},
          ]),
        },
        emphasis: {
          itemStyle: {
            color: {
              type: 'radial',
              x: 0.5,
              y: 0.5,
              r: 0.5,
              colorStops: [
                {offset: 0, color: '#9E87FF'},
                {offset: 0.4, color: '#9E87FF'},
                {offset: 0.5, color: '#fff'},
                {offset: 0.7, color: '#fff'},
                {offset: 0.8, color: '#fff'},
                {offset: 1, color: '#fff'},
              ],
            },
            borderColor: '#9E87FF',
            borderWidth: 2,
          },
        },
      },
    ],
  };
  state.global.homeChartOne.setOption(option);
  state.myCharts.push(state.global.homeChartOne);
};
// 饼图
const initPieChart = (dataMap: any) => {
  if (!state.global.dispose.some((b: any) => b === state.global.homeChartTwo)) state.global.homeChartTwo.dispose();
  state.global.homeChartTwo = markRaw(echarts.init(homePieRef.value, state.charts.theme));
  var getname = ['离线', '空闲', '已连接', '充电中', '预约中', '故障'];
  const colorList = ['#6B6F75FF', '#36C78B', '#e9ee8e', '#ffa496', '#E790E8','#363638FF'];
  // var getvalue = [34.2, 38.87, 17.88];
  // var data = [dataMap["0"]||0,dataMap["1"]||0,dataMap["2"]||0];
  var data = [];
  for (var i = 0; i < getname.length; i++) {
    data.push({name: getname[i], value: dataMap[`${i}`] || 0});
  }

  const option = {
    backgroundColor: state.charts.bgColor,
    title: {
      text: '充电站电桩状态',
      x: 'left',
      textStyle: {fontSize: '15', color: state.charts.color},
    },
    tooltip: {trigger: 'item', formatter: '{b} <br/> {c}'},
    graphic: {
      elements: [
        {
          type: 'image',
          z: -1,
          style: {
            image: themeConfig.value.isIsDark
                ? ''
                : 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANkAAADICAYAAABlNERIAAAAAXNSR0IArs4c6QAAFGVJREFUeF7tnX+QHvVdxz+fvWRaYEjyPM+VFEQL5Nk7ICO1zaVBi23iiBUKdKxWHIsKpc3l2Sc5LI2Kgx2ComCxxV549nJAgerEOmEsGAftOFZCa60gUmNJ8G6fpOdQqE3y7JMUTEuS24/zJHfJ5XLP7X53v/vj2eedGf7az8/35/Ni93mevV2mhP8VHhy7lrnnBmJ5FxH1ElGJiBYnXEbe0x0iogYRHSCRf/M8fvLgBnNH3pvOan+cRGG9oxPne8feHCQ2foOILkk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3oUcC0z8lWSnkrSjwLI0p9BLisAZKfGCshyueLpNwXIAFn6W5jzCgAZIMv5iqffHiADZOlvYc4rAGSALOcrnn57gAyQpb+FOa8AkAGynK94+u0BMkCW/hbmvAJABshyvuLptwfIAFn6W5jzCgAZIMv5iqffHiADZOlvYc4rAGSALOcrnn57gAyQpb+FOa8AkJ0a8P8Dt530O4Vfc6gAAAAASUVORK5CYII=',
            width: 60,
            height: 60,
          },
          left: '27.5%',
          top: 'center',
        },
      ],
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: '0%',
      left: '65%',
      top: 'center',
      itemWidth: 14,
      itemHeight: 14,
      data: getname,
      textStyle: {
        rich: {
          name: {
            fontSize: 14,
            fontWeight: 400,
            width: 200,
            height: 35,
            padding: [0, 0, 0, 60],
            color: state.charts.color,
          },
          rate: {
            fontSize: 15,
            fontWeight: 500,
            height: 35,
            width: 40,
            padding: [0, 0, 0, 30],
            color: state.charts.color,
          },
        },
      },
    },
    series: [
      {
        type: 'pie',
        radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
        center: ['32%', '50%'],
        itemStyle: {
          color: function (params: any) {
            return colorList[params.dataIndex];
          },
        },
        label: {show: false},
        labelLine: {show: false},
        data: data,
      },
    ],
  };
  state.global.homeChartTwo.setOption(option);
  state.myCharts.push(state.global.homeChartTwo);
};
// 柱状图
// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    for (let i = 0; i < state.myCharts.length; i++) {
      setTimeout(() => {
        state.myCharts[i].resize();
      }, i * 1000);
    }
  });
};
// 批量设置 echarts resize
const initEchartsResize = () => {
  window.addEventListener('resize', initEchartsResizeFun);
};

const loadCurrentEquipmentStatus = () => {
  $get(`connector/statConnectorStatus`, {stationId: state.currentStationId}).then((res: any) => {
    console.log(res)
    initPieChart(res || {});
  })
}


const loadStationStat = () => {
  let start = state.dateRange[0]
  let end = state.dateRange[1]
  let size = u.date.diff(new Date(start), new Date(end)) + 1;
  $get(`stat/stationStat`, {
    startTime: start,
    endTime: end,
    type: 'day',
    pageSize: size,
    stationId: state.currentStationId
  }).then((res: any) => {
    console.log(res)
    state.homeOneExtra = res.extraData
    initLineChart(res.list);
  })
}

const loadStationStatToday = () => {
  $get(`stat/stationTodayStat`, {stationId: state.currentStationId}).then((res: any) => {
    console.log(res)
    if (!u.isEmptyOrNull(res)) {
      let {chargeUsers, totalOrders, totalPower, totalMoney, elecMoney, payServiceAmount} = res
      state.homeOne[0].num1 = totalPower;
      state.homeOne[1].num1 = u.fmt.fmtMoney(totalMoney);
      state.homeOne[2].num1 = u.fmt.fmtMoney(elecMoney);
      state.homeOne[3].num1 = u.fmt.fmtMoney(payServiceAmount);
      state.homeOne[4].num1 = chargeUsers;
      state.homeOne[5].num1 = totalOrders;
    }

  })
}
// 页面加载时
onMounted(() => {
  var currentStationId = Session.get("currentStationId");
  if (currentStationId) {
    state.currentStationId = currentStationId;
  }
  console.error("home onMounted")
  NProgress.done();
  initEchartsResize();
  //加载充电走势数据
  loadStationStat()
  //今日统计数据
  loadStationStatToday();

  //加载充电桩状态
  loadCurrentEquipmentStatus();

  mittBus.on('stationChangeRefresh', (stationId) => {
    if (stationId) {
      state.currentStationId = stationId;
      loadStationStat()
      loadStationStatToday()
      loadCurrentEquipmentStatus()
    }
  });
});
// 由于页面缓存原因，keep-alive
onActivated(() => {
  initEchartsResizeFun();
});
// 监听 pinia 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
    () => isTagsViewCurrenFull.value,
    () => {
      initEchartsResizeFun();
    }
);
// 监听 pinia 中是否开启深色主题
watch(
    () => themeConfig.value.isIsDark,
    (isIsDark) => {
      nextTick(() => {
        state.charts.theme = isIsDark ? 'dark' : '';
        state.charts.bgColor = isIsDark ? 'transparent' : '';
        state.charts.color = isIsDark ? '#dadada' : '#303133';
        setTimeout(() => {
          loadStationStat()
        }, 500);
        setTimeout(() => {
          loadCurrentEquipmentStatus();
        }, 700);
        // setTimeout(() => {
        //   initBarChart();
        // }, 1000);
      });
    },
    {
      deep: true,
      immediate: true,
    }
);
</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
  overflow: hidden;

  .home-card-one,
  .home-card-two,
  .home-card-three {
    .home-card-item {
      width: 100%;
      height: 180px;
      border-radius: 4px;
      transition: all ease 0.3s;
      padding: 20px;
      overflow: hidden;
      background: var(--el-color-white);
      color: var(--el-text-color-primary);
      border: 1px solid var(--next-border-color-light);

      &:hover {
        box-shadow: 0 2px 12px var(--next-color-dark-hover);
        transition: all ease 0.3s;
      }

      &-icon {
        width: 70px;
        height: 70px;
        border-radius: 100%;
        flex-shrink: 1;

        i {
          color: var(--el-text-color-placeholder);
        }
      }

      &-title {
        font-size: 15px;
        font-weight: bold;
        height: 30px;
      }
    }
  }

  .home-card-one {
    @for $i from 0 through 3 {
      .home-one-animation#{$i} {
        opacity: 0;
        animation-name: error-num;
        animation-duration: 0.5s;
        animation-fill-mode: forwards;
        animation-delay: calc($i/4) + s;
      }
    }
  }

  .home-card-two,
  .home-card-three {
    .home-card-item {
      height: 780px;
      width: 100%;
      overflow: hidden;

      .home-monitor {
        height: 100%;

        .flex-warp-item {
          width: 25%;
          height: 111px;
          display: flex;

          .flex-warp-item-box {
            margin: auto;
            text-align: center;
            color: var(--el-text-color-primary);
            display: flex;
            border-radius: 5px;
            background: var(--next-bg-color);
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transition: all 0.3s ease;
            }
          }

          @for $i from 0 through $homeNavLengh {
            .home-animation#{$i} {
              opacity: 0;
              animation-name: error-num;
              animation-duration: 0.5s;
              animation-fill-mode: forwards;
              animation-delay: calc($i/10) + s;
            }
          }
        }
      }
    }
  }
}

.trend-header {
  display: inline-flex;
  justify-content: space-between;

  .trend-summary {
    flex: -1;
  }
}
</style>
