<template>
  <div id="air-info">
    <div style="height: 21px" v-if="airList.length!==0"></div>
    <div class="fan-speed">
      <div>
        <img src="@/assets/images/airInfo/fan-v-icon.png" alt=""/>
        <div class="fan-info" @click="handleOpenChart(windSpeedType,windSpeedId)">
          <div class="input-fan"><span>风速</span>{{ windSpeed }} {{ windSpeedUnit }}</div>
        </div>
      </div>
      <div class="wind-direction-info" @click="handleOpenChart(windDirectionSpeedType,windDirectionSpeedId)">
        <div class="input-fan"><span>风向</span>{{ windDirection }} {{ windDirectionUnit }}</div>
      </div>
    </div>
    <item-info
        v-for="(item,index) in airList"
        :key="index"
        :wp="item"
        @click="handleOpenChart(item,'air')"
    />
    <div style="height: 1px" v-if="airList.length!==0"></div>
    <div class="digital-tunnel">
      <el-dialog :close-on-click-modal="false" v-model="isWindSpeedVisited" :title="dialogTitle+'监控数据'" width="2175px"
                 :modal="false" id="airDialog">
        <div class="left-top-icon"></div>
        <div class="right-top-icon"></div>
        <div class="loading-block" v-if="showSpeedLoading">
          <div class="loading" v-if="loadingText==='加载中...'"></div>
          <span>{{ loadingText }}</span>
        </div>
        <div class="chat-dialog" v-else>
          <div id="containerWind"></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 ItemInfo from "./childComps/ItemInfo.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 {getNowFormatDate} from "@/utils/date.js";
import CsvExportor from "csv-exportor";

let myEcharts = reactive({});
const props = defineProps({
  list: Array,
  windSpeed: Array,
  airData: Array,
  isSimulate: Boolean,
});
const isFullScreen = ref(false);
let dataZoomTop = reactive('87%')
let chartData = reactive([])
const chooseDayRef = ref();
const chooseMonthRef = ref();
const itemInfo = ref();
const windSpeed = ref(0)
const windSpeedUnit = ref('m/s')
const windDirection = ref(null)
const windDirectionUnit = ref('°')
const loadingText = ref('加载中...')
const windSpeedId = ref(0)
const windSpeedType = ref(null)
const windDirectionSpeedId = ref(0)
const windDirectionSpeedType = ref(null)
const dialogTitle = ref('风速')
const openDialogId = ref(0)
const airList = ref([])
const timeList = ref(["年", "月", "日"]);
const timeSimulateList = ref(["日"]);
const isWindSpeedVisited = ref(false);
const showSpeedLoading = ref(false)
const clickMonth = ref('')
const clickDay = ref('')
const selectTimeButton = ref(props.isSimulate?0:2);
watch(() => props.windSpeed, (now) => {
  now.forEach(newItem => {
    windSpeed.value =newItem.value
  })
})
watch(() => props.list, (now) => {
  airList.value?.forEach(item => {
    now.forEach(newItem => {
      if (newItem.equipmentType === "windDirection") {//风向传感器
        windDirection.value = newItem.value
      }
      if (item.equipmentId === newItem.equipmentId) {
        item.value = newItem.value
      }
    })
  })
}, {deep: true});
watch(() => props.airData, (now) => {
  if (now.sensorList.length === 0) {
    airList.value = []
    windSpeed.value = null
    windDirection.value = null
  } else {
    getAirInfo(now.sensorList)
  }
  // if (now.sensorList.length !== 0) {
  //   if (now.sensorList.length === 0) {
  //     airList.value = []
  //   } else {
  //     getAirInfo(now.sensorList)
  //   }
  // } else {
  //   airList.value = []
  //   windSpeed.value = 0
  // }
}, {deep: true});
//导出csv
const handleExport = () => {
  let clickUnit = ''
  if (dialogTitle.value === '风速') {
    clickUnit = windSpeedUnit.value
  } else if (dialogTitle.value === '风向') {
    clickUnit = windDirectionUnit.value
  } else {
    airList.value.forEach(item => {
      if (item.name === dialogTitle.value) {
        clickUnit = item.unit
      }
    })
  }
  const header = ['时间', `${dialogTitle.value}值(${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 = dialogTitle.value + '监控数据-' + time
  CsvExportor.downloadCsv(newArray, {header}, `${name}.csv`);
}
const daySelect = (val) => {
  if (val) {
    clickDay.value = val
    if (isFullScreen.value) {
      getChartInfo(openDialogId.value, 'day', '', '', val[0], val[1])
    } else {
      getChartInfo(openDialogId.value, 'day', '', true, val[0], val[1])
    }
  } else {
    if (isFullScreen.value) {
      getChartInfo(openDialogId.value, 'day', '')
    } else {
      getChartInfo(openDialogId.value, 'day', '', true)
    }
  }
}
const monthSelect = (val) => {
  clickMonth.value = val
  if (isFullScreen.value) {
    getChartInfo(openDialogId.value, 'month', val)
  } else {
    getChartInfo(openDialogId.value, 'month', val, true)
  }
}
//放大弹窗
const handleFullScreen = () => {
  const titleName = document.getElementsByClassName('el-dialog__title')[0]
  const fan = document.getElementById('airDialog')
  const fanChart = document.getElementById('containerWind')
  const erd = elementResizeDetectorMaker();
  fan.classList.remove('shrink-screen-dialog')
  titleName.style.fontSize = '70px'
  erd.listenTo(document.getElementById('airDialog'), (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('airDialog')
  const fanChart = document.getElementById('containerWind')
  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 getChartInfo = (equipmentId, type = 'day', time = '', flag, startTime, endTime) => {
  showSpeedLoading.value = true
  nextTick(() => {
    if (flag) {
      const fan = document.getElementById('airDialog')
      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) {
        showSpeedLoading.value = false
        chartData = res.data
        nextTick(() => {
          if (flag) {
            const fanChart = document.getElementById('containerWind')
            const erd = elementResizeDetectorMaker();
            erd.listenTo(document.getElementById('airDialog'), (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) {
        showSpeedLoading.value = false
        chartData = res.data
        nextTick(() => {
          if (flag) {
            const fanChart = document.getElementById('containerWind')
            const erd = elementResizeDetectorMaker();
            erd.listenTo(document.getElementById('airDialog'), (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 = (id, type) => {
  selectTimeButton.value = 2
  isWindSpeedVisited.value = true
  clickMonth.value = ''
  clickDay.value = ''
  nextTick(() => {
    if (chooseMonthRef.value) {
      chooseMonthRef.value.clearData()
    }
    if (chooseDayRef.value) {
      chooseDayRef.value.clearData()
    }
  })
  isFullScreen.value = true
  if (type === 'air') {
    dialogTitle.value = id.name
    openDialogId.value = id.equipmentId
    getChartInfo(id.equipmentId, 'day', '', true)
  } else {
    if (id === "windDirection") {
      dialogTitle.value = '风向'
    } else {
      dialogTitle.value = '风速'
    }
    openDialogId.value = type
    getChartInfo(type, 'day', '', true)
  }
}
const changeDate = (index) => {
  switch (index) {
    case 0:
      return 'years'
    case 1:
      return 'month'
    case 2:
      return 'day'
  }
}
const timeSelect = (index) => {
  if (isFullScreen.value) {
    getChartInfo(openDialogId.value, changeDate(index))
  } else {
    getChartInfo(openDialogId.value, changeDate(index), '', true)
  }
};

const changeData = (item) => {
  return {
    equipmentId: item.equipmentId,
    icon: changeIcon(item.equipmentType,item.equipmentName),
    name: item.equipmentName.slice(0, 2),
    max: item.maxRange,
    value: item.value,
    point: item.valueThreshold,
    unit: item.unit
  }
}
const changeIcon = (type,name) => {
  switch (type) {
    case "oxygen":
      return 'o2-icon.png';
    case "temperature":
      return 'tempture-icon.png';
    case "humidness":
      return 'water-icon.png';
    case "humiture":
      if(name==='温度传感器'){
        return 'tempture-icon.png';
      }else if(name==='湿度传感器'){
        return 'water-icon.png';
      }
  }
}
const getAirInfo = (now) => {
  if (now === null) return;
  let airObj = {}
  let airArr = []
  now?.map(item => {
    if (item.equipmentType === "oxygen" || item.equipmentType === "temperature" || item.equipmentType === "humidness"|| item.equipmentType === "humiture") {
      airObj = changeData(item)
      airArr.push(airObj)
    } else if (item.equipmentType === "windSpeed"||item.equipmentName==="风速传感器") {
      windSpeedType.value = item.equipmentType
      windSpeedId.value = item.equipmentId
      windSpeed.value = item.value
      windSpeedUnit.value = item.unit
    } else if (item.equipmentType === "windDirection"||item.equipmentName==="风向传感器") {
      windDirectionSpeedType.value = item.equipmentType
      windDirectionSpeedId.value = item.equipmentId
      windDirection.value = item.value
      windDirectionUnit.value = item.unit
    }
  })
  if (airArr.length !== 0) {
    airArr.push(airArr.shift())
    airList.value = airArr
  }
}
const initChart = (type, values, top) => {
  //3.初始化container容器
  myEcharts = echarts.init(document.getElementById('containerWind'));
  //5.传入数据
  let option = {
    //图例
    legend: {
      // left: 0,
      textStyle: {
        color: '#FFFFFF',
        fontSize: 40
      },
      itemWidth: 70,
      itemHeight: 5,
      icon: "rect",
    },
    //离容器四侧的距离
    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: 48px;line-height: 48px;font-family: Bebas Neue-Regular, Bebas Neue;font-weight: 400;"><span style="background: linear-gradient(180deg, #F5B85F 0%, #FFFFFF 100%);-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: [3, 85, 47, 92, 17, 76, 69, 25, 56, 12, 89, 34, 71, 43, 67, 20, 98, 72, 19, 61, 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>
#air-info {
  //min-height: 350px;
  margin-top: 30px;
  //position: absolute;
  z-index: 100;
  width: 824px;
  border: 2px solid #0f82af;
  background: rgba(6, 34, 71, 0.78);
  border-radius: 20px;
  //height: 400px;
  //top: 1003px;
  //right: 72px;
  //background-image: url(@/assets/images/airInfo/bg.png);
  //padding: 25px 20px 1px 21px;

  .fan-speed {
    box-sizing: border-box;
    display: flex;
    //height: 40px;
    font-size: 30px;
    color: #ffffff;
    align-items: center;
    padding: 5px 0 5px 15px;
    margin-bottom: 15px;
    margin-left: 21px;

    > div:first-child {
      display: flex;
    }


    img {
      width: 29px;
      height: 34px;
    }

    .wind-direction-info {
      flex: 1;
      display: flex;
      justify-content: flex-end;
      margin-right: 54px;


      .input-fan {
        cursor: pointer;
        padding-right: 20px;

        &:hover {
          //width: 230px;
          padding-left: 20px;
          //padding-right: 20px;
          background: #2E5589;
          border-radius: 6px;
        }

        > span:first-child {
          //margin-left: 25px;
          margin-right: 25px;
        }
      }
    }

    .fan-info {
      flex: 1;
      display: flex;
      justify-content: flex-start;
      cursor: pointer;

      .input-fan {
        //margin: 0 26px;
        padding-right: 20px;

        &:hover {
          //width: 230px;
          background: #2E5589;
          border-radius: 6px;
        }

        > span:first-child {
          margin-left: 25px;
          margin-right: 25px;
        }
      }
    }
  }
}
</style>
