<template>
  <div id="used-ele" :style="{ backgroundColor: bgImage }" @click="handleOpenChart(fanList)">
    <!--    <div v-if="electricityConsumptionMonthly===0&&monthlySavings===0" class="showNull ">-->
    <!--      <div class="loading" v-if="loading===0"></div>-->
    <!--      {{ loading === 0 ? '加载中...' : '暂无数据~' }}-->
    <!--    </div>-->
    <div class="content">
      <div class="item">
        <div class="container" ref="length">
          <div class="value" ref="valueA"></div>
        </div>
        <div>
          <div class="icon"></div>
          <span>当月用电量：{{ electricityConsumptionMonthly }}kwh</span>
        </div>
      </div>
      <div class="item">
        <div class="container" ref="length">
          <div class="value" ref="valueB"></div>
        </div>
        <div>
          <div class="icon"></div>
          <span>当月节省量：{{ monthlySavings }}kwh</span>
        </div>
      </div>
      <div class="ele-left-bottom-icon"></div>
      <div class="ele-right-bottom-icon"></div>
    </div>
  </div>

  <div class="digital-tunnel">
    <el-dialog :close-on-click-modal="false" v-model="isVisited" width="2175px" :modal="false" id="eleDialog">
      <div class="left-top-icon"></div>
      <div class="right-top-icon"></div>
      <div class="user-select">
        <el-select
            v-model="chooseChartFan"
            filterable
            placeholder="请选择风机"
            :fit-input-width="true"
            :teleported="false"
            @change="changeFanData"
        >
          <el-option
              v-for="item in fanList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </div>
      <div class="top-tag">
        <div class="allUsedEle">
          <div class="use-title">
            月总用电量
          </div>
          <div class="value">{{ totalElectricityConsumption }}kwh</div>
        </div>
        <div class="allUsedEle">
          <div class="use-title">
            月节省量
          </div>
          <div class="value">{{ saveElectricity }}kwh</div>
        </div>
      </div>
      <div class="loading-block" v-if="showLoading">
        <div class="loading" v-if="loadingText==='加载中...'"></div>
        <span>{{ loadingText }}</span>
      </div>
      <div class="chat-dialog" v-else>
        <div id="containerEle"></div>
        <div style="width: 1px;"></div>
      </div>
      <div class="time-select">
        <div class="export-btn" @click="handleExport">
          导出
        </div>
        <choose-month v-if="selectTimeButton===1" ref="chooseMonthRef" @select="monthSelect"/>
        <time-range-btn
            :buttonList="timeList"
            v-model="selectTimeButton"
            @select="timeSelect"
        />
      </div>
      <div class="change-screen">
        <el-icon size="55" color="#05feff" class="full-icon" title="放大" @click="fullScreen" v-if="isFullScreen">
          <FullScreen/>
        </el-icon>
        <div v-else class="shrink-icon" title="缩小" @click="shrinkScreen"></div>
      </div>
      <div class="left-bottom-icon"></div>
      <div class="right-bottom-icon"></div>
    </el-dialog>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import TimeRangeBtn from "@/components/timeRangeBtn/index.vue"
import ChooseMonth from "@/components/chooseMonth/index.vue"
import {getEleEchartsInfo} from "@/api/largeScreen";
import elementResizeDetectorMaker from "element-resize-detector";
import CsvExportor from "csv-exportor";
import {getNowFormatDate} from "@/utils/date.js";

const props = defineProps({
  list: Array,
  eleData: Array,
  loading: Number
});

const loadingText = ref('加载中...')
const timeList = ref(["年", "月"]);
const selectTimeButton = ref(1);
const chooseMonthRef = ref();
const monthValue = ref('');
const chooseChartFan = ref('');
let myEcharts = reactive({});
const isFullScreen = ref(false);
let chartData = reactive([])
let dataZoomTop = reactive('89%')
const isVisited = ref(false);
const showLoading = ref(false)
const electricityConsumptionMonthly = ref(0)
const monthlySavings = ref(0)
const totalElectricityConsumption = ref(0)
const saveElectricity = ref(0)
const openEquipmentId = ref(0)
const length = ref(null);
const valueA = ref();
const fanList = ref([]);
const valueB = ref(monthlySavings.value);
const bgImage = computed(() =>
    isVisited.value
        ? "#2E5589"
        : "rgba(6,34,71,0.78)"
);
// watch(() => props.loading, (now) => {
//   props.loading = now
// }, {deep: true});
watch(() => props.eleData, (now) => {
  if (now) {
    let fanObj = {}
    now.frequencyChangerList.forEach(item => {
      if (item.equipmentType === 'frequency1' || item.equipmentType === "frequency2") {
        fanObj = {
          value: item.equipmentId,
          label: changeNum(item.equipmentId, item.equipmentType)
        }
      }
      fanList.value.push(fanObj)
    })
    getBasicData(now.largeScreenElectricity)
  }
  nextTick(() => {
    setValueA()
    setValueB()
  })
}, {deep: true});
// watch(() => props.list, (now) => {
//   console.log(now,props.eleData,'大V大V')
//   props.eleData.frequencyChangerList.forEach(item => {
//     now.forEach(newItem => {
//       if (item.equipmentId === newItem.equipmentId) {
//         if (newItem.electricityConsumptionDay) {
//           electricityConsumptionMonthly.value = newItem.electricityConsumptionMonthly
//         }
//       }
//     })
// })
//   setValueA()
//   setValueB()
// }, {deep: true});
const handleExport = () => {
  const header = ['月总用电量(kwh)', '月总节省电量(kwh)', '时间', '日用电量(kwh)', '日节省量(kwh)'];
  let newArray = []
  chartData.dates.forEach((item, index) => {
    let obj = {
      totalElectricityConsumption: chartData.totalElectricityConsumption,
      saveElectricity: chartData.saveElectricity,
      dates: chartData.dates[index],
      consumptionValues: chartData.consumptionValues[index],
      saveElectricityValues: chartData.saveElectricityValues[index]
    }
    newArray.push(obj)
  })
  let time = ''
  if (selectTimeButton.value === 1) {
    if (monthValue.value) {
      const index = monthValue.value.lastIndexOf("\-");
      time = monthValue.value.substring(0, index)
    } else {
      time = getNowFormatDate(false)
    }
  } else if (selectTimeButton.value === 0) {
    time = new Date().getFullYear() + '年'
  }
  const name = changeNum(chooseChartFan.value) + '用电量监控数据-' + time
  CsvExportor.downloadCsv(newArray, {header}, `${name}.csv`);
}
//放大弹窗
const fullScreen = () => {
  const fan = document.getElementById('eleDialog')
  const fanChart = document.getElementById('containerEle')
  const erd = elementResizeDetectorMaker();
  fan.classList.remove('shrink-screen-dialog')
  erd.listenTo(document.getElementById('eleDialog'), (element) => {
    fanChart.style.height = (element.offsetHeight - 280) + 'px'
    myEcharts.resize();
  });
  nextTick(() => {
    isFullScreen.value = false
    initChart(chartData.dates, chartData.consumptionValues, chartData.saveElectricityValues, '94%')
  })
}
const shrinkScreen = () => {
  const fan = document.getElementById('eleDialog')
  const fanChart = document.getElementById('containerEle')
  fan.classList.add('shrink-screen-dialog')
  fanChart.style.height = '1010px'
  myEcharts.resize();
  nextTick(() => {
    isFullScreen.value = true
    initChart(chartData.dates, chartData.consumptionValues, chartData.saveElectricityValues, dataZoomTop)
  })
}
const changeNum = (item,equipmentType) => {
  switch (equipmentType) {
    case 'frequency1':
      return '一号风机';
    case 'frequency2':
      return '二号风机';
  }
}
const setValueA = () => {
  if (electricityConsumptionMonthly.value === 0 || length.value === null || electricityConsumptionMonthly.value < 0) {
    valueA.value.style.height = `0px`;
  }
  let width = (electricityConsumptionMonthly.value * length.value?.offsetHeight) / 1000000;
  valueA.value.style.height = `${width}px`;
}
const setValueB = () => {
  if (monthlySavings.value === 0 || length.value === null || monthlySavings.value < 0) {
    valueB.value.style.height = `0px`;
  }
  let width = (monthlySavings.value * length.value?.offsetHeight) / 1000000;
  valueB.value.style.height = `${width}px`;
}
const getBasicData = (data) => {
  if (!data) return;
  electricityConsumptionMonthly.value = data.electricityConsumptionCount
  monthlySavings.value = data.conserveElectricityCount
}

const monthSelect = (val) => {
  monthValue.value = val
  if (isFullScreen.value) {
    getFanInfo(openEquipmentId.value, 'month', val)
  } else {
    getFanInfo(openEquipmentId.value, 'month', val, true)
  }

}
const changeDate = (index) => {
  switch (index) {
    case 0:
      return 'years'
    case 1:
      return 'month'
    default:
      return 1
  }
}
const timeSelect = (index) => {
  monthValue.value = ''
  if (isFullScreen.value) {
    getFanInfo(openEquipmentId.value, changeDate(index))
  } else {
    getFanInfo(openEquipmentId.value, changeDate(index), '', true)
  }
};
const changeFanData = (val) => {
  // selectTimeButton.value = 1
  openEquipmentId.value = val
  if (isFullScreen.value) {
    getFanInfo(val, changeDate(selectTimeButton.value), monthValue.value)
  } else {
    getFanInfo(val, changeDate(selectTimeButton.value), monthValue.value, true)
  }
}
const getFanInfo = (equipmentId, type = 'month', time = '', flag) => {
  showLoading.value = true
  nextTick(() => {
    if (flag) {
      const fan = document.getElementById('eleDialog')
      fan.classList.add('shrink-screen-dialog')
      if (isFullScreen.value) {
        const titleName = document.getElementsByClassName('el-dialog__title')[0]
        titleName.style.fontSize = '70px'
      }
    }
  })
  getEleEchartsInfo(equipmentId, time, type).then(res => {
    if (res?.code === 1000) {
      showLoading.value = false
      chartData = res.data
      totalElectricityConsumption.value = res.data.totalElectricityConsumption
      saveElectricity.value = res.data.saveElectricity
      nextTick(() => {
        if (flag) {
          const fanChart = document.getElementById('containerEle')
          const erd = elementResizeDetectorMaker();
          erd.listenTo(document.getElementById('eleDialog'), (element) => {
            fanChart.style.height = element.offsetHeight - 280 + 'px'
            myEcharts.resize();
          });
          if (isFullScreen.value) {
            initChart(res.data.dates, res.data.consumptionValues, res.data.saveElectricityValues, dataZoomTop)
          }
        } else {
          shrinkScreen()
        }
      })
    }
  })
  nextTick(() => {
    loadingText.value = '加载中...'
  })
}
const handleOpenChart = (list) => {
  monthValue.value = ''
  selectTimeButton.value = 1
  isVisited.value = true
  openEquipmentId.value = list[0].value
  chooseChartFan.value = list[0].value
  nextTick(() => {
    if (chooseMonthRef.value) {
      chooseMonthRef.value.clearData()
    }
  })
  isFullScreen.value = true
  getFanInfo(openEquipmentId.value, 'month', '', true)
}
/**
 * 初始化echarts实例方法
 */
const initChart = (type, valueA, valueB, top) => {
  //3.初始化container容器
  myEcharts = echarts.init(document.getElementById('containerEle'));
  //5.传入数据
  let option = {
    //图例
    legend: {
      left: 0,
      textStyle: {
        color: '#60DDDE',
        fontSize: 45
      },
      itemWidth: 30,
      itemHeight: 30,
      icon: "circle",
    },
    //离容器四侧的距离
    grid: {
      left: 0, // 左边距
      right: 20, // 右边距
      top: 80, // 顶边距
      bottom: 110, // 底边距
      containLabel: true,
    },
    //提示框组件
    tooltip: {
      show: true,
      trigger: 'axis',
      backgroundColor: "transparent", // 设置背景颜色为透明
      borderColor: "transparent", // 设置边框颜色为透明
      padding: 0, // 设置内边距为0
      textStyle: {
        fontSize: 40
      },
      formatter: function (params) {
        let content = `
          <div style="background: linear-gradient(180deg, #254062 0%, rgba(20,36,51,0.3) 100%);border: 2px solid #6087BA;border-radius: 4px;padding: 8px 16px;">
            <div style="font-size: 52px;font-family: PingFang SC-Regular, PingFang SC;font-weight: 400;color: #EFEEEE;margin-bottom: 8px;">${params[0].name}日</div>
            <div style="font-size: 48px;line-height: 48px;font-family: Bebas Neue-Regular, Bebas Neue;font-weight: 400;"><span style="color: #FFFFFF">日用电量: </span><span style="background: linear-gradient(180deg, #F5B85F 0%, #FFFFFF 100%);background-clip: text;-webkit-background-clip: text;-webkit-text-fill-color: transparent;">${params[0].value}</span></div>
            <div style="font-size: 48px;line-height: 48px;font-family: Bebas Neue-Regular, Bebas Neue;font-weight: 400;margin-top: 30px"><span style="color: #FFFFFF">日节省量: </span><span style="background: linear-gradient(180deg, #F5B85F 0%, #FFFFFF 100%);background-clip: text;-webkit-background-clip: text;-webkit-text-fill-color: transparent;">${params[1].value}</span></div>
          </div>`;
        return content;
      },
    },
    toolbox: {
      show: false,
      right: 10,
      feature: {
        dataZoom: {
          yAxisIndex: 'none'
        }
      }
    },
    dataZoom: [{
      type: 'inside'
    },
      {
        type: 'slider',
        top: top,
        height: 100,
        textStyle: {
          fontSize: 45,
          color: '#fffff'
        }
      }],
    //X轴
    xAxis: {
      type: 'category',
      // data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
      data: type,
      axisLabel: {
        textStyle: {
          fontSize: 45,
          color: '#D6F1FA'
        },
      },
    },
    //Y轴
    yAxis: {
      type: 'value',
      axisLabel: {
        textStyle: {
          fontSize: 45,
          color: '#D6F1FA'
        },
      },
    },
    //配置项
    series: [
      {
        name: '日用电量',
        // data: [120, 200, 150, 80, 70, 110, 130, 100, 140, 130, 160, 150, 90, 130, 110, 120, 150, 140, 130, 120, 110, 100, 90, 80, 100, 140, 130, 160, 150, 24, 50],
        data: valueA,
        type: 'bar'
      },
      {
        name: '日节省量',
        // data: [140, 130, 160, 150, 90, 130, 110, 120, 150, 140, 130, 120, 110, 100, 90, 80, 100, 140, 130, 160, 150, 24, 50, 120, 200, 150, 80, 70, 110, 130, 100,],
        data: valueB,
        type: 'bar'
      },
    ]
  }
  myEcharts.setOption(option);
  //图表大小自适应窗口大小变化
  window.onresize = () => {
    myEcharts.resize();
  }
}
</script>
<style lang="scss">
.user-select {
  margin-bottom: 126px;

  .el-select {
    width: 476px;
  }

  .el-input {
    width: 476px;

    .el-input__wrapper {
      background-color: transparent;
      box-shadow: none;
      border-radius: 10px;
      border: 2px solid #0F82AF;

      .el-input__inner {
        height: 80px;
        font-size: 40px;
        color: #FFFFFF;
      }
    }
  }


  .el-select__placeholder {
    height: 54px;
    line-height: 54px;
    color: #FFFFFF;
  }

  .el-select__placeholder.is-transparent {
    height: 54px;
    line-height: 54px;
  }

  .el-select__selected-item {
    //height: 54px;
    //line-height: 54px;
    .el-tag {
      max-width: none !important;
      height: 55px;
      font-size: 43px;

      .el-icon {
        font-size: 51px;
        width: auto;
        height: auto;
      }
    }
  }

  .el-select__caret {
    font-size: 35px !important;
  }

  .el-select-dropdown__item.is-hovering {
    background-color: #064B66 !important;
  }

  .el-select-dropdown.is-multiple .el-select-dropdown__item.is-selected:after {
    width: 42px;
    height: 42px;
  }

  .el-input {
    min-height: 75px;
    height: auto !important;
  }

  .el-form-item.is-error .el-input__wrapper {
    box-shadow: none;
  }

  .el-select__wrapper {
    min-height: 75px;
    height: auto !important;
    background-color: transparent;
    border: 1px solid #08B7B8;
    font-size: 35px;
    width: 476px !important;
  }

  .el-select__popper {
    margin-top: -12px !important;
    background: #072247 !important;
    border: 1px solid #0F82AF !important;
    //width: 476px!important;
    inset: 86px auto auto 0 !important;

    .el-select-dropdown {
      width: auto;
    }
  }

  .el-popper {
    width: auto;
    min-width: auto;
    margin-left: 0;
    box-sizing: border-box;
  }

  .el-popper__arrow::before {
    display: none;
  }

  .el-select-dropdown__item {
    font-size: 38px !important;
    height: 60px !important;
    line-height: 60px !important;

    > span {
      color: #FFFFFF;
    }
  }

  .el-select .el-input .el-select__caret {
    font-size: 35px !important;
  }

  .el-select-dropdown__item.hover, .el-select-dropdown__item:hover {
    background-color: #064B66 !important;
  }

  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected {
    background-color: #064B66 !important;
  }

  .el-select-tags-wrapper {
    .el-tag {
      padding: 28px 20px !important;
      font-size: 35px;

      .el-icon {
        width: 40px;
        height: 40px;
        font-size: 40px !important;
      }
    }
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-dialog__header) {
  padding: 0 !important;
}

#used-ele {
  margin-top: 40px;
  cursor: pointer;
  width: 830px;
  //height: 373px;
  color: aliceblue;
  border: 2px solid #0f82af;
  background: rgba(6, 34, 71, 0.78);
  border-radius: 20px;
  padding: 21px 62px 35px 62px;
  position: relative;

  .ele-left-bottom-icon {
    position: absolute;
    bottom: -3px;
    left: -3px;
    width: 41px;
    height: 41px;
    background-image: url(@/assets/images/badGasInfo/sp_jz.png);
    transform: rotate(-90deg);
  }

  .ele-right-bottom-icon {
    position: absolute;
    bottom: -3px;
    right: -3px;
    width: 41px;
    height: 41px;
    background-image: url(@/assets/images/badGasInfo/sp_jz.png);
    transform: rotate(180deg);
  }

  .title {
    width: 96px;
    height: 42px;
    font-size: 32px;
    font-family: MicrosoftYaHei, MicrosoftYaHei;
    font-weight: bold;
    color: #38cafb;
    line-height: 42px;
  }

  .content {
    margin-top: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;

    .item {
      margin-top: 44px;
      font-size: 28px;
      color: #38CAFB;
      display: flex;
      flex-direction: column;
      align-items: center;

      .container {
        width: 60px;
        height: 210px;
        -webkit-border-radius: 31px;
        border: 1px solid rgba(105, 231, 253, 1);
        position: relative;
        margin-bottom: 20px;
        padding: 1px;

        .value {
          position: absolute;
          bottom: 0;
          width: 100%;
          height: inherit;
          background: linear-gradient(180deg, #38CAFB 0%, #2775E7 100%);
          -webkit-border-radius: 31px;
          //transition: width 0.5s linear 0s;
          -webkit-transition: width 1s ease-in-out;
        }
      }

      > div:nth-child(2) {
        display: flex;

        .icon {
          margin-right: 10px;
          width: 29px;
          height: 33px;
          background-image: url(../../../assets/images/usedEle/white-ele.png);
        }
      }
    }
  }
}
</style>
