<template>
  <div>
    <div class="title">
      {{ $t("reportforms.Electricityreport") }}
      <div class="title_time">{{ currentDate }}</div>
    </div>
    <el-card class="price_allocationcard" v-if="false">
      <div class="price_allocation">
        <el-icon><WarningFilled /></el-icon>&ensp; {{ $t("reportforms.summary") }} &ensp;&ensp;&ensp;&ensp;<el-icon>
          <Close />
        </el-icon>
      </div>
    </el-card>
    <el-card>
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="$t('reportforms.SiteSummary')" name="站点汇总">
          <div class="tabdiv">
            <div class="tabpanesite">
              <div class="tabpane">
                <div>{{ $t("reportforms.timeframe") }}：</div>
                <div class="tabpane1">
                  <!-- year -->
                  <el-date-picker
                    v-if="timetype != 'year'"
                    v-model="timepicker"
                    :type="timetype"
                    :shortcuts="shortcuts"
                    :format="format"
                    :value-format="format"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="large"
                    :disabled-date="pickerOptions"
                  />
                  <el-date-picker
                    v-if="timetype == 'year'"
                    v-model="timepicker"
                    type="yearrange"
                    :format="format"
                    :value-format="format"
                    :shortcuts="shortcuts"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    size="large"
                    :disabled-date="pickerOptions"
                  />
                  <!-- <YearPicker
                    v-if="timetype == 'year'"
                    style="width: 300px"
                    ref="statisticPicker"
                    :label-width="50"
                    :shortcuts="shortcuts"
                    :init-year="dateValue"
                    :start-year1="timepicker[0]"
                    :end-year2="timepicker[1]"
                    @update-time-range="updateStatisticYear"
                  /> -->
                  <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>
                &ensp;&ensp;
                <el-button type="primary" size="large" color="#0052d9" @click="gatSummary">{{
                  $t("reportforms.Query")
                }}</el-button>
                <el-button size="large" @click="onreset">{{ $t("reportforms.Reset") }}</el-button>
              </div>

              <div class="exportright" v-if="BUTTONS.export">
                <el-dropdown trigger="click" :hide-on-click="false" @visible-change="onclose">
                  <el-button size="large" type="primary" plain>{{ $t("reportforms.export") }}</el-button>
                  <template #dropdown>
                    <el-dropdown-menu v-for="(item, index) in columnList" :key="index">
                      <el-dropdown-item>
                        <el-checkbox @change="oncheck" v-model="item.ifcolumn" :label="item.label" size="large" />
                        <template v-if="item.children">
                          <template v-for="(items, i) in item.children" :key="i">
                            <el-checkbox @change="onchildren" v-model="items.ifcolumn" :label="items.label" size="large" />
                          </template>
                        </template>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                    <div class="dropdown">
                      <el-button @click="onexport" type="primary" plain>{{ $t("reportforms.export") }}</el-button>
                    </div>
                  </template>
                </el-dropdown>
              </div>
            </div>
            &ensp;&ensp;
            <el-table :data="tableData.list" style="width: 100%" align="center" :show-overflow-tooltip="true">
              <!-- <el-table-column type="selection" width="55" /> -->
              <template v-for="(item, index) in columnList" :key="index">
                <el-table-column v-if="item.ifcolumn" :label="item.label" :prop="item.prop" align="center">
                  <template v-if="item.children">
                    <template v-for="(items, i) in item.children" :key="i">
                      <el-table-column v-if="items.ifcolumn" :label="items.label" :prop="items.prop" align="center">
                      </el-table-column>
                    </template>
                  </template>
                </el-table-column>
              </template>
              <!-- <el-table-column prop="stationName" label="站点名称" width="150" align="center" />
              <el-table-column label="充电量(kWh)" align="center">
                <el-table-column prop="chargeSharp" label="尖" align="center" />
                <el-table-column prop="chargePeak" label="峰" align="center" />
                <el-table-column prop="chargeShoulder" label="平" align="center" />
                <el-table-column prop="chargeValley" label="谷" align="center" />
                <el-table-column prop="chargeTotal" label="总" align="center" />
              </el-table-column>
              <el-table-column label="放电量(kWh)" align="center">
                <el-table-column prop="dischargeSharp" label="尖" align="center" />
                <el-table-column prop="dischargePeak" label="峰" align="center" />
                <el-table-column prop="dischargeShoulder" label="平" align="center" />
                <el-table-column prop="dischargeValley" label="谷" align="center" />
                <el-table-column prop="dischargeTotal" label="总" align="center" />
              </el-table-column>
              <el-table-column prop="overallEfficiency" label="综合效率(%)" width="150" align="center" /> -->
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('reportforms.Singlereport')" name="单站报表">
          <div class="tabpane">
            <div class="tabpane_1">{{ $t("reportforms.reporttype") }}：</div>
            <!-- <div :class="reportformsindex == 1 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(1)">时段报表</div> -->
            <div :class="reportformsindex == 2 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(2)">
              {{ $t("reportforms.dailyreport") }}
            </div>
            <div :class="reportformsindex == 3 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(3)">
              {{ $t("reportforms.Monthlyreport") }}
            </div>
            <div :class="reportformsindex == 4 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(4)">
              {{ $t("reportforms.annualreport") }}
            </div>
          </div>
          <div class="tabpanesite">
            <div class="selectsite">
              <div class="tabpane_1">{{ $t("reportforms.selectsite") }}：</div>
              <el-select
                v-model="Singlevalue"
                :placeholder="$t('reportforms.selectsite')"
                size="large"
                style="width: 240px"
                @change="postemsDevice"
              >
                <el-option v-for="item in cities" :key="item.id" :label="item.stationName" :value="item.id" />
              </el-select>
              &ensp;&ensp;&ensp;&ensp; &ensp;&ensp;
              <div class="tabpane_1">{{ $t("reportforms.SelectDate") }}：</div>
              <div>
                <el-date-picker
                  v-if="pickertype != 'year'"
                  v-model="starttime"
                  :type="pickertype"
                  :shortcuts="shortcuts"
                  :format="format"
                  :value-format="format"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  size="large"
                  clearable
                  :disabled-date="pickerOptions"
                />
                <el-date-picker
                  v-if="pickertype == 'year'"
                  v-model="starttime"
                  type="yearrange"
                  :format="format"
                  :value-format="format"
                  :shortcuts="shortcuts"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  size="large"
                  :disabled-date="pickerOptions"
                />
                <!-- <YearPicker
                  v-if="pickertype == 'year'"
                  style="width: 300px"
                  ref="statisticPicker"
                  :label-width="50"
                  :init-year="dateValue"
                  :start-year1="starttime[0]"
                  :end-year2="starttime[1]"
                  @update-time-range="updateStatisticYear1"
                /> -->
              </div>
              &ensp;&ensp;

              <el-button type="primary" size="large" color="#0052d9" @click="onselectsite">{{
                $t("reportforms.Query")
              }}</el-button>
              <el-button size="large" @click="onselectreset">{{ $t("reportforms.Reset") }}</el-button>
              &ensp;&ensp;
            </div>

            <!-- <div style="margin-left: 14px" v-if="BUTTONS.export">
              <el-button size="large" @click="singleexport" type="primary" plain v-if="reportformsindex != 1">导出</el-button>
            </div> -->
            <div class="exportright" v-if="BUTTONS.export && reportformsindex != 1">
              <el-dropdown trigger="click" :hide-on-click="false" @visible-change="onsingleclose">
                <el-button size="large" type="primary" plain>{{ $t("reportforms.export") }}</el-button>
                <template #dropdown>
                  <el-dropdown-menu v-for="(item, index) in singlecolumnList" :key="index">
                    <el-dropdown-item>
                      <el-checkbox @change="onsingle" v-model="item.ifcolumn" :label="item.label" size="large" />
                      <template v-if="item.children">
                        <template v-for="(items, i) in item.children" :key="i">
                          <el-checkbox @change="onsinglechildren" v-model="items.ifcolumn" :label="items.label" size="large" />
                        </template>
                      </template>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                  <div class="dropdown">
                    <el-button @click="singleexport" type="primary" plain>{{ $t("reportforms.export") }}</el-button>
                  </div>
                </template>
              </el-dropdown>
            </div>
          </div>
          <!-- <div v-if="reportformsindex == 1"> -->
          <!-- 目前没有--时段数据 -->
          <div v-if="false">
            <div class="tabpane_data">{{ $t("reportforms.perioddata") }}</div>
            <div class="tabpanechart">
              <div :class="chartindex == 1 ? 'tabpane_22' : 'tabpane_11'" @click="onchart(1)">
                <i class="iconfont iconfontfont">&#xeb96;</i>&ensp;{{ $t("reportforms.linechart") }}
              </div>
              <div :class="chartindex == 2 ? 'tabpane_22' : 'tabpane_11'" @click="onchart(2)">
                <i class="iconfont iconfontfont">&#xe663;</i>&ensp;{{ $t("reportforms.barchart") }}
              </div>
              <div :class="chartindex == 3 ? 'tabpane_22' : 'tabpane_11'" @click="onchart(3)">
                <i class="iconfont iconfontfont">&#xeb94;</i>&ensp;{{ $t("reportforms.table") }}
              </div>
            </div>
            <div class="Line_chart" v-if="chartindex == 1">
              <div class="gcurve_title">
                <div class="gcurve_tip"></div>
                <div>{{ $t("reportforms.Peak") }}</div>
                <div class="gcurve_peak"></div>
                <div>{{ $t("reportforms.Shoulder") }}</div>
                <div class="gcurve_flat"></div>
                <div>{{ $t("reportforms.Offpeak") }}</div>
                <div class="gcurve_valley"></div>
                <div>{{ $t("reportforms.Valley") }}</div>
              </div>
              <div class="gcurve_chart">
                <div class="trendchartchart" ref="trendchart"></div>
              </div>
              <div class="gcurve_divider"></div>
            </div>
            <div class="Line_chart" v-if="chartindex == 2">
              <div class="gcurve_title">
                <div class="gcurve_tip"></div>
                <div>{{ $t("reportforms.Peak") }}</div>
                <div class="gcurve_peak"></div>
                <div>{{ $t("reportforms.Shoulder") }}</div>
                <div class="gcurve_flat"></div>
                <div>{{ $t("reportforms.Offpeak") }}</div>
                <div class="gcurve_valley"></div>
                <div>{{ $t("reportforms.Valley") }}</div>
              </div>
              <div class="trendchartchart" ref="columnchart"></div>
            </div>
            <div class="Line_chart" v-if="chartindex == 3">
              <div class="columntable" v-if="tablelist.list">
                <el-table :data="tablelist.list" style="width: 100%" align="center" :show-overflow-tooltip="true">
                  <el-table-column prop="ymdHour" label="时间" width="150" align="center">
                    <template #default="scope">
                      {{ scope.row.ymdHour }}
                    </template>
                  </el-table-column>

                  <el-table-column label="充电量(kWh)" align="center">
                    <el-table-column prop="chargeSharpKwh" :label="$t('reportforms.Valley')" align="center" />
                    <el-table-column prop="chargePeakKwh" :label="$t('reportforms.Shoulder')" align="center" />
                    <el-table-column prop="chargeShoulderKwh" :label="$t('reportforms.Shoulder')" align="center" />
                    <el-table-column prop="chargeValleyKwh" :label="$t('reportforms.Shoulder')" align="center" />
                    <el-table-column prop="chargeKwh" :label="$t('reportforms.Total')" align="center" />
                  </el-table-column>
                  <el-table-column label="放电量(kWh)" align="center">
                    <el-table-column prop="dischargeSharpKwh" :label="$t('reportforms.Valley')" align="center" />
                    <el-table-column prop="dischargePeakKwh" :label="$t('reportforms.Shoulder')" align="center" />
                    <el-table-column prop="dischargeShoulderKwh" :label="$t('reportforms.Shoulder')" align="center" />
                    <el-table-column prop="dischargeValleyKwh" :label="$t('reportforms.Shoulder')" align="center" />
                    <el-table-column prop="dischargeKwh" :label="$t('reportforms.Total')" align="center" />
                  </el-table-column>

                  <el-table-column prop="ymdHour" label="时间" width="150" align="center">
                    <template #default="scope">
                      {{ scope.row.ymdHour }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div class="tabpane_data">{{ $t("reportforms.rawdata") }}</div>
            <div class="tabpane">
              <div :class="rawdataid == 1 ? 'tabpane_22' : 'tabpane_11'" @click="onrawdata(1)">
                {{ $t("reportforms.Dailydata") }}
              </div>
              <div :class="rawdataid == 2 ? 'tabpane_22' : 'tabpane_11'" @click="onrawdata(2)">
                {{ $t("reportforms.Accumulatedata") }}
              </div>
            </div>
            <div class="gcurve_title">
              <div class="gcurve_tip"></div>
              <div>{{ $t("reportforms.Peak") }}</div>
              <div class="gcurve_peak"></div>
              <div>{{ $t("reportforms.Shoulder") }}</div>
              <div class="gcurve_flat"></div>
              <div>{{ $t("reportforms.Offpeak") }}</div>
              <div class="gcurve_valley"></div>
              <div>{{ $t("reportforms.Valley") }}</div>
            </div>
            <div class="gcurve_chart">
              <div class="trendchartchart" ref="rawdatachart"></div>
            </div>
          </div>
          <div class="dailyreport" v-else>
            <el-table :data="betweenyear.list" style="width: 100%" align="center" :show-overflow-tooltip="true">
              <template v-for="(item, index) in singlecolumnList" :key="index">
                <el-table-column v-if="item.ifcolumn" :label="item.label" :prop="item.prop" align="center">
                  <template v-if="item.children">
                    <template v-for="(items, i) in item.children" :key="i">
                      <el-table-column v-if="items.ifcolumn" :label="items.label" :prop="items.prop" align="center">
                      </el-table-column>
                    </template>
                  </template>
                </el-table-column>
              </template>
              <!-- <el-table-column prop="ymdHour" label="数据质量状态" width="150" align="center">
                <template #default="scope">
               
                  <div v-if="scope.row.andTime != '合计'">
                    <div class="abnormal" v-if="scope.row.chargeTotal - scope.row.dischargeTotal > 200">充放数据有异</div>
                    <div class="normal" v-else-if="scope.row.chargeTotal - scope.row.dischargeTotal < 200">充电数据正常</div>
                  </div>
                </template>
              </el-table-column> -->

              <!-- <el-table-column label="日期" width="150" align="center">
                <template #default="scope">
                  <div v-if="scope.row.ymd">{{ scope.row.ymd }}</div>
                  <div v-if="scope.row.ym">{{ scope.row.ym }}</div>
                  <div v-if="scope.row.year">{{ scope.row.year }}</div>
                </template>
              </el-table-column>
              <el-table-column label="充电量(kWh)" align="center">
                <el-table-column prop="chargeSharp" label="尖" align="center" />
                <el-table-column prop="chargePeak" label="峰" align="center" />
                <el-table-column prop="chargeShoulder" label="平" align="center" />
                <el-table-column prop="chargeValley" label="谷" align="center" />
                <el-table-column prop="chargeTotal" label="总" align="center" />
              </el-table-column>
              <el-table-column label="放电量(kWh)" align="center">
                <el-table-column prop="dischargeSharp" label="尖" align="center" />
                <el-table-column prop="dischargePeak" label="峰" align="center" />
                <el-table-column prop="dischargeShoulder" label="平" align="center" />
                <el-table-column prop="dischargeValley" label="谷" align="center" />
                <el-table-column prop="dischargeTotal" label="总" align="center" />
              </el-table-column>
              <el-table-column prop="overallEfficiency" label="综合效率(%)" width="150" align="center" /> -->
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<!--   

 -->
<script setup lang="ts">
import { onMounted, Ref, ref } from "vue";
import {
  reportpowerday,
  stationstationName,
  reportsingleStationline,
  electricitylevelday,
  electricitylevelyearMonth,
  electricitylevelyear,
  reportpoweryearMonth,
  reportpoweryear,
  postemsSystemsingleStation,
  reportsingleStationoriginal,
  singleStationtable,
  Summaryexportday,
  Summaryexportmonth,
  Summaryexportyear,
  betweenbiaoExcel,
  betweenyearMonthExcel,
  betweenyearExcel,
  selectemssytemNameURL
} from "@/api/home/Multisite";
import { useAuthButtons } from "@/hooks/useAuthButtons";
const { BUTTONS } = useAuthButtons();
// import YearPicker from "@/components/year/index.vue";
import * as echarts from "echarts";
import { other, Station } from "@/api/interface";
// 汇总表头
const columnList = ref([
  {
    prop: "stationName",
    label: "日期",
    ifcolumn: true,
    children: null
  },
  {
    prop: "",
    label: "充电量(kWh)",
    ifcolumn: true,
    children: [
      {
        prop: "chargeSharp",
        label: "尖",
        ifcolumn: true
      },
      {
        prop: "chargePeak",
        label: "峰",
        ifcolumn: true
      },
      {
        prop: "chargeShoulder",
        label: "平",
        ifcolumn: true
      },
      {
        prop: "chargeValley",
        label: "谷",
        ifcolumn: true
      },
      {
        prop: "chargeTotal",
        label: "总",
        ifcolumn: true
      }
    ]
  },
  {
    prop: "",
    label: "放电量(kWh)",
    ifcolumn: true,
    children: [
      {
        prop: "dischargeSharp",
        label: "尖",
        ifcolumn: true
      },
      {
        prop: "dischargePeak",
        label: "峰",
        ifcolumn: true
      },
      {
        prop: "dischargeShoulder",
        label: "平",
        ifcolumn: true
      },
      {
        prop: "dischargeValley",
        label: "谷",
        ifcolumn: true
      },
      {
        prop: "dischargeTotal",
        label: "总",
        ifcolumn: true
      }
    ]
  }
  // ,
  // {
  //   prop: "overallEfficiency",
  //   label: "综合效率(%)",
  //   ifcolumn: true,
  //   children: null
  // }
]);
// 单站报表表头
const singlecolumnList = ref([
  {
    prop: "andTime",
    label: "日期",
    ifcolumn: true,
    children: null
  },
  {
    prop: "",
    label: "充电量(kWh)",
    ifcolumn: true,
    children: [
      {
        prop: "chargeSharp",
        label: "尖",
        ifcolumn: true
      },
      {
        prop: "chargePeak",
        label: "峰",
        ifcolumn: true
      },
      {
        prop: "chargeShoulder",
        label: "平",
        ifcolumn: true
      },
      {
        prop: "chargeValley",
        label: "谷",
        ifcolumn: true
      },
      {
        prop: "chargeTotal",
        label: "总",
        ifcolumn: true
      }
    ]
  },
  {
    prop: "",
    label: "放电量(kWh)",
    ifcolumn: true,
    children: [
      {
        prop: "dischargeSharp",
        label: "尖",
        ifcolumn: true
      },
      {
        prop: "dischargePeak",
        label: "峰",
        ifcolumn: true
      },
      {
        prop: "dischargeShoulder",
        label: "平",
        ifcolumn: true
      },
      {
        prop: "dischargeValley",
        label: "谷",
        ifcolumn: true
      },
      {
        prop: "dischargeTotal",
        label: "总",
        ifcolumn: true
      }
    ]
  }
]);
const currentDate = ref();
const activeName = ref("站点汇总");
const timepicker: Ref<any> = ref([]);
//year daterange
const timetype: Ref<any> = ref("daterange");
const handleClick = async (val: any) => {
  if (val.props.name == "站点汇总") {
    getdaymonthyear(1);
    gatSummary();
  } else {
    await poststationstationName();
    await onreportforms(2);
  }
};

// 格式化时间
const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};
// 选择时间
// const datepicker = (val: any) => {
//   console.log(timepicker.value);

//   timepicker.value = [formatDate(val[0]), formatDate(val[1])];
// };
// 选择日期

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 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];
    timepicker.value = [currentDate, currentDate];
    // getreportpowerday();
  } else if (value == 2) {
    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    const currentYearMonth = currentDate.slice(0, 7);

    timepicker.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];
    // 获取去年同月的日期
    timepicker.value = [currentDate.substring(0, 4), currentDate.substring(0, 4)];
    console.log(timepicker.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();
  }
};
// 查询
const gatSummary = () => {
  // getdaymonthyear(daymonthyearvalue.value);
  if (daymonthyearvalue.value == 1) {
    getreportpowerday();
  } else if (daymonthyearvalue.value == 2) {
    getreportpoweryearMonth();
  } else if (daymonthyearvalue.value == 3) {
    getreportpoweryear();
  }
};
// 重置
const onreset = () => {
  getdaymonthyear(1);
};
const onclose = (val: boolean) => {
  console.log(val);
  setTimeout(() => {
    if (!val) {
      for (const column of columnList.value) {
        column.ifcolumn = true;

        if (column.children) {
          for (const child of column.children) {
            child.ifcolumn = true;
          }
        }
      }
    }
  }, 500); // 延迟 0.5毫秒
};
const onsingleclose = (val: boolean) => {
  console.log(val);
  setTimeout(() => {
    if (!val) {
      for (const column of singlecolumnList.value) {
        column.ifcolumn = true;

        if (column.children) {
          for (const child of column.children) {
            child.ifcolumn = true;
          }
        }
      }
    }
  }, 500); // 延迟 0.5毫秒
};
// 点击汇总父元素多选
const oncheck = () => {
  if (columnList.value) {
    for (let index = 0; index < columnList.value.length; index++) {
      const column = columnList.value[index];
      if (column && !column.ifcolumn) {
        if (column.children && column.prop == "") {
          for (let i = 0; i < column.children.length; i++) {
            const child = column.children[i];
            child.ifcolumn = false;
          }
        }
      } else {
        if (column.children && column.prop == "") {
          for (let i = 0; i < column.children.length; i++) {
            const child = column.children[i];
            child.ifcolumn = true;
          }
        }
      }
    }
  }
};
// 点击汇总子元素
const onchildren = () => {
  if (columnList.value) {
    for (let index = 0; index < columnList.value.length; index++) {
      const column = columnList.value[index];
      if (column.children && column.prop == "") {
        for (let i = 0; i < column.children.length; i++) {
          const child = column.children[i];
          console.log(child);

          if (child && !child.ifcolumn) {
            column.ifcolumn = false;
          } else {
            column.ifcolumn = true;
            return;
          }
        }
      }
    }
  }
};
// 点击单站父元素多选
const onsingle = () => {
  if (singlecolumnList.value) {
    for (let index = 0; index < singlecolumnList.value.length; index++) {
      const column = singlecolumnList.value[index];
      if (column && !column.ifcolumn) {
        if (column.children && column.prop == "") {
          for (let i = 0; i < column.children.length; i++) {
            const child = column.children[i];
            child.ifcolumn = false;
          }
        }
      } else {
        if (column.children && column.prop == "") {
          for (let i = 0; i < column.children.length; i++) {
            const child = column.children[i];
            child.ifcolumn = true;
          }
        }
      }
    }
  }
};
// 点击单站子元素
const onsinglechildren = () => {
  if (singlecolumnList.value) {
    for (let index = 0; index < singlecolumnList.value.length; index++) {
      const column = singlecolumnList.value[index];
      if (column.children && column.prop == "") {
        for (let i = 0; i < column.children.length; i++) {
          const child = column.children[i];
          console.log(child);

          if (child && !child.ifcolumn) {
            column.ifcolumn = false;
          } else {
            column.ifcolumn = true;
            return;
          }
        }
      }
    }
  }
};
// 导出
const onexport = async () => {
  let obj: string[] = []; // 假设 prop 是 string 类型，如果不是，请根据实际类型修改

  if (columnList.value) {
    for (const column of columnList.value) {
      if (column?.ifcolumn) {
        if (column.prop) {
          obj.push(column.prop);
        }
        if (column.children) {
          for (const child of column.children) {
            if (child?.ifcolumn && child.prop) {
              obj.push(child.prop);
            }
          }
        }
      }
    }
  }
  const jsonString = obj.join(",");

  if (daymonthyearvalue.value == 1) {
    let obj = {
      excel: jsonString,
      startDate: timepicker.value[0],
      endDate: timepicker.value[1]
    };
    const { data } = await Summaryexportday(obj);
    downloadxlsx(timepicker.value[0], data);
  } else if (daymonthyearvalue.value == 2) {
    let obj = {
      excel: jsonString,

      startYearMonth: timepicker.value[0],
      endYearMonth: timepicker.value[1]
    };
    const { data } = await Summaryexportmonth(obj);
    downloadxlsx(timepicker.value[0], data);
  } else if (daymonthyearvalue.value == 3) {
    let obj = {
      excel: jsonString,
      startYear: timepicker.value[0],
      endYear: timepicker.value[1]
    };
    const { data } = await Summaryexportyear(obj);
    downloadxlsx(timepicker.value[0] + "-" + timepicker.value[1], data);
  }
};
const downloadxlsx = (item: string, data: other.Data) => {
  let fileUrl = `download/${data.msg}`;
  const date = new Date();
  const hours = formatTime(date.getHours());
  const minutes = formatTime(date.getMinutes());
  const seconds = formatTime(date.getSeconds());
  let fileName = `${item} ${hours}：${minutes}：${seconds}电量报表.xlsx`;
  fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
      // 创建一个临时的URL对象
      const url = URL.createObjectURL(blob);
      // 创建一个隐藏的<a>标签，并设置其href属性为临时URL
      const a = document.createElement("a");
      a.href = url;
      a.download = fileName; // 设置下载的文件名
      a.style.display = "none";
      // 将<a>标签添加到文档中，并模拟点击下载
      document.body.appendChild(a);
      a.click();
      // 下载完成后，移除<a>标签和临时URL对象
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    })
    .catch(error => {
      console.error("下载文件时出错:", error);
    });
};
const formatTime = (time: number) => {
  return time < 10 ? `0${time}` : time; // 如果时间小于 10，在前面加上 0
};
// 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"); // 确保是两位数

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

//   return formattedDate;
// };
const tableData = ref();
// 日
const getreportpowerday = async () => {
  let obj = {
    startDate: timepicker.value[0],
    endDate: timepicker.value[1]
  };
  const { data } = await reportpowerday(obj);
  data.total.stationName = "总计";

  data.list.push(data.total);
  tableData.value = data;
};
// 月份
const getreportpoweryearMonth = async () => {
  let obj = {
    startYearMonth: timepicker.value[0],
    endYearMonth: timepicker.value[1]
  };
  const { data } = await reportpoweryearMonth(obj);
  data.total.stationName = "总计";

  data.list.push(data.total);
  tableData.value = data;
};
// 年份
const getreportpoweryear = async () => {
  let obj = {
    startYear: timepicker.value[0],
    endYear: timepicker.value[1]
  };
  const { data } = await reportpoweryear(obj);
  data.total.stationName = "总计";

  data.list.push(data.total);
  tableData.value = data;
};
const reportformsindex = ref(2);
const pickertype: Ref<any> = ref("date");

// <!-- /--/ -->
//             <!-- daterange/日 -->

//             <!-- monthrange/月 -->
//             <!-- year/年 -->

const onreportforms = (val: any) => {
  if (val == 1) {
    pickertype.value = "date";
    starttime.value = currentDate.value;
  } else if (val == 2) {
    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];
        }
      }
    ];
    pickertype.value = "daterange";
    format.value = "YYYY-MM-DD";
    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    starttime.value = [currentDate, currentDate];
  } else if (val == 3) {
    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    const currentYearMonth = currentDate.slice(0, 7);
    starttime.value = [currentYearMonth, currentYearMonth];
    format.value = "YYYY-MM";
    pickertype.value = "monthrange";

    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 if (val == 4) {
    const today = new Date();
    const currentDate = today.toISOString().split("T")[0];
    // 获取去年同月的日期
    starttime.value = [currentDate.substring(0, 4), currentDate.substring(0, 4)];
    pickertype.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];
        }
      }
    ];

    getelectricitylevelyear();
  }
  reportformsindex.value = val;
  onreportformsid(reportformsindex.value);
};
const onreportformsid = (val: any) => {
  if (val == 1) {
    poststationstationName();
  } else if (val == 2) {
    getsingleStationyear();
  } else if (val == 3) {
    getelectricitylevelyearMonth();
  } else if (val == 4) {
    getelectricitylevelyear();
  }
};
const chartindex = ref(1);

const onchart = (val: any) => {
  chartindex.value = val;
  if (val == 1) {
    getstationsystem();
  } else if (val == 2) {
    getStationtable();
  } else {
    getsingleStationtable();
    getreportsingleStationoriginal();
  }
};
// 选择站点
const Singlevalue = ref("");
const cities: Ref<Station.todo[]> = ref([]);

const poststationstationName = async () => {
  const { data } = await stationstationName({});
  Singlevalue.value = data[0].id;
  cities.value = data;
  return;
  getemsSystemsingleStation();
  getstationsystem();
};
// 获取电站下的设备数
const pageable = ref({
  pn: 1,
  ps: 10,
  total: 0
});
const gettableData = ref();
const getplatformuserlist = async () => {
  let obj = {
    powerId: Singlevalue.value, //查询电站id
    pn: pageable.value.pn,
    ps: pageable.value.ps
  };
  const { data } = await selectemssytemNameURL(obj);
  gettableData.value = data;
  pageable.value.total = gettableData.value.total;
};
const postemsDevice = async (value: any) => {
  console.log(value);
};

// 选择日期starttime
const starttime: Ref<any> = ref("");
// 开始时间
// const yearstarttime = async (val: any) => {
//   console.log(val);

//   if (reportformsindex.value == 1) {
//     starttime.value = formatDate(val);
//   } else if (reportformsindex.value == 2) {
//     starttime.value = [formatDate(val[0]), formatDate(val[1])];
//   } else if (reportformsindex.value == 3) {
//     starttime.value = [formatDate(val[0]), formatDate(val[1])];
//   } else if (reportformsindex.value == 4) {
//     for (let index = 0; index < val.length; index++) {
//       val[index] = formatDate(val[index]);
//     }
//     starttime.value = val;
//   }
// };
// 查询-文件夹
const onselectsite = async () => {
  onreportformsid(reportformsindex.value);
  getplatformuserlist();
};
// 重置
const onselectreset = async () => {
  // onreportformsid(1);
  await onreportforms(2);
};

const singleexport = async () => {
  let obj: string[] = []; // 假设 prop 是 string 类型，如果不是，请根据实际类型修改

  if (singlecolumnList.value) {
    for (const column of singlecolumnList.value) {
      if (column?.ifcolumn) {
        if (column.prop) {
          obj.push(column.prop);
        }
        if (column.children) {
          for (const child of column.children) {
            if (child?.ifcolumn && child.prop) {
              obj.push(child.prop);
            }
          }
        }
      }
    }
  }
  const jsonString = obj.join(",");
  if (reportformsindex.value == 2) {
    let obj = {
      excel: jsonString,

      startTime: starttime.value[0],
      endTime: starttime.value[1]
    };
    const { data } = await betweenbiaoExcel(obj, Singlevalue.value);
    downloadxlsx(starttime.value[0], data);
  } else if (reportformsindex.value == 3) {
    let obj = {
      excel: jsonString,

      startYearMonth: starttime.value[0],
      endYearMonth: starttime.value[1]
    };
    const { data } = await betweenyearMonthExcel(obj, Singlevalue.value);
    downloadxlsx(starttime.value[0], data);
  } else if (reportformsindex.value == 4) {
    let obj = {
      excel: jsonString,
      startYear: starttime.value[0],
      endYear: starttime.value[1]
    };
    const { data } = await betweenyearExcel(obj, Singlevalue.value);
    downloadxlsx(starttime.value[0] + "-" + starttime.value[1], data);
  }
};

// 单站报表-报表
// const pickerincome = (val: (string | number | Date)[]) => {
//   console.log(val);
//   pickervalue.value = [formatDate(val[0]), formatDate(val[1])];
// };
// 时段折线图
const trendchart = ref();

const getstationsystem = async () => {
  let obj = {
    date: starttime.value
  };
  const { data } = await reportsingleStationline(obj, Singlevalue.value);

  powertrend(data);
};
const powertrend = (data: any) => {
  const valueList = data.map(function (item: any) {
    return item.chargeKwh;
  }); // 充电
  const secondList = data.map(function (item: any) {
    return item.dischargeKwh;
  }); //放电
  const trendchartvalue = echarts.init(trendchart.value);
  window.addEventListener(
    "resize",
    () => {
      trendchartvalue.resize();
    },
    false
  );
  let option = {
    grid: {
      left: "2%",
      right: "4%",
      bottom: "6%",
      containLabel: true
    },
    legend: {
      bottom: 0
    },
    title: [
      {
        subtext: "电量/kWh"
      }
    ],
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      // data: dateList,
      data: [
        "00:00",
        "01:00",
        "02:00",
        "03:00",
        "04:00",
        "05:00",
        "06:00",
        "07:00",
        "08:00",
        "09:00",
        "10:00",
        "11:00",
        "12:00",
        "13:00",
        "14:00",
        "15:00",
        "16:00",
        "17:00",
        "18:00",
        "19:00",
        "20:00",
        "21:00",
        "22:00",
        "23:00",
        "00:00"
      ],
      type: "category",
      axisTick: {
        show: false // 这里设置为false隐藏X轴刻度线
      }
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "充电",
        type: "line",
        showSymbol: false,

        data: valueList,
        lineStyle: {
          color: "#0691D9" // 设置折线颜色为红色
        }
      },
      {
        name: "放电",

        type: "line",
        showSymbol: false,

        data: secondList
      }
    ]
  };

  trendchartvalue.setOption(option, true);
};
// 单站报表_原始数据
const rawdataid = ref(1);
const rawdatachart = ref();
const onrawdata = async (val: any) => {
  rawdataid.value = val;
  if (val == 1) {
    getreportsingleStationoriginal();
  } else {
    getreportsingleStationoriginal();
  }
};
const singleid = ref();
const getemsSystemsingleStation = async () => {
  const { data } = await postemsSystemsingleStation({}, Singlevalue.value);
  singleid.value = data[0].id;
  getreportsingleStationoriginal();
};
const getreportsingleStationoriginal = async () => {
  const { data } = await reportsingleStationoriginal({ dateType: rawdataid.value }, Singlevalue.value, singleid.value);
  if (data) {
    ondatachart(data);
  }
};
const ondatachart = (data: any) => {
  if (data.length == 0) {
    return;
  }
  const valueList = data.map(function (item: any) {
    return item.accumulativeExportKwh;
  }); // 充电
  const secondList = data.map(function (item: any) {
    return item.accumulativeImportKwh;
  }); //放电

  const rawchart = echarts.init(rawdatachart.value);
  window.addEventListener(
    "resize",
    () => {
      rawchart.resize();
    },
    false
  );
  let option = {
    grid: {
      left: "2%",
      right: "4%",
      bottom: "6%",
      containLabel: true
    },
    legend: {
      bottom: 0
    },
    title: [
      {
        subtext: "电量/kWh"
      }
    ],
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      // data: dateList,
      data: [
        "00:00",
        "01:00",
        "02:00",
        "03:00",
        "04:00",
        "05:00",
        "06:00",
        "07:00",
        "08:00",
        "09:00",
        "10:00",
        "11:00",
        "12:00",
        "13:00",
        "14:00",
        "15:00",
        "16:00",
        "17:00",
        "18:00",
        "19:00",
        "20:00",
        "21:00",
        "22:00",
        "23:00",
        "00:00"
      ],
      type: "category",
      axisTick: {
        show: false // 这里设置为false隐藏X轴刻度线
      }
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "充电",
        type: "line",
        showSymbol: false,

        data: valueList,
        lineStyle: {
          color: "#0691D9" // 设置折线颜色为红色
        }
      },
      {
        name: "放电",

        type: "line",
        showSymbol: false,

        data: secondList
      }
    ]
  };

  rawchart.setOption(option, true);
};
const columnchart = ref();

// 单站报表_柱状图

const getStationtable = async () => {
  let obj = {
    date: starttime.value
  };
  const { data } = await reportsingleStationline(obj, Singlevalue.value);
  oncolumnchart(data);
};
const oncolumnchart = (data: any) => {
  const valueList = data.map(function (item: { chargeKwh: any }) {
    return item.chargeKwh;
  }); // 充电
  const secondList = data.map(function (item: { dischargeKwh: any }) {
    return item.dischargeKwh;
  }); //放电
  const columncharts = echarts.init(columnchart.value);
  window.addEventListener(
    "resize",
    () => {
      columncharts.resize();
    },
    false
  );
  let option = {
    grid: {
      left: "2%",
      right: "4%",
      bottom: "10%",
      containLabel: true
    },
    legend: {
      bottom: 0
    },
    title: [
      {
        subtext: "电量/kWh"
      }
    ],
    tooltip: {
      trigger: "axis"
    },
    xAxis: {
      // data: dateList,
      data: [
        "00:00",
        "01:00",
        "02:00",
        "03:00",
        "04:00",
        "05:00",
        "06:00",
        "07:00",
        "08:00",
        "09:00",
        "10:00",
        "11:00",
        "12:00",
        "13:00",
        "14:00",
        "15:00",
        "16:00",
        "17:00",
        "18:00",
        "19:00",
        "20:00",
        "21:00",
        "22:00",
        "23:00",
        "00:00"
      ],
      type: "category",
      axisTick: {
        show: false // 这里设置为false隐藏X轴刻度线
      }
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        name: "充电",
        type: "bar",
        showSymbol: false,

        data: valueList,
        lineStyle: {
          color: "#0691D9" // 设置折线颜色为红色
        }
      },
      {
        name: "放电",

        type: "bar",
        showSymbol: false,

        data: secondList
      }
    ]
  };

  columncharts.setOption(option, true);
};
// 单站报表_表格

const tablelist = ref();

const getsingleStationtable = async () => {
  let obj = {
    date: starttime.value
  };
  const { data } = await singleStationtable(obj, Singlevalue.value);
  if (data.list.length > 0) {
    data.total.ymdHour = "合计";
    data.list.push(data.total);
    tablelist.value = data;
  }

  // tablelist.value = data;
};
// 电量报表-单站_日月年报表
const betweenyear = ref();
const getsingleStationyear = async () => {
  let obj = {
    startTime: starttime.value[0],
    endTime: starttime.value[1]
  };
  const { data } = await electricitylevelday(obj, Singlevalue.value);

  betweenyear.value = data;
  data.total.ymd = "合计";
  betweenyear.value.list.push(data.total);
  betweenyear.value.list = betweenyear.value.list.map((item: { ymd: any }) => {
    return {
      ...item,
      andTime: item.ymd,
      ymd: undefined // 如果需要完全删除 ymd 键，可以设置为 undefined
    };
  });
};
const getelectricitylevelyearMonth = async () => {
  let obj = {
    startYearMonth: starttime.value[0],
    endYearMonth: starttime.value[1]
  };
  const { data } = await electricitylevelyearMonth(obj, Singlevalue.value);

  betweenyear.value = data;
  data.total.ym = "合计";
  betweenyear.value.list.push(data.total);
  betweenyear.value.list = betweenyear.value.list.map((item: { ym: any }) => {
    return {
      ...item,
      andTime: item.ym,
      ym: undefined // 如果需要完全删除 ymd 键，可以设置为 undefined
    };
  });
};
const getelectricitylevelyear = async () => {
  let obj = {
    startYear: starttime.value[0],
    endYear: starttime.value[1]
  };
  const { data } = await electricitylevelyear(obj, Singlevalue.value);

  betweenyear.value = data;
  data.total.year = "合计";
  betweenyear.value.list.push(data.total);
  betweenyear.value.list = betweenyear.value.list.map((item: { year: any }) => {
    return {
      ...item,
      andTime: item.year,
      year: undefined // 如果需要完全删除 ymd 键，可以设置为 undefined
    };
  });
};

onMounted(() => {
  const current = localStorage.getItem("currentDate");
  if (current) {
    currentDate.value = current;
  }
  timepicker.value = [currentDate.value, currentDate.value];
  starttime.value = current;
  getreportpowerday();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
