<template>
  <div class="big-machine" v-loading="listLoading">
    <div class="condition">
      <div class="condition-left">
        <div class="time-label">时间类型:</div>
        <el-radio-group
          v-model="dateType"
          style="margin-right: 0.24rem"
          @change="updateDateType"
        >
          <el-radio label="hour">小时</el-radio>
          <el-radio label="day">日</el-radio>
          <el-radio label="month">月</el-radio>
          <el-radio label="year">年</el-radio>
        </el-radio-group>
        <el-date-picker
          v-model="timeDate"
          :default-time="['00:00:00', '23:59:59']"
          type="datetimerange"
          range-separator="至"
          v-if="dateType == 'hour'"
          placeholder="选择日期"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
        <el-date-picker
          v-model="dayDate"
          type="daterange"
          v-if="dateType == 'day'"
          :key="this.dateType"
          range-separator="至"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="dateChange"
        >
        </el-date-picker>
        <el-date-picker
          v-model="monthDate"
          type="monthrange"
          v-if="dateType == 'month'"
          :key="this.dateType"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          value-format="yyyy-MM"
          @change="dateChange"
        >
        </el-date-picker>
        <div class="years-div" v-if="dateType == 'year'" :key="this.dateType">
          <el-date-picker
            v-model="startYear"
            type="year"
            placeholder="选择开始年份"
            style="width: 180px"
            value-format="yyyy"
          >
          </el-date-picker>
          <div class="years-word">至</div>
          <el-date-picker
            v-model="endYear"
            type="year"
            placeholder="选择结束年份"
            style="width: 180px"
            value-format="yyyy"
          >
          </el-date-picker>
        </div>
        <el-select
          style="margin-left: 0.1rem"
          v-model="systemType"
          placeholder="请选择系统类型"
          clearable
        >
          <el-option
            v-for="dict in systemTypes"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
        <div class="success-btn" style="margin: 0 0.12rem">
          <el-button type="success" @click="findData">查询</el-button>
        </div>
        <div class="warning-btn">
          <el-button type="warning" @click="exportData">导出</el-button>
        </div>
      </div>
    </div>
    <div class="machine">
      <div class="machine-left">
        <div class="machine-li">
          <div class="tit">冷水机组</div>
          <div class="machine-center-li">
            <div class="machine-context">
              <div class="chart">
                <machine-chart :chartsData="chiller"></machine-chart>
              </div>
            </div>
          </div>
        </div>
        <div class="machine-li">
          <div class="tit">冷冻水泵</div>
          <div class="machine-center-li">
            <div class="machine-context">
              <div class="chart">
                <machine-chart :chartsData="chillerPump"></machine-chart>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="machine-center">
        <div class="total">
          <div class="data1">
            <span>冷水机组</span>
            <div class="p-class">
              <countTo
                class="p-class2"
                :startVal="startVal"
                :endVal="allDataArr[0].value"
                :duration="duration"
                :separator="separator"
                :decimals="2"
                ref="CountToPower"
              ></countTo
              >kwh
            </div>
          </div>
          <div class="data2">
            <span>冷冻水泵</span>
            <div class="p-class">
              <countTo
                class="p-class2"
                :startVal="startVal"
                :endVal="allDataArr[1].value"
                :duration="duration"
                :separator="separator"
                :decimals="2"
                ref="CountToPower"
              ></countTo
              >kwh
            </div>
          </div>
          <div class="data3">
            <span>冷却水泵</span>
            <div class="p-class">
              <countTo
                class="p-class2"
                :startVal="startVal"
                :endVal="allDataArr[2].value"
                :duration="duration"
                :separator="separator"
                :decimals="2"
                ref="CountToPower"
              ></countTo
              >kwh
            </div>
          </div>
          <div class="data4">
            <span>冷却塔</span>
            <div class="p-class">
              <countTo
                class="p-class2"
                :startVal="startVal"
                :endVal="allDataArr[3].value"
                :duration="duration"
                :separator="separator"
                :decimals="2"
                ref="CountToPower"
              ></countTo
              >kwh
            </div>
          </div>
          <canvas class="rain"></canvas>
          <canvas class="dashed"></canvas>
          <div class="sphere">
            <div class="sphere-bg"></div>
            <div class="sum">
              <div class="sum-title">总耗电量</div>
              <div class="p-all">
                <countTo
                  :startVal="startVal"
                  :endVal="allElect"
                  :duration="duration"
                  :separator="separator"
                  :decimals="2"
                  ref="CountToPower"
                ></countTo
                >kwh
              </div>
            </div>
          </div>
          <div class="cicle3"></div>
          <div class="cicle4"></div>
          <div class="cicle5"></div>
          <div class="cicle6"></div>
          <div class="cicle7"></div>
          <div class="cicle8">
            <span>{{ electProp[0] }}%</span>
            <p>冷水机组</p>
          </div>
          <div class="cicle9">
            <span>{{ electProp[1] }}%</span>
            <p>冷冻水泵</p>
          </div>
          <div class="cicle10">
            <span>{{ electProp[2] }}%</span>
            <p>冷却水泵</p>
          </div>
          <div class="cicle11">
            <span>{{ electProp[3] }}%</span>
            <p>冷却塔</p>
          </div>
        </div>
      </div>
      <div class="machine-right">
        <div class="machine-li">
          <div class="tit">冷却水泵</div>
          <div class="machine-center-li">
            <div class="machine-context">
              <div class="chart">
                <machine-chart :chartsData="coolPump"></machine-chart>
              </div>
            </div>
          </div>
        </div>
        <div class="machine-li">
          <div class="tit">冷却塔</div>
          <div class="machine-center-li">
            <div class="machine-context">
              <div class="chart">
                <machine-chart :chartsData="coolTower"></machine-chart>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="" :visible.sync="dialogVisible" width="750px">
      <prop-chart></prop-chart>
    </el-dialog>
  </div>
</template>

<script>
import { format2 } from "@/utils/datetime";
import machineChart from "./machineChart.vue";
// import propChart from './propChart.vue';
import countTo from "vue-count-to";
import { energyAnalyze, analyzeExport } from "@/api/centerairC/energyManage";
import { listData } from "@/api/system/dict/data";
export default {
  components: { machineChart, countTo },
  data() {
    return {
      listLoading: false,
      dateType: "hour", //默认选择小时
      timeDate: [], //小时值
      dayDate: [], //日值
      monthDate: [], //月值
      startYear: "", //开始年份
      endYear: "", //结束年份
      startTime: "", //开始日期
      endTime: "", //结束日期
      allDataArr: [
        { value: 0 }, // 初始化元素及其属性
        { value: 0 },
        { value: 0 },
        { value: 0 },
      ],
      chillerPump: [], //冷冻泵
      chiller: [], //主机
      coolPump: [], //冷却泵
      coolTower: [], //冷却塔
      allElect: 0, //总耗电量
      electProp: [], //耗电占比
      dialogVisible: false,
      startVal: 0, //开始的数
      duration: 1000, // 持续时间
      separator: "", // 分隔符
      systemType: "", //系统类型
      systemTypes: [],
    };
  },
  created() {
    // 在组件创建完成后，设置默认值
  },
  mounted() {
    this.initializeTimeDate();
    this.getDictList();
  },
  methods: {
    /** 查询系统类型-字典数据列表 */
    getDictList() {
      let data = {
        pageNum: 1,
        pageSize: 100,
        dictType: "sys_type",
      };
      listData(data).then((response) => {
        this.systemTypes = response.rows;
        this.systemType = this.systemTypes[0].dictValue;
        this.getTableData();
      });
    },
    // 初始化时间
    initializeTimeDate() {
      const start = new Date(new Date().setHours(0, 0, 0, 0));
      const end = new Date(new Date().setHours(23, 59, 59, 59));
      this.timeDate = [format2(start), format2(end)]; // 更新
    },
    // 选择时间类型
    updateDateType() {
      // this.dateType = this.radio;
      console.log(this.dateType);
      (this.timeDate = []), //小时值
        (this.dayDate = []), //日值
        (this.monthDate = []), //月值
        (this.startYear = ""), //开始年份
        (this.endYear = ""); //结束年份
    },
    // 选中日期事件
    dateChange() {
      // console.log("打印时间", this.timeform.time1);
      if (!this.dayDate) {
        this.$nextTick(() => {
          this.dayDate = [];
        });
      }
      if (!this.monthDate) {
        this.$nextTick(() => {
          this.monthDate = [];
        });
      }
    },
    // 查询
    findData() {
      console.log("this.dateType", this.dateType);
      console.log("this.timeDate", this.timeDate);
      switch (this.dateType) {
        case "hour":
          if (!this.timeDate) {
            this.showMessage("请选择时间！", "warning");
          } else {
            this.getTableData();
          }
          break;
        case "day":
          if (this.dayDate.length === 0) {
            this.showMessage("请选择时间！", "warning");
          } else {
            const newLength =
              new Date(this.dayDate[1]).getTime() -
              new Date(this.dayDate[0]).getTime();
            const dayDiff = Math.floor(newLength / (1000 * 60 * 60 * 24));
            if (dayDiff > 31) {
              this.showMessage(
                "最多只能选择30天区间，请重新选择再查询！",
                "warning"
              );
            } else {
              this.getTableData();
            }
          }
          break;
        case "month":
          if (this.monthDate.length === 0) {
            this.showMessage("请选择时间！", "warning");
          } else {
            const [start, end] = this.monthDate;
            const startDate = new Date(start);
            const endDate = new Date(end);
            const startYear = startDate.getFullYear();
            const startMonth = startDate.getMonth();
            const endYear = endDate.getFullYear();
            const endMonth = endDate.getMonth();
            const monthDiff =
              (endYear - startYear) * 12 + (endMonth - startMonth);
            if (monthDiff > 12) {
              this.showMessage(
                "最多只能选择12个月区间，请重新选择再查询！",
                "warning"
              );
            } else {
              this.getTableData();
            }
          }
          break;
        case "year":
          if (!this.startYear || !this.endYear) {
            this.showMessage("请选择全年份区间！", "warning");
          } else if (this.startYear > this.endYear) {
            this.showMessage("结束年份要大于开始年份！", "warning");
          } else {
            this.getTableData();
          }
          break;
        default:
          break;
      }
    },
    // 显示消息的函数
    showMessage(message, type) {
      this.$message({
        message: message,
        type: type,
      });
    },
    //请求数据
    getTableData() {
      if (this.dateType == "hour") {
        this.startTime = format2(this.timeDate[0]);
        this.endTime = format2(this.timeDate[1]);
      } else if (this.dateType == "day") {
        this.startTime = this.dayDate.length > 0 ? this.dayDate[0] : "";
        this.endTime = this.dayDate.length > 0 ? this.dayDate[1] : "";
      } else if (this.dateType == "month") {
        this.startTime = this.monthDate.length > 0 ? this.monthDate[0] : "";
        this.endTime = this.monthDate.length > 0 ? this.monthDate[1] : "";
      } else if (this.dateType == "year") {
        (this.startTime = this.startYear), (this.endTime = this.endYear);
      }
      let data = {
        timeType: this.dateType,
        startTime: this.startTime,
        endTime: this.endTime,
        systemType: this.systemType,
      };
      console.log("查询数据参数", data);
      this.listLoading = true;
      energyAnalyze(data).then((res) => {
        console.log("能源返回", res);
        if (res.code == 200 && res.data.all) {
          this.allDataArr = res.data.all;
          this.allDataArr = this.allDataArr.map((item) => {
            item.value = parseFloat(item.value);
            return item;
          });
          this.chillerPump = res.data.chillerPump;
          this.chiller = res.data.chiller;
          this.coolPump = res.data.coolPump;
          this.coolTower = res.data.coolTower;
          console.log("this.allDataArr", this.allDataArr);
          // 总电量
          this.allElect = this.allDataArr.reduce(
            (sum, item) => sum + item.value,
            0
          );
          console.log("this.allElect ", this.allElect);
          this.electProp = [];
          // 计算每个指标的百分比
          this.allDataArr.forEach((item) => {
            console.log("两数相除", item.value, this.allElect);
            let percentage;
            if (this.allElect === 0) {
              percentage = 0; // 或者设为其他特定值，如 null
            } else {
              percentage = (parseFloat(item.value) / this.allElect) * 100;
              percentage = percentage.toFixed(2);
            }
            this.electProp.push(percentage);
          });

          console.log("百分比数组", this.electProp);
        } else {
          this.chiller = [];
          this.chillerPump = [];
          this.coolPump = [];
          this.coolTower = [];
        }
      });
      // Just to simulate the time of the request
      setTimeout(() => {
        this.listLoading = false;
      }, 1.0 * 1000);
    },
    // 导出
    exportData() {
      let data = {
        timeType: this.dateType,
        startTime: this.startTime,
        endTime: this.endTime,
        systemType: this.systemType,
      };
      console.log("导出数据参数", data);
      analyzeExport(data).then((res) => {
        console.log("导出返回", res);
        if (res) {
          // 请求的结果就是文件
          // 创建一个blob URL，用于生成下载链接
          const url = window.URL.createObjectURL(new Blob([res]));
          // 创建一个<a>元素，并设置其href和download属性
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "机房能耗报表.xls"); // 设置下载的文件名
          // 模拟点击下载链接
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          // 释放blob URL资源
          window.URL.revokeObjectURL(url);
          this.$message({
            type: "success",
            message: "导出成功!",
          });
        } else {
          this.$message.error("导出失败!");
        }
      });
      // .catch((err) => {
      //     this.$message.error('导出失败!');
      // })
    },
    onReversal() {
      this.dialogVisible = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.condition {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  margin-bottom: 0.24rem;

  .condition-left {
    display: flex;
    flex-direction: row;
    align-items: center;
    flex-wrap: wrap;

    .years-div {
      display: flex;
      flex-direction: row;
      align-items: center;

      .years-word {
        font-size: 14px;
        margin: 0 5px;
        color: #388ff3;
      }
    }

    .time-label {
      font-size: 16px;
      line-height: 7px;
      margin-right: 12px;
      white-space: nowrap;
    }
  }
}
.machine {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;
  width: 100%;

  .machine-center {
    width: 50%;
  }

  .machine-left,
  .machine-right {
    display: flex;
    flex-direction: column;
    width: 25%;
    // background: #00be97;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-right: 1px;

    .machine-li {
      width: 100%;
      margin-bottom: 0.3rem;
      border: 1px solid rgba(9, 83, 133, 0.5);
      box-shadow: inset 0 0 30px rgba(9, 83, 133, 0.4);
      position: relative;
      border-radius: 0.07rem;

      .tit {
        padding: 0.1rem 0.1rem 0.1rem 0.25rem;
        border-bottom: 1px solid rgba(9, 83, 133, 0.5);
        font-size: 0.18rem;
        font-weight: 500;
        position: relative;
        // background: rgba(64, 72, 71, 0.5);
        border-radius: 0.07rem 0.07rem 0 0;
        box-shadow: 0 0 5px rgba(9, 83, 133, 0.5);
        display: flex;
        flex-direction: row;
        align-items: center;
      }

      .tit::before {
        position: absolute;
        content: "";
        width: 6px;
        height: 6px;
        background: rgba(20, 231, 231, 0.9);
        box-shadow: 0 0 5px rgba(0, 93, 130, 0.9);
        border-radius: 50%;
        left: 0.1rem;
        top: 0.18rem;
      }

      .machine-center-li {
        width: 100%;

        .machine-context {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          width: 100%;

          .chart {
            width: 100%;
            height: 330px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
          }
        }
      }
    }
  }
}
// 媒体查询，适配大于2000px分辨率的大屏样式
@media (min-width: 2000px) {
  .condition {
    .condition-left {
      .years-div {
        .years-word {
          font-size: 0.14rem !important;
          margin: 0 0.05rem !important;
        }
      }

      .time-label {
        font-size: 0.16rem !important;
        line-height: 0.07rem !important;
        margin-right: 0.12rem !important;
      }
    }
  }
  .machine {
    .machine-left,
    .machine-right {
      .machine-li {
        .tit::before {
          width: 0.06rem !important;
          height: 0.06rem !important;
        }

        .machine-center-li {
          .machine-context {
            .chart {
              height: 3.3rem !important;
            }
          }
        }
      }
    }
  }
}
</style>
