<template>
  <div>
    <div class="title">
      多站总览
      <div class="title_time">{{ currentDate }}</div>
    </div>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="overview_title1">
              <div class="overview_title_name">站点总数</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">{{ multiStation.stationTotalCount }}<span class="overview_unit"> 个</span></div>
              <div class="overview_img">
                <img src="../../assets/images/server2.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line">
              在线{{ multiStation.stationTotalCount }}个 \ 离线{{ multiStation.stationOfflineCount }}个
            </div>
            <el-divider />
            <div class="overview_line">
              装机功率: {{ (multiStation.installedPower * 1).toFixed(2) }}MW | 装机容量:
              {{ (multiStation.installedPower * 1).toFixed(2) }} MWh
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="overview_title1">
              <div class="overview_title_name">今日充电量</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">{{ multiStation.dayImportKwh }} <span class="overview_unit"> MWh</span></div>
              <div class="overview_img1">
                <img src="../../assets/images/charging.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line">较昨日下降: {{ multiStation.importKwhDiffYDay }} MWh</div>
            <el-divider />
            <div class="overview_line">
              月充电: {{ multiStation.monthImportKwh }}MW | 累计充电: {{ multiStation.accumulativeImportKwh }} MWh
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="overview_title1">
              <div class="overview_title_name">今日放电量</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">{{ multiStation.dayExportKwh }}<span class="overview_unit"> MWh</span></div>
              <div class="overview_img2">
                <img src="../../assets/images/discharge.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line">较昨日下降: {{ multiStation.exportKwhDiffYDay }} MWh</div>
            <el-divider />
            <div class="overview_line">
              月充电: {{ multiStation.monthExportKwh }} MWh | 累计充电: {{ multiStation.accumulativeExportKwh }} MWh
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="overview_title1">
              <div class="overview_title_name">今日收益</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">{{ multiStation.todayProfit }} <span class="overview_unit">元</span></div>
              <div class="overview_img3">
                <img src="../../assets/images/qian.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line">较昨日下降: {{ multiStation.profitDiffYDay }} mwh</div>
            <el-divider />
            <div class="overview_line">
              本月收益: {{ multiStation.monthProfit }}万元 | 总收益: {{ multiStation.totalProfit }}万元
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="18">
        <el-card>
          <div class="grid_div grid-content ep-bg-purple">
            <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
              <el-tab-pane label="收益统计" name="first"> </el-tab-pane>
              <el-tab-pane label="充放电统计" name="second"> </el-tab-pane>
              <div class="grid_div1">
                <div v-if="tabpropslabel == '收益统计'" style="width: 68%" ref="baroption" id="baroption"></div>
                <div v-else style="width: 100%" ref="baroption" id="baroption"></div>
                <div id="income" v-show="tabpropslabel == '收益统计'"></div>
              </div>
            </el-tabs>
            <div class="grid_divright">
              <div :class="recentlytype == 7 ? 'grid_divright_1' : 'grid_divright_2'" @click="recently(7)">近7日</div>
              <div :class="recentlytype == 31 ? 'grid_divright_1' : 'grid_divright_2'" @click="recently(31)">近31日</div>
              <div :class="recentlytype == 360 ? 'grid_divright_1' : 'grid_divright_2'" @click="recently(360)">近12月</div>
              <el-date-picker
                v-model="value2"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-value="value2"
                :disabled-date="pickerOptions"
              />
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="grid_right">
              <div>故障警告</div>
              <div class="grid_right1">查看详细</div>
            </div>
            <div id="gridpiechart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统列表</span>
        </div>
      </template>
      <div class="cardtable">
        <div>通讯状态:</div>
        &emsp;
        <el-select v-model="onlineStatus" placeholder="Select" size="large" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        &emsp;
        <el-input v-model="modelinput" style="width: 240px" placeholder="请输入内容" size="large" />
        &emsp;
        <el-button type="primary" size="large" color="#0052d9" @click="query(0)">查询</el-button>
        <el-button size="large" @click="query(1)">重置</el-button>
      </div>
      <el-table :data="tableData.records" style="width: 100%" border>
        <el-table-column type="index" width="50" />
        <el-table-column prop="stationName" label="电站名称" />
        <el-table-column prop="onlineStatus" label="在线状态">
          <template #default="scope">
            {{ scope.row.onlineStatus == 0 ? "离线" : "在线" }}
          </template>
        </el-table-column>
        <el-table-column prop="todayChargeCap" label="今日充电量(kWh)" />
        <el-table-column prop="todayDischargeCap" label="今日放电量(kWh)" />
        <el-table-column prop="totalChargeCap" label="总充电量(kWh)" />
        <el-table-column prop="totalDischargeCap" label="总放电量(kWh)" />
        <el-table-column prop="todayAlarmCount" label="今日告警" align="center">
          <template #default="scope">
            {{ scope.row.todayAlarmCount == null ? "-" : scope.row.todayAlarmCount }}
          </template>
        </el-table-column>

        <el-table-column prop="overallEfficiency" label="综合效率(%)" />
        <el-table-column prop="dischargeCompletionRate" label="放电达成率(%)" />
        <el-table-column prop="yesterdayProfit" label="昨日收益(元)" />
        <el-table-column prop="totalProfit" label="总收益(万元)" />
      </el-table>
      <div class="example_block">
        <!-- <el-pagination layout="prev, pager, next" :total="tableData.records.length" @change="changemultiStationpagebase" /> -->
        <Pagination :pageable="pageable" :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
import type { TabsPaneContext } from "element-plus";
import * as echarts from "echarts";
import Pagination from "@/components/ProTable/components/Pagination.vue";

import {
  gethomesite,
  multiStationday,
  multiStationtopday,
  multiStatiopower,
  alarmMultiStation,
  multiStationpagebaseInfo,
  multiStationdayMonth,
  multiStationtopyearMonth,
  multiStatyearMonth
} from "@/api/home/Multisite";
const multiStation = ref();
const activeName = ref("first");
const value2 = ref();
const tableData = ref();
const currentDate = ref();
const baroption = ref();
const onlineStatus = ref("");
const modelinput = ref();
const tabpropslabel = ref("收益统计");
const recentlytype = ref(7);
const options = ref([
  {
    value: "",
    label: "全部"
  },
  {
    value: "1",
    label: "在线"
  },
  {
    value: "0",
    label: "离线"
  }
]);
const handleClick = (tab: TabsPaneContext) => {
  // if (baroption.value) {
  //   baroption.value.dispose(); //地图图表
  // }

  tabpropslabel.value = tab.props.label;
  if (tab.props.label == "收益统计") {
    getmultiStationtopday(); // 收益排名图
    getmultiStation();
  } else {
    getmultiStatiopower();
  }
};
// 查询最近数据
const recently = (val: any) => {
  // 获取当前日期
  recentlytype.value = val;
  const today = new Date();
  const currentDate = today.toLocaleDateString();

  // 获取过去 7 天的日期
  const sevenDaysAgoDate = new Date(today);
  sevenDaysAgoDate.setDate(today.getDate() - 7);
  const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();

  // 获取过去 31 天的日期
  const thirtyOneDaysAgoDate = new Date(today);
  thirtyOneDaysAgoDate.setDate(today.getDate() - 31);
  const thirtyOneDaysAgo = thirtyOneDaysAgoDate.toLocaleDateString();

  // 获取去年同月的日期
  const lastYearSameMonthDate = new Date(today.getFullYear() - 1, today.getMonth(), today.getDate());
  const lastYearSameMonth = lastYearSameMonthDate.toLocaleDateString();

  if (tabpropslabel.value == "收益统计") {
    if (val == 7) {
      value2.value = [sevenDaysAgo, currentDate];
      getmultiStation(); // 收益统计图
      getmultiStationtopday(); // 收益排名图
    } else if (val == 31) {
      value2.value = [thirtyOneDaysAgo, currentDate];
      getmultiStation(); // 收益统计图
      getmultiStationtopday(); // 收益排名图
    } else {
      value2.value = [lastYearSameMonth, currentDate];

      getmultiStationMonth(); // 收益统计图
      getmultiStationtopMonth(); // 收益排名图
    }
  } else {
    if (val == 7) {
      value2.value = [sevenDaysAgo, currentDate];
      getmultiStatiopower(); // 充放电统计图
    } else if (val == 31) {
      value2.value = [thirtyOneDaysAgo, currentDate];
      getmultiStatiopower(); // 充放电统计图
    } else {
      value2.value = [lastYearSameMonth, currentDate];
      getmultiStatiopowerMonth();
    }
  }
};

const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};
const getsite = async () => {
  // 获取年份
  const year = new Date().getFullYear();
  // 获取月份，补零
  const month = String(new Date().getMonth() + 1).padStart(2, "0");
  // 获取日期，补零
  const day = String(new Date().getDate()).padStart(2, "0");
  // 拼接年月日
  currentDate.value = `${year}-${month}-${day}`;
  localStorage.setItem("currentDate", currentDate.value);
  const today = new Date();
  const sevenDaysAgoDate = new Date(today);
  sevenDaysAgoDate.setDate(today.getDate() - 6);
  const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();
  value2.value = [sevenDaysAgo, currentDate.value];
  const { data } = await gethomesite();

  multiStation.value = data;
};
// 收益统计图
const getmultiStation = async () => {
  const { data } = await multiStationday({ startDate: value2.value[0], endDate: value2.value[1] });
  // const profits = data.map(item => item.profit);
  // const dates = data.map(item => item.ymd);
  const dates = [["product", "收益"]];
  // console.log(data.length);

  if (data.length != 0) {
    for (let index = 0; index < data.length; index++) {
      dates.push([data[index].ymd, data[index].profit]);
    }
  } else {
    dates.push([value2.value[0], "50"], [value2.value[1], "120"]);
  }
  const profits = [{ type: "bar" }];

  baroptionchart(dates, profits);
};
// 收益统计图
const getmultiStationMonth = async () => {
  const { data } = await multiStationdayMonth({ startDate: value2.value[0], endDate: value2.value[1] });
  // const profits = data.map(item => item.profit);
  // const dates = data.map(item => item.ymd);
  const dates = [["product", "收益"]];

  if (data.length != 0) {
    for (let index = 0; index < data.length; index++) {
      dates.push([data[index].ymd, data[index].profit]);
    }
  } else {
    dates.push([value2.value[1], "0"]);
  }

  const profits = [{ type: "bar" }];

  baroptionchart(dates, profits);
};
// 充放电统计图
const getmultiStatiopower = async () => {
  const { data } = await multiStatiopower({ startDate: value2.value[0], endDate: value2.value[1] });
  const dates = [["product", "充电", "放电"]];
  if (data.length != 0) {
    for (let index = 0; index < data.length; index++) {
      dates.push([data[index].ymd, data[index].chargeTotal.toString(), data[index].dischargeTotal.toString()]);
    }
  } else {
    dates.push([value2.value[1], "0", "0"]);
  }

  const profits = [{ type: "bar" }, { type: "bar" }];

  baroptionchart(dates, profits);
};
// 充放电统计月份
const getmultiStatiopowerMonth = async () => {
  const { data } = await multiStatyearMonth({ startYearMonth: value2.value[0], endYearMonth: value2.value[1] });
  const dates = [["product", "充电", "放电"]];
  // console.log(data);

  if (data.length != 0) {
    for (let index = 0; index < data.length; index++) {
      dates.push([data[index].ymd, data[index].chargeTotal.toString(), data[index].dischargeTotal.toString()]);
    }
  } else {
    dates.push([value2.value[1], "0", "0"]);
  }

  const profits = [{ type: "bar" }, { type: "bar" }];
  baroptionchart(dates, profits);
};
// 收益统计
const baroptionchart = (dates: string[][], profits: { type: string }[]) => {
  // console.log(dates, profits);

  const baroptionvalue = echarts.init(baroption.value);
  window.addEventListener(
    "resize",
    () => {
      baroptionvalue.resize();
    },
    false
  );
  let option = {
    title: {
      subtext: "收益/元"
    },
    legend: {
      right: 30
    },
    grid: {
      left: "1%",
      right: "4%",
      bottom: "0%",
      containLabel: true
    },
    xAxis: {
      type: "category"
    },
    yAxis: {
      type: "value"
    },
    dataset: {
      source: dates
    },
    series: profits
  };

  baroptionvalue.setOption(option, true);
};
// 收益排名日
const getmultiStationtopday = async () => {
  const { data } = await multiStationtopday({ startDate: value2.value[0], endDate: value2.value[1] });
  let profitlist = [];
  let stationNames = [];
  if (data.length != 0) {
    profitlist = data.map(item => item.profit).sort((a, b) => a - b);
    stationNames = data.map(item => item.stationName);
  } else {
    profitlist = [60, 40, 70, 20, 80, 100, 120];
    stationNames = ["演示电站一", "演示电站二", "演示电站三", "演示电站四", "演示电站五", "演示电站六", "演示电站七"];
  }

  // console.log(profitlist, stationNames);

  baroptionincome(profitlist, stationNames);
};
// 收益排名月份
const getmultiStationtopMonth = async () => {
  const { data } = await multiStationtopyearMonth({ startDate: value2.value[0], endDate: value2.value[1] });
  const profitlist = data.map(item => item.profit).sort((a, b) => a - b);
  const stationNames = data.map(item => item.stationName);

  baroptionincome(profitlist, stationNames);
};
// 收益排名
const baroptionincome = (profitlist: number[], stationNames: string[]) => {
  let baroption = echarts.init(document.getElementById("income"));
  window.addEventListener(
    "resize",
    () => {
      baroption.resize();
    },
    false
  );
  let option = {
    title: {
      subtext: "收益排名"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {},
    grid: {
      left: "3%",
      right: "1%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: "value",
      inverse: true, // 将 Y 轴反转
      data: stationNames,
      axisLabel: {
        textStyle: {
          fontSize: 0 // 设置字体大小
        }
      },
      axisLine: {
        show: false // 隐藏 X 轴刻度线
      },
      axisTick: {
        show: false // 隐藏 X 轴刻度线
      },
      splitLine: {
        show: false // 隐藏 x 轴背景刻度线
      }
    },
    yAxis: {
      type: "category",
      position: "right",
      data: profitlist,
      axisLine: {
        show: false // 隐藏 y 轴刻度线
      },
      axisTick: {
        show: false // 隐藏 y 轴刻度线
      }
    },
    series: [
      {
        type: "bar",
        data: profitlist,
        label: {
          //图形上显示文本标签
          formatter: function (p: any) {
            return stationNames[p.dataIndex];
          },
          show: true,
          position: "right",
          distance: -105, // 设置标签与图形的距离
          textStyle: {
            fontWeight: "bolder",
            fontSize: "10" //文字大小
          }
        },
        stack: "total", //数据堆叠同个类目轴上系列配置相同的stack值可以堆叠放置
        //图形渐变色
        color: "#d6e9ca"
      }
    ]
  };

  baroption.setOption(option);
};
const postalarmMultiStation = async () => {
  let { data } = await alarmMultiStation({});
  let list = data.map(function (item) {
    return {
      value: item.cnt, // 将 cnt 键修改为 value
      name: item.name
    };
  });

  baropPiechart(list);
};

// 故障告警
const baropPiechart = (list: string | any[]) => {
  let piechart = echarts.init(document.getElementById("gridpiechart"));
  window.addEventListener(
    "resize",
    () => {
      piechart.resize();
    },
    false
  );
  let option1 = {
    tooltip: {
      trigger: "item"
    },
    legend: {
      show: true,
      orient: "vertical",
      bottom: "0%",
      icon: "circle",
      textStyle: {
        fontSize: 14,
        rich: {
          a: {
            fontSize: 14
          }
        }
      },
      formatter: function (name: string) {
        for (let index = 0; index < list.length; index++) {
          if (name == list[index].name) {
            return `${name + " " + " " + "" + " "} {a|${list[index].value}} 条`;
          }
        }
      }
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: "center",
          fontSize: 0
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 0,
            fontWeight: "bold"
          }
        },
        labelLine: {
          show: false
        },
        data: list
      }
    ]
  };

  piechart.setOption(option1);
};
// 查询
const query = async (val: number) => {
  if (val == 0) {
    postmultiStationpagebaseInfo();
  } else {
    onlineStatus.value = "";
    modelinput.value = "";
    pageable.value.pn = 1;
    pageable.value.ps = 10;
    postmultiStationpagebaseInfo();
  }
};

// const changemultiStationpagebase = async (value: any) => {
//   pageable.value.ps = value;
//   postmultiStationpagebaseInfo();
// };
const pageable = ref({
  ps: 10,
  pn: 1,
  total: 0
});
const handleSizeChange = async (e: any) => {
  pageable.value.ps = e;
  postmultiStationpagebaseInfo();
};
const handleCurrentChange = async (e: any) => {
  pageable.value.pn = e;

  postmultiStationpagebaseInfo();
};
// 电站列表
const postmultiStationpagebaseInfo = async () => {
  const { data } = await multiStationpagebaseInfo({
    onlineStatus: onlineStatus.value,
    keyword: modelinput.value,
    pn: pageable.value.pn,
    ps: pageable.value.ps
  });

  tableData.value = data;
  console.log(tableData.value.total);

  pageable.value.total = tableData.value.total;
};
onMounted(() => {
  getsite();
  getmultiStationtopday();
  postalarmMultiStation();
  getmultiStation();
  postmultiStationpagebaseInfo();
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
<!-- 

-->
