<template>
  <div id="bad-gas-info" :style="{ backgroundImage: 'url(' + getImageUrl(bgImage) + ')' }">
    <div class="title">有害气体</div>
    <div v-if="badGasList == null || badGasList.length === 0" class="showNull">
      <div class="loading" v-if="loading === 0"></div>
      {{ loading === 0 ? '加载中...' : '暂无数据~' }}
    </div>
    <div v-else class="info-list" @click="handleOpenChart">
      <gas-info-item v-for="item in badGasList" :key="item.equipmentId" :gasInfo="item" />
    </div>
    <div class="digital-tunnel">
      <el-dialog :close-on-click-modal="false" v-model="isBadGasVisited" title="有害气体监控数据" width="2175px" :modal="false"
        id="badDialog">
        <div class="left-top-icon"></div>
        <div class="right-top-icon"></div>
        <div class="loading-block" v-if="showLoading">
          <div class="loading"></div>
          <span>加载中...</span>
        </div>
        <div class="chat-dialog" v-else>
          <div id="containerBad"></div>
          <div style="width: 1px"></div>
        </div>
        <div class="time-select">
          <div class="export-btn" @click="handleExport">
            导出
          </div>
          <choose-dates v-if="selectTimeButton === 2" ref="chooseDayRef" @select="daySelect" />
          <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.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 GasInfoItem from "./childComps/GasInfoItem.vue";
import * as echarts from "echarts";
import TimeRangeBtn from "@/components/timeRangeBtn/index.vue";
import { getBadGasEchartsInfo } from "@/api/largeScreen";
import ChooseDates 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";

const props = defineProps({
  list: Array,
  badGasData: Array,
  tunnelId: Number,
  loading: Number,
});
const chooseDayRef = ref();
const chooseMonthRef = ref();
const timeList = ref(["年", "月", "日"]);
const selectTimeButton = ref(2);
const isBadGasVisited = ref(false);
const showLoading = ref(false)
const isFullScreen = ref(false);
let chartData = reactive([])
let dataZoomTop = reactive('87%')
const badGasList = ref([]);
let myEcharts = reactive({});
const clickMonth = ref('')
const clickDay = ref('')
const bgImage = computed(() => (isBadGasVisited.value ? "sp_active.png" : "bg.png"));
watch(
  () => props.list,
  (now) => {
    badGasList.value?.forEach((item) => {
      now.forEach((newItem) => {
        if (item.equipmentId === newItem.equipmentId) {
          item.value = newItem.value;
        }
      });
    });
  },
  { deep: true }
);

watch(
  () => props.badGasData,
  (now) => {
    if (now.sensorList === null) {
      badGasList.value = []
    } else {
      getBadGasInfo(now.sensorList);
    }
  },
  { deep: true }
);

watch(
  () => props.tunnelId,
  (now) => {
    props.tunnelId = now
  },
  { deep: true }
);
//导出csv
const handleExport = () => {
  console.log(badGasList.value)
  let dustUnit
  let carbonUnit
  let carbonMonoxideUnit
  let nitrogenUnit
  let sulfurMonoxideUnit
  let sulfurDioxideUnit
  let hydrogenSulfideUnit
  badGasList.value.forEach((item) => {
    if (item.name === '粉尘') {
      dustUnit = item.unit
    } else if (item.name === '二氧化碳') {
      carbonUnit = item.unit
    } else if (item.name === '一氧化碳') {
      carbonMonoxideUnit = item.unit
    } else if (item.name === '二氧化氮') {
      nitrogenUnit = item.unit
    } else if (item.name === '一氧化氮') {
      sulfurMonoxideUnit = item.unit
    } else if (item.name === '二氧化硫') {
      sulfurDioxideUnit = item.unit
    } else if (item.name === '硫化氢') {
      hydrogenSulfideUnit = item.unit
    }
  });
  const header = ['时间', `粉尘(${dustUnit})`, `二氧化碳(${carbonUnit})`, `一氧化碳(${carbonMonoxideUnit})`, `二氧化氮(${nitrogenUnit})`, `一氧化氮(${sulfurMonoxideUnit})`, `二氧化硫(${sulfurDioxideUnit})`, `硫化氢(${hydrogenSulfideUnit})`];
  let newArray = []
  chartData.dates.forEach((item, index) => {
    let obj = {
      dates: chartData.dates[index],
      dustValues: chartData.dustValues[index],
      carbonDioxideValues: chartData.carbonDioxideValues[index],
      carbonMonoxideValues: chartData.carbonMonoxideValues[index],
      nitrogenDioxideValues: chartData.nitrogenDioxideValues[index],
      sulfurMonoxideValues: chartData.sulfurMonoxideValues[index],
      sulfurDioxideValues: chartData.sulfurDioxideValues[index],
      hydrogenSulfideValues: chartData.hydrogenSulfideValues[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 = '有害气体监控数据-' + time
  CsvExportor.downloadCsv(newArray, { header }, `${name}.csv`);
}
//放大弹窗
const handleFullScreen = () => {
  const titleName = document.getElementsByClassName('el-dialog__title')[0]
  const fan = document.getElementById('badDialog')
  const fanChart = document.getElementById('containerBad')
  const erd = elementResizeDetectorMaker();
  fan.classList.remove('shrink-screen-dialog')
  titleName.style.fontSize = '70px'
  erd.listenTo(document.getElementById('badDialog'), (element) => {
    fanChart.style.height = (element.offsetHeight - 140) + 'px'
    myEcharts.resize();
  });
  nextTick(() => {
    isFullScreen.value = false
    initChart(chartData.dates, chartData, '93%')
  })
}
const shrinkScreen = () => {
  const fan = document.getElementById('badDialog')
  const fanChart = document.getElementById('containerBad')
  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, dataZoomTop)
  })
}
const daySelect = (val) => {
  if (val) {
    clickDay.value = val
    if (isFullScreen.value) {
      getBadGasChartInfo('day', '', '', val[0], val[1])
    } else {
      getBadGasChartInfo('day', '', true, val[0], val[1])
    }
  } else {
    if (isFullScreen.value) {
      getBadGasChartInfo('day', '')
    } else {
      getBadGasChartInfo('day', '', true)
    }
  }
}
const monthSelect = (val) => {
  clickMonth.value = val
  if (isFullScreen.value) {
    getBadGasChartInfo('month', val)
  } else {
    getBadGasChartInfo('month', val, true)
  }
}
const changeDate = (index) => {
  switch (index) {
    case 0:
      return 'years'
    case 1:
      return 'month'
    case 2:
      return 'day'
  }
}
const timeSelect = (index) => {
  if (isFullScreen.value) {
    getBadGasChartInfo(changeDate(index))
  } else {
    getBadGasChartInfo(changeDate(index), '', true)
  }
};
const getBadGasInfo = (now) => {
  if (now === null) return;
  let windPressureObj = {};
  let windPressureArr = [];
  now?.map((item) => {
    if (
      item.equipmentType === "dust" ||
      item.equipmentType === "carbonDioxide" ||
      item.equipmentType === "carbonMonoxide" ||
      item.equipmentType === "hydrogenSulfide" ||
      item.equipmentType === "sulfurDioxide" ||
      item.equipmentType === "sulfurMonoxide" ||
      item.equipmentType === "nitrogenDioxide"
    ) {
      windPressureObj = changeData(item);
      windPressureArr.push(windPressureObj);
    }
  });
  badGasList.value = windPressureArr;
};
const changeData = (item) => {
  return {
    equipmentId: item.equipmentId,
    name: item.equipmentName.slice(0, item.equipmentName.length - 2),
    max: item.maxRange,
    value: item.value,
    point: item.valueThreshold,
    unit: item.unit,
  };
};
const getBadGasChartInfo = (type, time = '', flag, startTime, endTime) => {
  showLoading.value = true
  let id = props.tunnelId
  nextTick(() => {
    if (flag) {
      const fan = document.getElementById('badDialog')
      fan.classList.add('shrink-screen-dialog')
      if (isFullScreen.value) {
        const titleName = document.getElementsByClassName('el-dialog__title')[0]
        titleName.style.fontSize = '70px'
      }
    }
  })
  getBadGasEchartsInfo(id, time, type, startTime, endTime).then(res => {
    if (res?.code === 1000) {
      showLoading.value = false
      chartData = res.data
      nextTick(() => {
        if (flag) {
          const fanChart = document.getElementById('containerBad')
          const erd = elementResizeDetectorMaker();
          erd.listenTo(document.getElementById('badDialog'), (element) => {
            fanChart.style.height = element.offsetHeight - 140 + 'px'
            myEcharts.resize();
          });
          if (isFullScreen.value) {
            initChart(res.data.dates, res.data, dataZoomTop)
          }
        } else {
          shrinkScreen()
        }
      })
    }
  })
}
const handleOpenChart = () => {
  clickMonth.value = ''
  clickDay.value = ''
  nextTick(() => {
    if (chooseMonthRef.value) {
      chooseMonthRef.value.clearData()
    }
    if (chooseDayRef.value) {
      chooseDayRef.value.clearData()
    }
  })
  isBadGasVisited.value = true
  isFullScreen.value = true
  getBadGasChartInfo('day', '', true)
};
const getImageUrl = (name) => {
  return new URL(`../../../assets/images/badGasInfo/${name}`, import.meta.url)
    .href;
};
/**
 * 初始化echarts实例方法
 */
const initChart = (type, values, top) => {
  //3.初始化container容器
  myEcharts = echarts.init(document.getElementById("containerBad"));
  //5.传入数据
  let option = {
    //图例
    legend: {
      left: 0,
      textStyle: {
        color: '#60DDDE',
        fontSize: 40
      },
      itemWidth: 30,
      itemHeight: 30,
      icon: "circle",
    },
    //离容器四侧的距离
    grid: {
      left: 0, // 左边距
      right: 20, // 右边距
      top: 80, // 顶边距
      bottom: 170, // 底边距
      containLabel: true,
    },
    //提示框组件
    tooltip: {
      show: true,
      trigger: "axis",
      backgroundColor: "rgba(20,36,51,0.7)", // 设置背景颜色为透明
      borderColor: "#6087BA", // 设置边框颜色为透明
      padding: 0, // 设置内边距为0
      borderWidth: 2,
      textStyle: {
        fontSize: 40,
      },
      formatter: (params) => {
        let res = ` <div style="font-size: 52px;font-family: PingFang SC-Regular, PingFang SC;font-weight: 400;color: #EFEEEE;margin-bottom: -30px;margin-left: 20px">${params[0].name}</div>` + '<br/>'
        for (let i = 0; i < params.length; i++) {
          res += `
              <div style="font-size: 52px;line-height: 48px;font-family: Bebas Neue-Regular, Bebas Neue;font-weight: 400;margin:0 20px 30px 20px;"><span style="color: #FFFFFF">${params[i].seriesName}: </span><span style="background: linear-gradient(180deg, #F5B85F 0%, #FFFFFF 100%);background-clip: text;-webkit-background-clip: text;-webkit-text-fill-color: transparent;">${params[i].value}</span></div>
             `;
        }
        return res

        // 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: type,
      axisLabel: {
        textStyle: {
          fontSize: 45,
          color: "#D6F1FA",
        },
      },
    },
    //Y轴
    yAxis: {
      type: "value",
      axisLabel: {
        textStyle: {
          fontSize: 45,
          color: "#D6F1FA",
        },
      },
    },
    //配置项
    series: [
      {
        name: values.dustValues.length!==0?"粉尘":"",
        // 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.dustValues.length!==0?values.dustValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
      {
        name: values.carbonDioxideValues.length!==0?"二氧化碳":"",
        // 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.carbonDioxideValues.length!==0?values.carbonDioxideValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
      {
        name: values.carbonMonoxideValues.length!==0?"一氧化碳":"",
        // data: [
        //   96, 38, 75, 10, 62, 81, 41, 27, 69, 16, 33, 57, 73, 87, 22, 46, 11,
        //   79, 51, 29, 60, 48, 83, 15,
        // ],
        data: values.carbonMonoxideValues.length!==0?values.carbonMonoxideValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
      {
        name: values.nitrogenDioxideValues.length!==0?"二氧化氮":"",
        // data: [
        //   53, 88, 10, 67, 92, 31, 74, 46, 20, 37, 85, 16, 63, 70, 41, 99, 25,
        //   77, 82, 13, 68, 49, 55, 7, 39,
        // ],
        data: values.nitrogenDioxideValues.length!==0?values.nitrogenDioxideValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
      {
        name: values.sulfurMonoxideValues.length!==0?"一氧化氮":"",
        // data: [
        //   37, 19, 85, 62, 28, 91, 43, 76, 14, 68, 33, 52, 71, 26, 97, 49, 82,
        //   17, 66, 30, 78, 55, 23, 47,
        // ],
        data: values.sulfurMonoxideValues.length!==0?values.sulfurMonoxideValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
      {
        name: values.sulfurDioxideValues.length!==0?"二氧化硫":"",
        // data: [
        //   6, 30, 91, 77, 28, 51, 42, 83, 16, 65, 35, 72, 18, 96, 47, 79, 100,
        //   23, 80, 44, 62, 59, 13, 86,
        // ],
        data: values.sulfurDioxideValues.length!==0?values.sulfurDioxideValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
      {
        name: values.hydrogenSulfideValues.length!==0?"硫化氢":"",
        // data: [
        //   13, 27, 39, 51, 62, 73, 84, 95, 10, 20, 30, 40, 50, 60, 70, 80, 90,
        //   100, 11, 21, 31, 41, 51,
        // ],
        data: values.hydrogenSulfideValues.length!==0?values.hydrogenSulfideValues:[],
        type: "line",
        smooth: true,
        symbolSize: 24,
        lineStyle: {
          width: 5,
        },
      },
    ],
  };
  myEcharts.setOption(option, true);
  //图表大小自适应窗口大小变化
  window.onresize = () => {
    myEcharts.resize();
  };
};
</script>

<style lang="scss" scoped>
#bad-gas-info {
  margin-top: 30px;
  cursor: pointer;
  //position: absolute;
  width: 824px;
  min-height: 300px;
  //height: 621px;
  //top: 1441px;
  //right: 72px;
  background-image: url(../../../assets/images/badGasInfo/bg.png);
  padding: 22px 17px 25px 50px;

  .title {
    font-size: 38px;
    font-weight: 800;
    color: #38cafb;
    line-height: 45px;
    //margin: 22px 0px 0px 62px;
  }

  .info-list {
    width: 100%;
    //height: calc(621px - 45px - 22px);
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    padding: 16px 0 0 10px;
  }
}
</style>
