<template>
  <div id="wind-pressure">
    <div class="name">风压</div>
    <div v-if="wpList==null||wpList.length===0" class="showNull">
      <div class="loading" v-if="loading===0"></div>
      {{ loading === 0 ? '加载中...' : '暂无数据~' }}
    </div>
    <div v-else class="list">
      <wind-pressure-item v-for="(item,index) in wpList" :key="item.equipmentId" :wp="item"
                          @click="handleOpenChart(item)"/>
    </div>
    <div class="digital-tunnel">
      <el-dialog :close-on-click-modal="false" v-model="isVisited" :title="windSort+'监控数据'" width="2175px"
                 :modal="false" id="windDialog">
        <div class="left-top-icon"></div>
        <div class="right-top-icon"></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="container"></div>
          <div style="width: 1px;"></div>
        </div>
        <div class="time-select">
          <div class="export-btn" @click="handleExport">
            导出
          </div>
          <choose-day v-if="isSimulate?selectTimeButton === 0:selectTimeButton===2" ref="chooseDayRef" @select="daySelect"/>
          <choose-month v-if="selectTimeButton===1" ref="chooseMonthRef" @select="monthSelect"/>
          <time-range-btn
              :buttonList="isSimulate?timeSimulateList:timeList"
              v-model="selectTimeButton"
              @select="timeSelect"
          />
        </div>
        <div class="change-screen">
          <el-icon size="55" color="#05feff" class="full-icon" title="放大" @click.stop="handleFullScreen"
                   v-if="isFullScreen">
            <FullScreen/>
          </el-icon>
          <div v-else class="shrink-icon" title="缩小" @click.stop="shrinkScreen"></div>
        </div>
        <div class="left-bottom-icon"></div>
        <div class="right-bottom-icon"></div>
      </el-dialog>
    </div>
  </div>
</template>

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

const props = defineProps({
  list: Array,
  winData: Array,
  loading: Number,
  isSimulate: Boolean,
});
const loadingText = ref('加载中...')
const chooseDayRef = ref();
const chooseMonthRef = ref();
const windSort = ref(1)
const windSortId = ref(1)
const timeList = ref(["年", "月", "日"]);
const timeSimulateList = ref(["日"]);
const isVisited = ref(false);
const isFullScreen = ref(false);
let chartData = reactive([])
let dataZoomTop = reactive('87%')
const showLoading = ref(false)
let myEcharts = reactive({});
const wpList = ref([]);
const clickMonth = ref('')
const clickDay = ref('')
const selectTimeButton = ref(props.isSimulate?0:2);
watch(() => props.list, (now) => {
  wpList.value.forEach(item => {
    now.forEach(newItem => {
      if (item.equipmentId === newItem.equipmentId) {
        item.value = newItem.value
      }
    })
  })
}, {deep: true});

watch(() => props.winData, (now) => {
  getScreenInfo(now.windPressureSensorList)
}, {deep: true});
//导出csv
const handleExport = () => {
  let clickUnit = ''
  wpList.value.forEach(item => {
    if (item.equipmentName === windSort.value) {
      clickUnit = item.unit
    }
  })
  const header = ['时间', `风压值(${clickUnit})`];
  let newArray = []
  chartData.dates.forEach((item, index) => {
    let obj = {
      dates: chartData.dates[index],
      values: chartData.values[index]
    }
    newArray.push(obj)
  })
  let time = ''
  if (selectTimeButton.value === 1) {
    if (clickMonth.value) {
      const index = clickMonth.value.lastIndexOf("\-");
      time = clickMonth.value.substring(0, index)
    } else {
      time = getNowFormatDate(false)
    }
  } else if (selectTimeButton.value === 2) {
    if (clickDay.value) {
      if (clickDay.value[1]) {
        time = clickDay.value.map(item => item).join('到')
      } else {
        time = clickDay.value
      }
    } else {
      time = getNowFormatDate(true)
    }
  } else if (selectTimeButton.value === 0) {
    time = new Date().getFullYear() + '年'
  }
  const name = windSort.value + '监控数据-' + time
  CsvExportor.downloadCsv(newArray, {header}, `${name}.csv`);
}
//放大弹窗
const handleFullScreen = () => {
  const titleName = document.getElementsByClassName('el-dialog__title')[0]
  const fan = document.getElementById('windDialog')
  const fanChart = document.getElementById('container')
  const erd = elementResizeDetectorMaker();
  fan.classList.remove('shrink-screen-dialog')
  titleName.style.fontSize = '70px'
  erd.listenTo(document.getElementById('windDialog'), (element) => {
    fanChart.style.height = (element.offsetHeight - 140) + 'px'
    myEcharts.resize();
  });
  nextTick(() => {
    isFullScreen.value = false
    initChart(chartData.dates, chartData.values, '93%')
  })
}
const shrinkScreen = () => {
  const fan = document.getElementById('windDialog')
  const fanChart = document.getElementById('container')
  const titleName = document.getElementsByClassName('el-dialog__title')[0]
  titleName.style.fontSize = '50px'
  fan.classList.add('shrink-screen-dialog')
  fanChart.style.height = '1200px'
  myEcharts.resize();
  nextTick(() => {
    isFullScreen.value = true
    initChart(chartData.dates, chartData.values, dataZoomTop)
  })
}
const daySelect = (val) => {
  if (val) {
    clickDay.value = val
    if (isFullScreen.value) {
      getWindInfo(windSortId.value, 'day', '','', val[0], val[1])
    } else {
      getWindInfo(windSortId.value, 'day', '', true, val[0], val[1])
    }
  }else {
    if (isFullScreen.value) {
      getWindInfo(windSortId.value, 'day', '')
    } else {
      getWindInfo(windSortId.value, 'day', '', true)
    }
  }
}
const monthSelect = (val) => {
  clickMonth.value = val
  if (isFullScreen.value) {
    getWindInfo(windSortId.value, 'month', val)
  } else {
    getWindInfo(windSortId.value, 'month', val, true)
  }
}
const getWindInfo = (equipmentId, type = 'day', time = '', flag, startTime, endTime) => {
  isVisited.value = true
  showLoading.value = true
  nextTick(() => {
    if (flag) {
      const fan = document.getElementById('windDialog')
      fan.classList.add('shrink-screen-dialog')
      if (isFullScreen.value) {
        const titleName = document.getElementsByClassName('el-dialog__title')[0]
        titleName.style.fontSize = '70px'
      }
    }
  })
  if(props.isSimulate) {
    getSimulationEchartsInfo(equipmentId, time, type, startTime, endTime).then(res => {
      if (res?.code === 1000) {
        showLoading.value = false
        chartData = res.data
        nextTick(() => {
          if (flag) {
            const fanChart = document.getElementById('container')
            const erd = elementResizeDetectorMaker();
            erd.listenTo(document.getElementById('windDialog'), (element) => {
              fanChart.style.height = element.offsetHeight - 140 + 'px'
              myEcharts.resize();
            });
            if (isFullScreen.value) {
              initChart(res.data.dates, res.data.values, dataZoomTop)
            }
          } else {
            shrinkScreen()
          }
        })
      } else {
        loadingText.value = res.msg
      }
    })

  }else{
    getEchartsInfo(equipmentId, time, type, startTime, endTime).then(res => {
      if (res?.code === 1000) {
        showLoading.value = false
        chartData = res.data
        nextTick(() => {
          if (flag) {
            const fanChart = document.getElementById('container')
            const erd = elementResizeDetectorMaker();
            erd.listenTo(document.getElementById('windDialog'), (element) => {
              fanChart.style.height = element.offsetHeight - 140 + 'px'
              myEcharts.resize();
            });
            if (isFullScreen.value) {
              initChart(res.data.dates, res.data.values, dataZoomTop)
            }
          } else {
            shrinkScreen()
          }
        })
      } else {
        loadingText.value = res.msg
      }
    })

  }
  nextTick(() => {
    loadingText.value = '加载中...'
  })
}

const handleOpenChart = (item) => {
  selectTimeButton.value = 2
  clickMonth.value = ''
  clickDay.value = ''
  nextTick(() => {
    if (chooseMonthRef.value) {
      chooseMonthRef.value.clearData()
    }
    if (chooseDayRef.value) {
      chooseDayRef.value.clearData()
    }
  })
  isFullScreen.value = true
  getWindInfo(item.equipmentId, 'day', '', true)
  windSort.value = item.equipmentName
  windSortId.value = item.equipmentId
}
const changeDate = (index) => {
  switch (index) {
    case 0:
      return 'years'
    case 1:
      return 'month'
    case 2:
      return 'day'
  }
}
const timeSelect = (index) => {
  if (isFullScreen.value) {
    getWindInfo(windSortId.value, changeDate(index))
  } else {
    getWindInfo(windSortId.value, changeDate(index), '', true)
  }
};
const getScreenInfo = (now) => {
  let windPressureObj = {}
  let windPressureArr = []
  now?.map(item => {
    windPressureObj = {
      equipmentId: item.equipmentId,
      equipmentName: item.equipmentName,
      max: item.maxRange,
      value: item.value,
      point: item.valueThreshold,
      unit: item.unit
    }
    windPressureArr.push(windPressureObj)
  })
  if (windPressureArr.map(item => item.equipmentName).includes('10号风压')) {
    windPressureArr.push(windPressureArr.shift())
  }
  wpList.value = windPressureArr
}
/**
 * 初始化echarts实例方法
 */
const initChart = (type, values, top) => {
  //3.初始化container容器
  myEcharts = echarts.init(document.getElementById('container'));
  //5.传入数据
  let option = {
    //图例
    legend: {
      left: 0,
      textStyle: {
        color: '#FFFFFF',
        fontSize: 40
      },
      // itemWidth: 20,
      // itemHeight: 20
    },
    //离容器四侧的距离
    grid: {
      left: 0, // 左边距
      right: 20, // 右边距
      top: 80, // 顶边距
      bottom: 170, // 底边距
      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: 52px;line-height: 48px;font-family: Bebas Neue-Regular, Bebas Neue;font-weight: 400;margin-top: 20px"><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>`;
        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: ['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','24:00'],
      data: type,
      axisLabel: {
        textStyle: {
          fontSize: 45,
          color: '#D6F1FA'
        },
      },
    },
    //Y轴
    yAxis: {
      type: 'value',
      axisLabel: {
        textStyle: {
          fontSize: 45,
          color: '#D6F1FA'
        },
      },
    },
    //配置项
    series: [
      {
        // data: [56, 12, 89, 34, 71, 43, 67, 20, 98, 72, 19, 61, 3, 85, 47, 92, 17, 76, 69, 25, 31, 49, 81, 63],
        data: values,
        type: 'line',
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5
        },
      }
    ]
  }
  myEcharts.setOption(option);
  //图表大小自适应窗口大小变化
  window.onresize = () => {
    myEcharts.resize();
  }
}

</script>

<style lang="scss" scoped>
#wind-pressure {
  width: 830px;
  //height: 779px;
  //position: absolute;
  //min-height: 350px;
  //top: 185px;
  //right: 68px;
  background-image: url(../../../assets/images/windPressure/bg.png);
  padding: 22px 17px 1px 23px;

  .name {
    font-size: 38px;
    font-family: MicrosoftYaHei, MicrosoftYaHei;
    font-weight: bold;
    color: #38cafb;
    line-height: 42px;
    margin-left: 50px;
    margin-bottom: 6px;
  }
}
</style>
