<template>
  <div>
    <div class="title">
      {{ $t("incomeforms.incomestatement") }}
      <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("incomeforms.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('incomeforms.incomestatement')" name="站点汇总">
          <div class="tabdiv">
            <div class="tabpanesite">
              <div class="tabpane">
                <div>时间范围：</div>
                <div class="tabpane1">
                  <el-date-picker
                    v-if="timetype != 'year'"
                    v-model="timepicker"
                    :type="timetype"
                    :shortcuts="shortcuts"
                    :format="format"
                    :value-format="format"
                    :start-placeholder="$t('incomeforms.StartTime')"
                    :end-placeholder="$t('incomeforms.EndTime')"
                    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="$t('incomeforms.StartTime')"
                    :end-placeholder="$t('incomeforms.EndTime')"
                    size="large"
                    :disabled-date="pickerOptions"
                  />
                  <!-- <YearPicker
                    v-if="timetype == 'year'"
                    style="width: 300px"
                    ref="statisticPicker"
                    :label-width="50"
                    :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("incomeforms.Query") }}
                </el-button>
                <el-button size="large" @click="onreset">{{ $t("incomeforms.Reset") }} </el-button>
                <!-- <el-button v-if="BUTTONS.export" size="large" @click="onexport" type="primary" plain>导出</el-button> -->
              </div>

              <div v-if="BUTTONS.export" class="exportright">
                <el-dropdown trigger="click" :hide-on-click="false" @visible-change="onclose">
                  <el-button size="large" type="primary" plain>{{ $t("incomeforms.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("incomeforms.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 :data="tableData.list" style="width: 100%" align="center" :show-overflow-tooltip="true">
              <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> -->
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('incomeforms.Singlereport')" name="单站报表">
          <div class="tabdiv">
            <div class="tabpane">
              <div class="tabpane_1">{{ $t("incomeforms.reporttype") }}：</div>
              <div :class="reportformsindex == 2 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(2)">
                {{ $t("incomeforms.dailyreport") }}
              </div>
              <div :class="reportformsindex == 3 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(3)">
                {{ $t("incomeforms.Monthlyreport") }}
              </div>
              <div :class="reportformsindex == 4 ? 'tabpane_2' : 'tabpane_1'" @click="onreportforms(4)">
                {{ $t("incomeforms.annualreport") }}
              </div>
            </div>
            <div class="tabpanesite">
              <div class="selectsite">
                <div class="tabpane_1">{{ $t("incomeforms.selectsite") }}：</div>
                <el-select
                  v-model="Singlevalue"
                  :placeholder="$t('incomeforms.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("incomeforms.SelectDate") }}：</div>
                <div>
                  <el-date-picker
                    v-if="pickertype != 'year'"
                    v-model="starttime"
                    :type="pickertype"
                    :shortcuts="shortcuts"
                    :format="format"
                    :value-format="format"
                    :start-placeholder="$t('incomeforms.StartTime')"
                    :end-placeholder="$t('incomeforms.EndTime')"
                    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="$t('incomeforms.StartTime')"
                    :end-placeholder="$t('incomeforms.EndTime')"
                    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("incomeforms.Query")
                }}</el-button>
                <el-button size="large" @click="onselectreset">{{ $t("incomeforms.Reset") }}</el-button>
              </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("incomeforms.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("incomeforms.export") }}</el-button>
                    </div>
                  </template>
                </el-dropdown>
              </div>
            </div>
            <div class="dailyreport">
              <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 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>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>
<!--    -->
<script setup lang="ts">
import { onMounted, Ref, ref } from "vue";
import {
  stationstationName,
  singleincomeday,
  singleincomeyearMonth,
  singleincomeyear,
  incomeday,
  incomeyearMonth,
  incomeyear,
  reportsummarymonthEXcel,
  summaryearmonthEXcel,
  reportsummaryyearEXcel,
  reportsingleExcel,
  singlemonthExcel,
  singleyeaeExcel
} from "@/api/home/Multisite";
import { other, Station } from "@/api/interface";
import { useAuthButtons } from "@/hooks/useAuthButtons";
const { BUTTONS } = useAuthButtons();
console.log(BUTTONS);
// 表头
const columnList = ref([
  {
    prop: "ymdHour",
    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: "year",
    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
  // }
  {
    prop: "overallEfficiency",
    label: "应收益(元)",
    ifcolumn: true,
    children: null
  }
]);
//
const currentDate = ref();
const activeName = ref("站点汇总");

const handleClick = async (val: any) => {
  activeName.value = val.props.name;
  if (val.props.name == "站点汇总") {
    getdaymonthyear(1);
    gatSummary();
  } else {
    await poststationstationName();
    await onreportforms(2);
  }
};
const timepicker: Ref<any> = ref([]);

// 禁用日期
const pickerOptions = (time: { getTime: (arg0: Date) => number }) => {
  return time.getTime(new Date()) > Date.now();
};
// 选择时间
// const datepicker = (val: any) => {
//   timepicker.value = [formatDate(val[0]), formatDate(val[1])];
// };
// 选择日期
const daymonthyearvalue = ref(1);

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 daymonthyear = ref([
  {
    value: 1,
    label: "按日"
  },
  {
    value: 2,
    label: "按月"
  },
  {
    value: 3,
    label: "按年"
  }
]);
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];
    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 = () => {
  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.children && column.prop == "") {
        for (let i = 0; i < column.children.length; i++) {
          const child = column.children[i];

          if (child && !column.ifcolumn) {
            child.ifcolumn = false;
          } else {
            child.ifcolumn = true;
          }
          if (child && child.ifcolumn) {
            column.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 reportsummarymonthEXcel(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 summaryearmonthEXcel(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 reportsummaryyearEXcel(obj);
    downloadxlsx(timepicker.value[0] + "-" + timepicker.value[1], data);
  }
};
const downloadxlsx = (item: string, data: other.Data) => {
  console.log(item, 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"); // 确保是两位数
//   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 tableData = ref();

// 日
const getreportpowerday = async () => {
  let obj = {
    startDate: timepicker.value[0],
    endDate: timepicker.value[1]
  };
  const { data } = await incomeday(obj);
  data.total.ymdHour = "总计";
  data.list.push(data.total);
  tableData.value = data;
};
// 月份
const getreportpoweryearMonth = async () => {
  let obj = {
    startYearMonth: timepicker.value[0],
    endYearMonth: timepicker.value[1]
  };
  const { data } = await incomeyearMonth(obj);
  data.total.ymdHour = "总计";
  data.list.push(data.total);
  tableData.value = data;
};
// 年份

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

const reportformsindex = ref(2);
const pickertype: Ref<any> = ref("daterange");
const onreportforms = (val: any) => {
  reportformsindex.value = val;

  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];
        }
      }
    ];
  }
  onselectsite();
};

// 选择站点
const Singlevalue = ref("");
const cities: Ref<Station.todo[]> = ref([]);
const poststationstationName = async () => {
  const { data } = await stationstationName({});
  Singlevalue.value = data[0].id;
  cities.value = data;
  // getsingleincomeday();
};
const postemsDevice = async (value: any) => {
  console.log(value);
};

// 选择日期
const starttime: Ref<any> = ref("");
// 开始时间
// const yearstarttime = async (val: any) => {
//   if (reportformsindex.value == 1) {
//   } 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 () => {
  if (reportformsindex.value == 2) {
    getsingleincomeday();
  } else if (reportformsindex.value == 3) {
    getsingleincomeyearMonth();
  } else if (reportformsindex.value == 4) {
    getsingleincomeyear();
  }
  // onreportforms(reportformsindex.value);
};
// 重置
const onselectreset = async () => {
  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 reportsingleExcel(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 singlemonthExcel(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 singleyeaeExcel(obj, Singlevalue.value);
    downloadxlsx(starttime.value[0] + "-" + starttime.value[1], data);
  }
};
// 电量报表-单站_日月年报表
const betweenyear = ref();
const getsingleincomeday = async () => {
  let obj = {
    startDate: starttime.value[0],
    endDate: starttime.value[1]
  };
  const { data } = await singleincomeday(obj, Singlevalue.value);

  betweenyear.value = data;
  data.total.ymd = "合计";
  betweenyear.value.list.push(data.total);
};
const getsingleincomeyearMonth = async () => {
  let obj = {
    startYearMonth: starttime.value[0],
    endYearMonth: starttime.value[1]
  };
  const { data } = await singleincomeyearMonth(obj, Singlevalue.value);

  betweenyear.value = data;
  data.total.ym = "合计";
  betweenyear.value.list.push(data.total);
};
const getsingleincomeyear = async () => {
  let obj = {
    startYear: starttime.value[0],
    endYear: starttime.value[1]
  };
  const { data } = await singleincomeyear(obj, Singlevalue.value);

  betweenyear.value = data;
  data.total.year = "合计";
  betweenyear.value.list.push(data.total);
};
onMounted(() => {
  const current = localStorage.getItem("currentDate");
  if (current) {
    currentDate.value = current;
    starttime.value = [currentDate.value, currentDate.value];
  }
  timepicker.value = [currentDate.value, currentDate.value];
  getreportpowerday();
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
<!--

-->
