<template>
  <div>
    <div class="title">
      {{ $t("home.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">{{ $t("home.TotalSites") }}</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/server2.png" alt="站点" />
              </div>
            </div>
            <div class="overview_line">
              {{ $t("home.online") }} {{ multiStation.stationOnlineCount }} {{ $t("type") == "zh" ? "个" : "" }} \
              {{ $t("home.offline") }} {{ multiStation.stationOfflineCount }} {{ $t("type") == "zh" ? "个" : "" }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("home.InstalledPower") }}: {{ formatAmountkwh(multiStation.installedPower) }}
              {{ formatCompany1(multiStation.installedPower) }} | {{ $t("home.InstalledCapacity") }}:
              {{ formatAmountkwh(multiStation.installedCap) }} {{ formatCompany(multiStation.installedCap) }}
            </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("home.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("home.upperYesterday") }}: {{ formatAmountkwh_(multiStation.importKwhDiffYDay) }}
              {{ formatCompany_(multiStation.importKwhDiffYDay) }}
            </div>
            <div class="overview_line" v-else>
              {{ $t("home.belowYesterday") }}: {{ formatAmountkwh_(multiStation.importKwhDiffYDay) }}
              {{ formatCompany_(multiStation.importKwhDiffYDay) }}
            </div>

            <el-divider />
            <div class="overview_line">
              {{ $t("home.Charging") }} : {{ formatAmountkwh(multiStation.monthImportKwh) }}
              {{ formatCompany(multiStation.monthImportKwh) }} | {{ $t("home.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("home.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("home.upperYesterday") }}: {{ formatAmountkwh_(multiStation.exportKwhDiffYDay) }}
              {{ formatCompany_(multiStation.exportKwhDiffYDay) }}
            </div>
            <div class="overview_line" v-else>
              {{ $t("home.belowYesterday") }}: {{ formatAmountkwh_(multiStation.exportKwhDiffYDay) }}
              {{ formatCompany_(multiStation.exportKwhDiffYDay) }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("home.Discharge") }}: {{ formatAmountkwh(multiStation.monthExportKwh) }}
              {{ formatCompany(multiStation.monthExportKwh) }} | {{ $t("home.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("home.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("home.upperYesterday") }}: {{ formatAmount1(multiStation.profitDiffYDay) }}
              {{ formatAmounts2(multiStation.profitDiffYDay) }}
            </div>
            <div class="overview_line" v-else>
              {{ $t("home.belowYesterday") }}: {{ formatAmount1(multiStation.profitDiffYDay) }}
              {{ formatAmounts2(multiStation.profitDiffYDay) }}
            </div>
            <el-divider />
            <div class="overview_line">
              {{ $t("home.MTDRevenue") }}: {{ formatAmount(multiStation.monthProfit) }}
              {{ formatAmounts(multiStation.monthProfit) }} | {{ $t("home.TotalRevenue") }}:
              {{ formatAmount(multiStation.totalProfit) }} {{ formatAmounts(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: 60%" 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)">日</div>
              <div :class="recentlytype == 31 ? 'grid_divright_1' : 'grid_divright_2'" @click="recently(31)">月</div>
              <div :class="recentlytype == 360 ? 'grid_divright_1' : 'grid_divright_2'" @click="recently(360)">年</div> -->
              <el-date-picker
                v-model="value2"
                :type="timetype"
                :shortcuts="shortcuts"
                :start-placeholder="$t('home.StartTime')"
                :end-placeholder="$t('home.EndTime')"
                :default-value="value2"
                :format="format"
                :value-format="format"
                unlink-panels
                size="large"
                :disabled-date="pickerOptions"
                @change="pickerincome"
              />
              <el-select
                v-model="daymonthyearvalue"
                :placeholder="$t('home.SelectDate')"
                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>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="grid-content ep-bg-purple">
            <div class="grid_right">
              <div>{{ $t("home.FaultAlerts") }}</div>
              <div class="grid_right1">{{ $t("home.ViewDetails") }}</div>
            </div>
            <div id="gridpiechart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>{{ $t("home.DeviceList") }}</span>
        </div>
      </template>
      <div class="cardtable">
        <div>{{ $t("home.CommunicationStatus") }}:</div>
        &emsp;
        <el-select v-model="onlineStatus" :placeholder="$t('home.Pleaseselect')" 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('home.Pleaseselect')" size="large" />
        &emsp;
        <el-button type="primary" size="large" color="#0052d9" @click="query(0)">{{ $t("home.Query") }}</el-button>
        <el-button size="large" @click="query(1)">{{ $t("home.Reset") }}</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="$t('home.PlantName')" :show-overflow-tooltip="true" />
        <el-table-column prop="onlineStatus" :label="$t('home.OnlineStatus')">
          <template #default="scope">
            {{ scope.row.onlineStatus == 0 ? $t("home.offline") : $t("home.online") }}
          </template>
        </el-table-column>
        <el-table-column prop="todayChargeCap" :label="$t('home.TodayCharging')" />
        <el-table-column prop="todayDischargeCap" :label="$t('home.TodaysDischarge')" />
        <el-table-column prop="totalChargeCap" :label="$t('home.TotalCharged')" />
        <el-table-column prop="totalDischargeCap" :label="$t('home.TotalDischarged')" />
        <el-table-column prop="todayAlarmCount" :label="$t('home.TodayAlerts')" align="center">
          <template #default="scope">
            {{ scope.row.todayAlarmCount == null ? "-" : scope.row.todayAlarmCount }}
          </template>
        </el-table-column>

        <el-table-column prop="overallEfficiency" :label="$t('home.RoundEfficiency')" />
        <!-- <el-table-column prop="dischargeCompletionRate" label="放电达成率(%)" /> -->
        <!-- <el-table-column prop="yesterdayProfit" label="昨日收益(元)" /> -->
        <el-table-column prop="yesterdayProfit" :label="$t('home.YesterdayRevenue')" align="center">
          <template #default="scope">
            {{ scope.row.yesterdayProfit.toFixed(2) }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="totalProfit" label="总收益(元)" /> .toFixed(2)-->
        <el-table-column prop="totalProfit" :label="$t('home.TotalRevenue')" align="center">
          <template #default="scope">
            {{ scope.row.totalProfit.toFixed(2) }}
          </template>
        </el-table-column>
      </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>
<!-- el-car -->
<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 {
  gethomesite,
  multiStationday,
  multiStationtopday,
  multiStatiopower,
  alarmMultiStation,
  multiStationpagebaseInfo,
  multiStationdayMonth,
  multiStationtopyearMonth,
  multiStatyearMonth,
  multiStatiopowerMonth,
  multiStationtopdayMonth,
  multiStationMonthMonth
} 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 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);
  }
  // if (amount > -1000) {
  //   return amount.toFixed(2);
  // } else {
  //   return (amount / 1000).toFixed(2);
  // }
};
const formatCompany_ = (amount: number) => {
  if (amount == undefined) {
    return "kWh";
  }
  return "kWh";
  // if (amount > -1000) {
  //   return "kWh";
  // } else {
  //   return "MWh";
  // }
};
const formatAmount = (amount: number) => {
  if (amount == undefined) {
    return "0";
  }
  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) => {
  // console.log(amount > -10000);

  if (amount == undefined) {
    return "0";
  }
  if (amount > 0) {
    return amount.toFixed(2);
  } else {
    return Math.abs(amount).toFixed(2);
  }
  // if (amount > -10000) {
  //   return amount.toFixed(2);
  // } else {
  //   return (amount / 10000).toFixed(2);
  // }
};
const formatAmounts2 = (amount: number) => {
  console.log(amount);

  if (amount == undefined) {
    return "元";
  }
  return "元";
  // if (amount > -10000) {
  //   return "元";
  // } else {
  //   return "万元";
  // }
};
const pickerincome = () => {
  // value2.value = [formatDate(value[0]), formatDate(value[1])];

  if (tabpropslabel.value == "收益统计") {
    if (daymonthyearvalue.value == 1) {
      getmultiStation(); // 收益统计图
      getmultiStationtopday(); // 收益排名图
    } else if (daymonthyearvalue.value == 2) {
      // getmultiStation(); // 收益统计图
      // getmultiStationtopday(); // 收益排名图
      getmultiStationMonthMonth();
      getmultiStationtopdayMonth();
    } else {
      getmultiStationMonth(); // 收益统计图
      getmultiStationtopMonth(); // 收益排名图
    }
  } else {
    if (daymonthyearvalue.value == 1) {
      getmultiStatiopower(); // 充放电统计图
    } else if (daymonthyearvalue.value == 2) {
      // getmultiStatiopower(); // 充放电统计图
      getmultisMonth();
    } else {
      getmultiStatiopowerMonth();
    }
  }
};
// const formatDate = (dateString: string | number | Date) => {
//   const date = new Date(dateString);

//   // 提取年、月、日、时、分信息
//   const year = date.getFullYear();
//   const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1，并确保是两位数
//   const day = String(date.getDate()).padStart(2, "0"); // 确保是两位数
//   const hours = String(date.getHours()).padStart(2, "0"); // 确保是两位数
//   const minutes = String(date.getMinutes()).padStart(2, "0"); // 确保是两位数

//   // 拼接成 "YYYY-MM-DD HH:MM" 格式
//   const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;

//   return formattedDate;
// };
const handleClick = (tab: TabsPaneContext) => {
  // if (baroption.value) {
  //   baroption.value.dispose(); //地图图表
  // }
  tabpropslabel.value = tab.props.label;
  pickerincome();
  // if (tab.props.label == "收益统计") {
  //   getmultiStationtopday(); // 收益排名图
  //   getmultiStation();
  // } else {
  //   getmultiStatiopower();
  // }
};
//
const daymonthyearvalue = ref(1);

const daymonthyear = 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 timetype: Ref<any> = ref("daterange");
const format = ref("YYYY-MM-DD");

const getdaymonthyear = async (value: any) => {
  daymonthyearvalue.value = value;
  if (value == 1) {
    timetype.value = "daterange";
    format.value = "YYYY-MM-DD";
    shortcuts.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() - 6);
    // const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();
    const year1 = sevenDaysAgoDate.getFullYear();
    const month1 = String(sevenDaysAgoDate.getMonth() + 1).padStart(2, "0"); // Months are zero-based
    const day1 = String(sevenDaysAgoDate.getDate()).padStart(2, "0");
    const formattedDate = `${year1}-${month1}-${day1}`;

    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();
    timetype.value = "monthrange";
    format.value = "YYYY-MM";

    shortcuts.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);
    timetype.value = "yearrange";
    format.value = "YYYY";

    shortcuts.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];
        }
      }
    ];
    // getreportpoweryear();
  }
  if (tabpropslabel.value == "收益统计") {
    if (daymonthyearvalue.value == 1) {
      getmultiStation(); // 收益统计图
      getmultiStationtopday(); // 收益排名图
    } else if (daymonthyearvalue.value == 2) {
      // getmultiStation(); // 收益统计图
      // getmultiStationtopday(); // 收益排名图
      getmultiStationMonthMonth();
      getmultiStationtopdayMonth();
    } else {
      getmultiStationMonth(); // 收益统计图
      getmultiStationtopMonth(); // 收益排名图
    }
  } else {
    if (daymonthyearvalue.value == 1) {
      getmultiStatiopower(); // 充放电统计图
    } else if (daymonthyearvalue.value == 2) {
      // getmultiStatiopower(); // 充放电统计图
      getmultisMonth();
    } else {
      getmultiStatiopowerMonth();
    }
  }
};
// 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() - 7);
  // const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();
  // const sevenDaysAgo = sevenDaysAgoDate.toLocaleDateString();
  const year1 = sevenDaysAgoDate.getFullYear();
  const month1 = String(sevenDaysAgoDate.getMonth() + 1).padStart(2, "0"); // Months are zero-based
  const day1 = String(sevenDaysAgoDate.getDate()).padStart(2, "0");

  // Format the date as "YYYY-MM-DD"
  const formattedDate = `${year1}-${month1}-${day1}`;
  value2.value = [formattedDate, 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], "0"], [value2.value[1], "0"]);
  }
  const profits = [{ type: "bar" }];

  baroptionchart(dates, profits, "收益/元");
};
// 收益统计图
const getmultiStationMonthMonth = async () => {
  const { data } = await multiStationMonthMonth({ 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], "0"], [value2.value[1], "0"]);
  }
  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, "kWh");
};
// 充放电统计图
const getmultisMonth = async () => {
  const { data } = await multiStatiopowerMonth({ 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, "kWh");
};
// 充放电统计月份
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, "kWh");
};
// 收益统计
const baroptionchart = (dates: string[][], profits: { type: string }[], subtext: string | undefined) => {
  // console.log(dates, profits);

  const baroptionvalue = echarts.init(baroption.value);
  window.addEventListener(
    "resize",
    () => {
      baroptionvalue.resize();
    },
    false
  );
  let option = {
    title: {
      subtext: subtext
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    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) {
    const sortedData = data
      .map(item => ({
        profit: parseFloat(item.profit + "").toFixed(2), // 保留小数点后两位
        stationName: item.stationName
      }))
      .sort((a, b) => parseFloat(a.profit) - parseFloat(b.profit)); // 确保排序时比较为数字

    profitlist = sortedData.map(item => parseFloat(item.profit)); // 转回为数字
    stationNames = sortedData.map(item => item.stationName);
  } else {
    profitlist = [1, 1, 1, 1, 1, 1, 1];
    stationNames = ["演示电站一", "演示电站二", "演示电站三", "演示电站四", "演示电站五", "演示电站六", "演示电站七"];
  }

  baroptionincome(profitlist, stationNames);
};
// 收益排名
const getmultiStationtopdayMonth = async () => {
  const { data } = await multiStationtopdayMonth({ startDate: value2.value[0], endDate: value2.value[1] });
  let profitlist = [];
  let stationNames = [];
  if (data.length != 0) {
    const sortedData = data
      .map(item => ({
        profit: parseFloat(item.profit + "").toFixed(2), // 保留小数点后两位
        stationName: item.stationName
      }))
      .sort((a, b) => parseFloat(a.profit) - parseFloat(b.profit)); // 确保排序时比较为数字

    profitlist = sortedData.map(item => parseFloat(item.profit)); // 转回为数字
    stationNames = sortedData.map(item => item.stationName);
  } else {
    profitlist = [1, 1, 1, 1, 1, 1, 1];
    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: true // 隐藏 X 轴刻度线
      },
      axisTick: {
        // show: true // 隐藏 X 轴刻度线
      },
      splitLine: {
        show: false // 隐藏 x 轴背景刻度线
      }
    },
    yAxis: {
      type: "category",
      position: "right",
      data: profitlist,
      axisLine: {
        show: true // 隐藏 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>
<!-- 

-->
