<template>
  <div>
    <div class="title">
      <el-select
        v-model="Singlevalue"
        collapse-tags
        :placeholder="$t('overview.SelectPlant')"
        popper-class="custom-header"
        :max-collapse-tags="1"
        class="Space_content"
        size="large"
      >
        <el-option
          v-for="(item, index) in cities"
          :key="index"
          :label="item.stationName"
          :value="item.id"
          @click="onselect(item)"
        />
        <template #prefix>
          {{ (cities.find(s => s.id === Singlevalue) || {}).stationName }}
        </template>
      </el-select>
    </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">{{ $t("overview.TodayEnergy") }}</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">
                {{ formatAmountkwh(multiStation.dayImportKwh) }}
                <span class="overview_unit"> {{ formatCompany(multiStation.dayImportKwh) }}</span>
              </div>
              <div class="overview_img1">
                <img src="../../assets/images/charging.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line" v-if="multiStation.importKwhDiffYDay > 0">
              {{ $t("overview.upperYesterday") }}: {{ formatAmountkwh_(multiStation.importKwhDiffYDay) }}
              {{ formatCompany_(multiStation.importKwhDiffYDay) }}
            </div>
            <div class="overview_line" v-else>
              {{ $t("overview.belowYesterday") }}: {{ formatAmountkwh_(multiStation.importKwhDiffYDay) }}
              {{ formatCompany_(multiStation.importKwhDiffYDay) }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("overview.Charging") }}: {{ formatAmountkwh(multiStation.monthImportKwh) }}
              {{ formatCompany(multiStation.monthImportKwh) }} | {{ $t("overview.TotalCharging") }}:
              {{ formatAmountkwh(multiStation.accumulativeImportKwh) }}
              {{ formatCompany(multiStation.accumulativeImportKwh) }}
            </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">{{ $t("overview.TodayDischarge") }}</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">
                {{ formatAmountkwh(multiStation.dayExportKwh) }}
                <span class="overview_unit"> {{ formatCompany(multiStation.dayExportKwh) }}</span>
              </div>
              <div class="overview_img2">
                <img src="../../assets/images/discharge.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line" v-if="multiStation.exportKwhDiffYDay > 0">
              {{ $t("overview.upperYesterday") }}: {{ formatAmountkwh_(multiStation.exportKwhDiffYDay) }}
              {{ formatCompany_(multiStation.exportKwhDiffYDay) }}
            </div>
            <div class="overview_line" v-else>
              {{ $t("overview.belowYesterday") }}: {{ formatAmountkwh_(multiStation.exportKwhDiffYDay) }}
              {{ formatCompany_(multiStation.exportKwhDiffYDay) }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("overview.Discharge") }}: {{ formatAmountkwh(multiStation.monthExportKwh) }}
              {{ formatCompany(multiStation.monthExportKwh) }} | {{ $t("overview.discharge") }}:
              {{ formatAmountkwh(multiStation.accumulativeExportKwh) }}
              {{ formatCompany(multiStation.accumulativeExportKwh) }}
            </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">{{ $t("overview.TodayRevenue") }}</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">
                {{ formatAmount(multiStation.todayProfit) }}
                <span class="overview_unit">{{ formatAmounts(multiStation.todayProfit) }}</span>
              </div>
              <div class="overview_img3">
                <img src="../../assets/images/qian.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line" v-if="multiStation.profitDiffYDay > 0">
              {{ $t("overview.upperYesterday") }}: {{ formatAmount1(multiStation.profitDiffYDay) }}
              {{ formatAmounts2(multiStation.profitDiffYDay) }}
            </div>
            <div class="overview_line" v-else>
              {{ $t("overview.belowYesterday") }}: {{ formatAmount1(multiStation.profitDiffYDay) }}
              {{ formatAmounts2(multiStation.profitDiffYDay) }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("overview.MTDRevenue") }}: {{ formatAmount(multiStation.monthProfit) }}
              {{ formatAmounts(multiStation.monthProfit) }} | {{ $t("overview.TotalRevenue") }}:
              {{ formatAmount(multiStation.totalProfit) }}
              {{ formatAmounts(multiStation.totalProfit) }}
            </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">{{ $t("overview.TotalDevices") }}</div>
            </div>
            <div class="overview_title">
              <div class="overview_titlename">
                {{ multiStation.stationTotalCount }} <span class="overview_unit">{{ $t("type") == "zh" ? "个" : "" }}</span>
              </div>
              <div class="overview_img">
                <img src="../../assets/images/gu1.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line">
              {{ $t("overview.Online") }} {{ multiStation.stationOnlineCount }} {{ $t("type") == "zh" ? "个" : "" }} \
              {{ $t("overview.Offline") }} {{ multiStation.stationOfflineCount }} {{ $t("type") == "zh" ? "个" : "" }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("overview.InstalledPower") }}: {{ formatAmountkwh(multiStation.installedPower) }}
              {{ formatCompany1(multiStation.installedPower) }} | {{ $t("overview.InstalledCapacity") }}:
              {{ formatAmountkwh(multiStation.installedCap) }}
              {{ formatCompany(multiStation.installedCap) }}
            </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="$t('overview.RevenueAnalytics')" name="first"></el-tab-pane>
              <el-tab-pane :label="$t('overview.DischargeStatistics')" name="second"></el-tab-pane>
              <div class="grid_div1">
                <div ref="baroption" id="baroption"></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="timetype1"
                :shortcuts="shortcuts1"
                :format="format1"
                :value-format="format1"
                :start-placeholder="$t('overview.StartTime')"
                :end-placeholder="$t('overview.EndTime')"
                :default-value="value2"
                :disabled-date="pickerOptions"
                size="large"
                @change="onhandleClick"
                :default-time="defaultTime2"
              />
              <el-select
                v-model="daymonthyearvalue1"
                :placeholder="$t('overview.SelectDate')"
                size="large"
                style="width: 80px"
                @change="getdaymonthyear1"
              >
                <el-option v-for="item in daymonthyear1" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="grid_right">
              <div>{{ $t("overview.PlantInformation") }}</div>
              <div class="grid_right1" @click="details()">{{ $t("overview.ViewDetails") }}</div>
            </div>
            <!-- <div id="gridpiechart">-||-</div> -->
            <div class="gridpiechart">
              <img class="gridpiechartimg" :src="stationinfodata.absoluteStationPicUrl" alt="" />
            </div>
            <div class="gridpiechartname">{{ stationinfodata.stationName }}</div>

            <div class="gridpiechartdiv">
              <div class="gridpiechartnameright">{{ $t("overview.TotalInstalledCapacity") }}</div>
              <div class="gridpiechartnameleft">{{ stationinfodata.installedCap }} kWh</div>
            </div>

            <div class="gridpiechartdiv">
              <div class="gridpiechartnameright">{{ $t("overview.RatedPower") }}</div>
              <div class="gridpiechartnameleft">{{ stationinfodata.installedPower }} MW</div>
            </div>
            <div class="gridpiechartdiv">
              <div class="gridpiechartnameright">{{ $t("overview.CommissioningDate") }}</div>
              <div class="gridpiechartnameleft">{{ stationinfodata.operationDate }}</div>
            </div>
            <div class="gridpiechartdiv">
              <div class="gridpiechartnameright">{{ $t("overview.PlantLocation") }}</div>
              <div class="gridpiechartnameleft1">
                <el-icon><Location /></el-icon>&nbsp;<el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="stationinfodata.detailedaddress"
                  placement="left-start"
                >
                  {{ stationinfodata.detailedaddress }}
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="middle">
      <el-card style="width: 100%">
        <div class="middleleft">
          <div class="middlelefttop">
            <div>{{ $t("overview.CompositePower") }}</div>

            <div class="middle_divright">
              <!-- <div :class="timedays == 7 ? 'middle_divright_1' : 'middle_divright_2'" @click="oncomprehen(7)">近7日</div>
              <div :class="timedays == 31 ? 'middle_divright_1' : 'middle_divright_2'" @click="oncomprehen(31)">近31日</div>
              <div :class="timedays == 360 ? 'middle_divright_1' : 'middle_divright_2'" @click="oncomprehen(360)">近12月</div> -->
              <el-date-picker
                v-model="timedayslist"
                :type="pickertype"
                :shortcuts="shortcuts"
                :format="format"
                :value-format="format"
                unlink-panels
                size="large"
                :start-placeholder="$t('overview.StartTime')"
                :end-placeholder="$t('overview.EndTime')"
                :default-value="timedayslist"
                :disabled-date="pickerOptions"
                @change="onpowerblur"
              />
              <!-- <el-select
                v-model="daymonthyearvalue"
                placeholder="选择日期"
                size="large"
                style="width: 80px"
                @change="getdaymonthyear"
              >
                <el-option v-for="item in daymonthyear" :key="item.value" :label="item.label" :value="item.value" />
              </el-select> -->
            </div>
          </div>
          <div class="middleleftchart" ref="comprehensive"></div>
        </div>
      </el-card>
    </div>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ $t("overview.DeviceList") }}</span>
        </div>
      </template>
      <div class="cardtable">
        <div>{{ $t("overview.CommunicationStatus") }}:</div>
        &emsp;
        <el-select v-model="onlineStatus" :placeholder="$t('overview.EndTime')" 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="$t('overview.DeviceID')" size="large" />
        &emsp;
        <el-button type="primary" size="large" color="#0052d9" @click="query(0)">{{ $t("overview.Query") }}</el-button>
        <el-button size="large" @click="query(1)">{{ $t("overview.Reset") }}</el-button>
      </div>
      <el-table :data="tableData.records" style="width: 100%" border :scrollbar-always-on="true">
        <el-table-column type="index" :label="$t('overview.SNo')" width="60" />
        <el-table-column prop="eid" :label="$t('overview.DeviceID')" width="160" :show-overflow-tooltip="true" />
        <el-table-column prop="emsDeviceId" :label="$t('overview.DeviceName')" width="160" :show-overflow-tooltip="true" />
        <el-table-column prop="onlineStatus" :label="$t('overview.OnlineStatus')" width="160">
          <template #default="scope">
            {{ scope.row.onlineStatus == 0 ? $t("overview.Offline") : $t("overview.Online") }}
          </template>
        </el-table-column>
        <el-table-column prop="dayImportKwh" :label="$t('overview.TodayCharging')" width="160" />
        <el-table-column prop="dayExportKwh" :label="$t('overview.TodaysDischarge')" width="160" />
        <el-table-column prop="accumulativeImportKwh" :label="$t('overview.TotalCharged')" width="160" />
        <el-table-column prop="accumulativeExportKwh" :label="$t('overview.TotalDischarged')" width="160" />
        <el-table-column prop="soc" label="SOC(%)" width="160" />
        <el-table-column prop="todayAlarmCount" :label="$t('overview.Maintenance')" align="center" width="160">
          <template #default="scope">
            {{ scope.row.todayAlarmCount == null ? "-" : scope.row.todayAlarmCount }}
          </template>
        </el-table-column>

        <el-table-column prop="gridActivePower" :label="$t('overview.GridActivePower')" width="160" />
        <el-table-column prop="storageActivePower" :label="$t('overview.ESSActivePower')" width="160" />
        <el-table-column prop="loadActivePower" :label="$t('overview.LoadActivePower')" width="160" />
      </el-table>
      <div class="example_block">
        <Pagination :pageable="pageable" :handle-size-change="handleSizeChange" :handle-current-change="handleCurrentChange" />
        <!-- <el-pagination layout="prev, pager, next" :total="tableData.total" @change="changemultiStationpagebase" /> -->
      </div>
    </el-card>
    <el-dialog v-model="dialogVisible" title="查看电站" width="800" :before-close="handleClose">
      <div class="dialog">
        <div :class="informationtype == 1 ? 'information' : 'more'" @click="oninformation">
          {{ $t("overview.BasicInformation") }}
        </div>
        <div :class="informationtype == 2 ? 'information' : 'more'" @click="onmoreinformation">
          {{ $t("overview.MoreDetails") }}
        </div>
      </div>
      <div v-if="informationtype == 1">
        <div class="more_img">
          <div class="more_name">{{ $t("overview.PlantPhotos") }}：</div>
          <img class="dialogimg" :src="stationinfodata.absoluteStationPicUrl" alt="" />
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.PlantName") }}：</div>
          <div class="more_theme">{{ stationinfodata.stationName }}</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.InstalledPower") }}：</div>
          <div class="more_theme">{{ stationinfodata.installedPower }}MW</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.InstalledCapacity") }}：</div>
          <div class="more_theme">{{ stationinfodata.installedCap }}kWh</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.PlantLocation") }}：</div>
          <div class="more_theme">{{ stationinfodata.province }}</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.CommissioningDate") }}：</div>
          <div class="more_theme">{{ stationinfodata.operationDate }}</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.ContactNumber") }}：</div>
          <div class="more_theme">{{ stationinfodata.contactPhone }}</div>
        </div>
      </div>
      <div v-if="informationtype == 2">
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.InstallationPhotos") }}：</div>
          <div class="more_theme">-</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.GridConnectionInfo") }}：</div>
          <div class="more_theme">-</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.TransformerSpecifications") }}：</div>
          <div class="more_theme">-</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.TransformerCapacity") }}：</div>
          <div class="more_theme">-</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.Installer") }}：</div>
          <div class="more_theme">-</div>
        </div>
        <div class="dialog_title">
          <div class="more_name">{{ $t("overview.InstallerContact") }}：</div>
          <div class="more_theme">-</div>
        </div>
      </div>
      <div class="dialog_footer">
        <el-button @click="dialogVisible = false" size="large">{{ $t("overview.Close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<!--    -->
<script setup lang="ts">
import { onMounted, Ref, ref } from "vue";
import type { TabsPaneContext } from "element-plus";
import * as echarts from "echarts";
import Pagination from "@/components/ProTable/components/Pagination.vue";

import {
  getmuitiStation,
  emsSystempage,
  stationstationName,
  postsexportKwh,
  singlestationday,
  singlestationyearMonth,
  singlestationchargingMonth,
  overallEfficiencyday,
  // overallEfficiencyyearMonth,
  Stationinfo,
  singlestationdayMonth,
  postsexportKwhMonth
} from "@/api/home/Multisite";
import { Station } from "@/api/interface";
import { useRoute } from "vue-router";
const route = useRoute();

const multiStation = ref();
const activeName = ref("first");
const value2 = ref();
const tableData = ref();
const currentDate = ref();
const baroption = ref();
const modelinput = ref();
const pageable = ref({
  ps: 10,
  pn: 1,
  total: 0
});
// 选择站点
const Singlevalue = ref();
const Singledata = ref([]);
const onselect = (val: any) => {
  activeName.value = "first";
  Singledata.value = val.id;
  getStationinfo();
  // gatsinglestationday();
  postmultiStationpagebaseInfo();
  onhandleClick();
  getsite();
  onpowerblur();
};

const cities: Ref<Station.todo[]> = ref([]);

const onlineStatus = ref("");
// const recentlytype = ref(7);
const tabpropslabel = ref("收益统计");

const options = ref([
  {
    value: "",
    label: "全部"
  },
  {
    value: "1",
    label: "在线"
  },
  {
    value: "0",
    label: "离线"
  }
]);

const poststationstationName = async () => {
  const { data } = await stationstationName({});
  if (route.query.powerId) {
    Singlevalue.value = route.query.powerId;
  } else {
    Singlevalue.value = data[0].id;
  }

  cities.value = data;
  getsite();
  getStationinfo();
  gatsinglestationday();
  postmultiStationpagebaseInfo();
  onpowerblur();

  // oncomprehen(7);
};
// 选择站点
const getsite = async () => {
  console.log(Singlevalue.value);
  const { data } = await getmuitiStation(Singlevalue.value);
  multiStation.value = data;
};
// 站点信息 查看详细
const stationinfodata = ref();
const getStationinfo = async () => {
  const { data } = await Stationinfo({}, Singlevalue.value);
  stationinfodata.value = data;
};
const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};
const defaultTime2: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 56, 56)]; // '00:00:00', '23:56:56'
// 查询最近数据

const getdaymonthyear1 = async (value: any) => {
  daymonthyearvalue.value = value;
  if (value == 1) {
    timetype1.value = "daterange";
    format1.value = "YYYY-MM-DD";
    shortcuts1.value = [
      {
        text: "过去7天",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setDate(start.getDate() - 7);
          return [start, end];
        }
      },
      {
        text: "过去1个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 1);
          return [start, end];
        }
      },
      {
        text: "过去3个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 3);
          return [start, end];
        }
      }
    ];

    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    const sevenDaysAgoDate = new Date(today);
    sevenDaysAgoDate.setDate(today.getDate() - 7);
    // const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();
    const year = sevenDaysAgoDate.getFullYear();
    const month = String(sevenDaysAgoDate.getMonth() + 1).padStart(2, "0"); // Months are zero-based
    const day = String(sevenDaysAgoDate.getDate()).padStart(2, "0");

    // Format the date as "YYYY-MM-DD"
    const formattedDate = `${year}-${month}-${day}`;
    value2.value = [formattedDate, currentDate];

    // getreportpowerday();
  } else if (value == 2) {
    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    const currentYearMonth = currentDate.slice(0, 7);

    value2.value = [currentYearMonth, currentYearMonth];
    // getreportpoweryearMonth();

    timetype1.value = "monthrange";
    format1.value = "YYYY-MM";

    shortcuts1.value = [
      {
        text: "本月",
        value: () => {
          return [new Date(), new Date()];
        }
      },
      {
        text: "过去6个月",
        value: () => {
          const end = new Date();
          const start = new Date();
          start.setMonth(start.getMonth() - 6);
          return [start, end];
        }
      },
      {
        text: "今年",
        value: () => {
          const end = new Date();
          const start = new Date(new Date().getFullYear(), 0);
          return [start, end];
        }
      }
    ];
  } else {
    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    // 获取去年同月的日期
    value2.value = [currentDate.substring(0, 4), currentDate.substring(0, 4)];
    console.log(value2.value);
    timetype1.value = "yearrange";
    format1.value = "YYYY";

    shortcuts1.value = [
      {
        text: "今年",
        value: () => {
          return [new Date(), new Date()];
        }
      },
      {
        text: "过去1年",
        value: () => {
          const end = new Date();
          const start = new Date(new Date().setFullYear(new Date().getFullYear() - 1));
          return [start, end];
        }
      },
      {
        text: "过去2年",
        value: () => {
          const start = new Date();
          const end = new Date(new Date().setFullYear(new Date().getFullYear() - 2));
          return [start, end];
        }
      }
    ];
  }
  if (tabpropslabel.value == "收益统计") {
    if (daymonthyearvalue.value == 1) {
      gatsinglestationday();
    } else if (daymonthyearvalue.value == 2) {
      getsinglestationdayMonth();
    } else {
      gatsinglestationyearMonth();
    }
  } else {
    if (daymonthyearvalue.value == 1) {
      getmultiStatiopower();
    } else if (daymonthyearvalue.value == 2) {
      getpostsexportKwhMonth();
    } else {
      getsinglestationchargingMonth();
    }
  }
};
// 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];
//       gatsinglestationday();
//     } else if (val == 31) {
//       value2.value = [thirtyOneDaysAgo, currentDate];
//       gatsinglestationday();
//     } else {
//       value2.value = [lastYearSameMonth, currentDate];
//       gatsinglestationyearMonth();
//     }
//   } else {
//     if (val == 7) {
//       value2.value = [sevenDaysAgo, currentDate];
//       getmultiStatiopower();
//     } else if (val == 31) {
//       value2.value = [thirtyOneDaysAgo, currentDate];
//       getmultiStatiopower();
//     } else {
//       value2.value = [lastYearSameMonth, currentDate];
//       getsinglestationchargingMonth();
//     }
//   }
// };

// 切换收益统计与充放电统计
const handleClick = (tab: TabsPaneContext) => {
  tabpropslabel.value = tab.props.label;

  if (tabpropslabel.value == "收益统计") {
    if (daymonthyearvalue.value == 1) {
      gatsinglestationday();
    } else if (daymonthyearvalue.value == 2) {
      getsinglestationdayMonth();
    } else {
      gatsinglestationyearMonth();
    }
  } else {
    if (daymonthyearvalue.value == 1) {
      getmultiStatiopower();
    } else if (daymonthyearvalue.value == 2) {
      getpostsexportKwhMonth();
    } else {
      getsinglestationchargingMonth();
    }
  }
};
const onhandleClick = () => {
  if (tabpropslabel.value == "收益统计") {
    if (daymonthyearvalue.value == 1) {
      gatsinglestationday();
    } else if (daymonthyearvalue.value == 2) {
      getsinglestationdayMonth();
    } else {
      gatsinglestationyearMonth();
    }
  } else {
    if (daymonthyearvalue.value == 1) {
      getmultiStatiopower();
    } else if (daymonthyearvalue.value == 2) {
      getpostsexportKwhMonth();
    } else {
      getsinglestationchargingMonth();
    }
  }
};
// 收益统计----日
const listday = ref([
  {
    ymd: "2025-02-12",
    profit: 1
  },
  {
    ymd: "2025-02-13",
    profit: 1
  },
  {
    ymd: "2025-02-14",
    profit: 1
  },
  {
    ymd: "2025-02-15",
    profit: 1
  },
  {
    ymd: "2025-02-16",
    profit: 1
  },
  {
    ymd: "2025-02-17",
    profit: 1
  },
  {
    ymd: "2025-02-18",
    profit: 1
  }
]);

const gatsinglestationday = async () => {
  const { data } = await singlestationday({ startDate: value2.value[0], endDate: value2.value[1] }, Singlevalue.value);
  const dates = [["product", "收益"]];

  if (data.list.length < 1) {
    data.list.push(...listday.value);
  }
  for (let index = 0; index < data.list.length; index++) {
    dates.push([data.list[index].ymd, data.list[index].profit.toFixed()]);
  }

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

  baroptionchart(dates, profits, "收益/元");
};
// 收益统计----月
const getsinglestationdayMonth = async () => {
  const { data } = await singlestationdayMonth({ startDate: value2.value[0], endDate: value2.value[1] }, Singlevalue.value);
  const dates = [["product", "收益"]];
  if (data.list.length < 1) {
    data.list.push(...listday.value);
  }
  for (let index = 0; index < data.list.length; index++) {
    dates.push([data.list[index].ymd, data.list[index].profit.toFixed()]);
  }

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

  baroptionchart(dates, profits, "收益/元");
};
// 收益统计------年份
const gatsinglestationyearMonth = async () => {
  const { data } = await singlestationyearMonth(
    { startYearMonth: value2.value[0], endYearMonth: value2.value[1] },
    Singlevalue.value
  );
  const dates = [["product", "收益"]];
  if (data.list.length < 1) {
    data.list.push(...listday.value);
  }
  for (let index = 0; index < data.list.length; index++) {
    dates.push([data.list[index].ymd, data.list[index].profit.toFixed()]);
  }
  const profits = [{ type: "bar" }];

  baroptionchart(dates, profits, "收益/元");
};
// 充放电统计图
const TotalKwh = ref([
  {
    ymd: "2025-02-12",
    chargeTotal: 1,
    dischargeTotal: 0.5
  },
  {
    ymd: "2025-02-13",
    chargeTotal: 1,
    dischargeTotal: 0.5
  },
  {
    ymd: "2025-02-14",
    chargeTotal: 1,
    dischargeTotal: 0.5
  },
  {
    ymd: "2025-02-15",
    chargeTotal: 1,
    dischargeTotal: 0.5
  },
  {
    ymd: "2025-02-16",
    chargeTotal: 1,
    dischargeTotal: 0.5
  },
  {
    ymd: "2025-02-17",
    chargeTotal: 1,
    dischargeTotal: 0.5
  },
  {
    ymd: "2025-02-18",
    chargeTotal: 1,
    dischargeTotal: 0.5
  }
]);
const getmultiStatiopower = async () => {
  const { data } = await postsexportKwh({ startDate: value2.value[0], endDate: value2.value[1] }, Singlevalue.value);
  const dates = [["product", "充电", "放电"]];
  if (data.length < 1) {
    data.push(...TotalKwh.value);
  }
  for (let index = 0; index < data.length; index++) {
    dates.push([data[index].ymd, data[index].chargeTotal.toString(), data[index].dischargeTotal.toString()]);
  }
  const profits = [{ type: "bar" }, { type: "bar" }];

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

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

  baroptionchart(dates, profits, "kWh");
};
// 收益统计
const baroptionchart = (dates: string[][], profits: { type: string }[], subtext: string | undefined) => {
  const baroptionvalue = echarts.init(baroption.value);
  window.addEventListener(
    "resize",
    () => {
      baroptionvalue.resize();
    },
    false
  );
  let option = {
    title: {
      subtext: subtext
    },
    legend: {
      right: 30
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    grid: {
      left: "1%",
      right: "4%",
      bottom: "0%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      axisLabel: {}
    },
    yAxis: {
      type: "value"
    },
    dataset: {
      source: dates
    },
    series: profits
  };

  baroptionvalue.setOption(option, true);
};
// 查询
const query = async (val: number) => {
  if (val == 0) {
    postmultiStationpagebaseInfo();
  } else {
    pageable.value.ps = 1;
    onlineStatus.value = "";
    modelinput.value = "";
    postmultiStationpagebaseInfo();
  }
};
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 emsSystempage(
    {
      onlineStatus: onlineStatus.value,
      keyword: modelinput.value,
      pn: pageable.value.ps,
      ps: pageable.value.pn
    },
    Singlevalue.value
  );
  tableData.value = data;
  console.log(tableData.value.total);

  pageable.value.total = tableData.value.total;
};
const dialogVisible = ref(false);
// 卡片详情对话框
const details = () => {
  dialogVisible.value = true;
};
const informationtype = ref(1);
const oninformation = () => {
  informationtype.value = 1;
};
const onmoreinformation = () => {
  informationtype.value = 2;
};
const handleClose = () => {
  dialogVisible.value = false;
};
// 综合效率---------------------------------------------------------------
const comprehensive = ref();
// const timedays = ref(7);
const timedayslist = ref();
const pickertype: Ref<any> = ref("daterange");
const daymonthyearvalue = ref(1);
const daymonthyearvalue1 = ref(1);
const timetype1: Ref<any> = ref("daterange");
const format = ref("YYYY-MM-DD");
const format1 = ref("YYYY-MM-DD");

const daymonthyear1 = ref([
  {
    value: 1,
    label: "按日"
  },
  {
    value: 2,
    label: "按月"
  },
  {
    value: 3,
    label: "按年"
  }
]);
const shortcuts = ref([
  {
    text: "过去7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    }
  },
  {
    text: "过去1个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    }
  },
  {
    text: "过去3个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    }
  }
]);
const shortcuts1 = ref([
  {
    text: "过去7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 7);
      return [start, end];
    }
  },
  {
    text: "过去1个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 1);
      return [start, end];
    }
  },
  {
    text: "过去3个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(start.getMonth() - 3);
      return [start, end];
    }
  }
]);
const onpowerblur = () => {
  getdaymonthyear();
};
const getdaymonthyear = async () => {
  // daymonthyearvalue.value = value;
  getcomprehensiveefficiency();

  // if (daymonthyearvalue.value == 1) {
  //   getcomprehensiveefficiency();
  // } else if (daymonthyearvalue.value == 2) {
  // } else {
  //   getoverallEfficiencyyearMonth();
  // }
};
// const oncomprehen = (val: number) => {
//   // 获取当前日期
//   timedays.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 (val == 7) {
//     timedayslist.value = [sevenDaysAgo, currentDate];
//     getcomprehensiveefficiency();
//   } else if (val == 31) {
//     timedayslist.value = [thirtyOneDaysAgo, currentDate];
//     getcomprehensiveefficiency();
//   } else {
//     timedayslist.value = [lastYearSameMonth, currentDate];
//     getoverallEfficiencyyearMonth();
//   }
// };
const getcomprehensiveefficiency = async () => {
  const { data } = await overallEfficiencyday(
    { startDate: timedayslist.value[0], endDate: timedayslist.value[1] },
    Singlevalue.value
  );
  const dates = [["profit", "综合效率"]];

  for (let index = 0; index < data.list.length; index++) {
    dates.push([data.list[index].ymd, data.list[index].overallEfficiency.toString()]);
  }
  const profits = [
    {
      type: "line",
      showSymbol: false
    }
  ];

  getiveefficiency(data.avgEfficiency, dates, profits);
};
// const getoverallEfficiencyyearMonth = async () => {
//   const { data } = await overallEfficiencyyearMonth(
//     {
//       startYearMonth: timedayslist.value[0],
//       endYearMonth: timedayslist.value[1]
//     },
//     Singlevalue.value
//   );
//   const dates = [["profit", "综合效率"]];
//   for (let index = 0; index < data.list.length; index++) {
//     dates.push([data.list[index].ymd, data.list[index].overallEfficiency.toString()]);
//   }
//   const profits = [
//     {
//       type: "line",
//       showSymbol: false
//     }
//   ];

//   getiveefficiency(data.avgEfficiency, dates, profits);
// };
const getiveefficiency = (num: any, dates: string[][], profits: { type: string }[]) => {
  const comprehensivevalue = echarts.init(comprehensive.value);
  window.addEventListener(
    "resize",
    () => {
      comprehensivevalue.resize();
    },
    false
  );
  let option = {
    title: {
      text: `综合效率${num}%`,
      subtext: "效率/%"
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      right: 30
    },
    grid: {
      left: "2%",
      right: "4%",
      bottom: "10%",
      containLabel: true
    },
    xAxis: {
      type: "category"
    },
    yAxis: {
      type: "value"
    },
    dataZoom: [
      {
        type: "inside",
        xAxisIndex: [0, 1],
        start: 0,
        end: 100
      },
      {
        show: true,
        xAxisIndex: [0, 1],
        type: "slider",
        bottom: 10,
        start: 0,
        end: 100
      }
    ],
    dataset: {
      source: dates
    },
    series: profits
  };

  comprehensivevalue.setOption(option, true);
};
// 综合效率---------------------------------------------------------------

// 充电量进位
const formatAmountkwh = (amount: number) => {
  if (amount == undefined) {
    return "1000";
  }
  if (amount < 1000) {
    return amount.toFixed(2);
  } else {
    return (amount / 1000).toFixed(2);
  }
};
const formatCompany1 = (amount: number) => {
  if (amount == undefined) {
    return "kW";
  }
  if (amount < 1000) {
    return "kW";
  } else {
    return "MW";
  }
};
const formatCompany = (amount: number) => {
  if (amount == undefined) {
    return "kWh";
  }
  if (amount < 1000) {
    return "kWh";
  } else {
    return "MWh";
  }
};
const formatAmountkwh_ = (amount: number) => {
  if (amount == undefined) {
    return "1000";
  }
  if (amount > 0) {
    return amount.toFixed(2);
  } else {
    return Math.abs(amount).toFixed(2);
  }
};
const formatCompany_ = (amount: number) => {
  if (amount == undefined) {
    return "kWh";
  }
  if (amount > 0) {
    return "kWh";
  } else {
    return "kWh";
  }
};
const formatAmount = (amount: number) => {
  if (amount == undefined) {
    return "1000";
  }
  if (amount < 10000) {
    return amount.toFixed(2);
  } else {
    return (amount / 10000).toFixed(2);
  }
};
const formatAmounts = (amount: number) => {
  if (amount == undefined) {
    return "元";
  }
  if (amount < 10000) {
    return "元";
  } else {
    return "万元";
  }
};
const formatAmount1 = (amount: number) => {
  if (amount == undefined) {
    return "1000";
  }
  if (amount > -10000) {
    return amount.toFixed(2);
  } else {
    return (amount / 10000).toFixed(2);
  }
};
const formatAmounts2 = (amount: number) => {
  if (amount == undefined) {
    return "元";
  }
  if (amount > -10000) {
    return "元";
  } else {
    return "万元";
  }
};
onMounted(() => {
  const current = localStorage.getItem("currentDate");
  if (current) {
    currentDate.value = current;
  }
  // 获取过去 7 天的日期
  const today = new Date();
  const sevenDaysAgoDate = new Date(today);
  sevenDaysAgoDate.setDate(today.getDate() - 7);
  // const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();

  // Get year, month, and day components
  const year = sevenDaysAgoDate.getFullYear();
  const month = String(sevenDaysAgoDate.getMonth() + 1).padStart(2, "0"); // Months are zero-based
  const day = String(sevenDaysAgoDate.getDate()).padStart(2, "0");

  // Format the date as "YYYY-MM-DD"
  const formattedDate = `${year}-${month}-${day}`;
  value2.value = [formattedDate, currentDate.value];
  timedayslist.value = [formattedDate, currentDate.value];

  poststationstationName();
});
</script>

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