<template>
  <div class="main">
    <div class="main_in" @mouseleave="boxMouseleave" @mouseenter="boxMouseenter">
      <weatherTitle
        v-if="chartData.weatherTitleName"
        :title="'近24小时水情信息'"
        :isSelect="true"
        fnName="weatherBus"
        :isCirculate="true"
        :keywords="chartData.weatherTitleName"
        :selectList="chartData.weatherTitleArr"
        refreshName="waterRefreshName"
      />
      <div>
        <div class="main-title" @click="openModal(stcd)">
          <div>
            <span>{{ chartData.weatherTitleName }}&nbsp;</span>水位过程线
          </div>
        </div>
        <div v-if="chartData.waterLevel.length > 0" id="water" style="width: 100%; height: 260px"></div>
        <div v-else style="width: 100%; height: 260px">
          <img class="none-data" src="../../../assets/images/weatheHome/none-data.png" />
        </div>
      </div>
      <div>
        <div class="main-title" @click="openModal(stcd)">
          <div>
            <span>{{ chartData.weatherTitleName }}&nbsp;</span>流量过程线
          </div>
        </div>
        <div v-if="chartData.flow.length > 0" id="water2" style="width: 100%; height: 260px"></div>
        <div v-else style="width: 100%; height: 260px">
          <img class="none-data" src="../../../assets/images/weatheHome/none-data.png" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref, onBeforeUnmount } from 'vue';
import weatherTitle from '../../../components/Title/weatherTitle.vue';
import { DownOutlined } from '@ant-design/icons-vue';
import { getWaterRegimen } from '/@/api/swHome/index';
import { useBasicStore } from '/@/store/modules/basicData';
const basicStore = useBasicStore();
import eventBus from '/@/utils/eventBus';
import { useMapStore } from '/@/store/modules/map';

const mapStore = useMapStore();
const openModal = (item) => {
  mapStore.setstInfo({ stcd: item });
};

// 引入图表插件
const { proxy } = getCurrentInstance();
const echarts = proxy.$echarts;
let charts1 = null;
eventBus.on('waterRefreshName', () => {
  if (Object.keys(basicStore.getStDetailInfo).length != 0) {
    chartData.weatherTitleName = chartData.weatherTitleArr[0].name;
    processingArrays(basicStore.getStDetailInfo);
  }
});
function waterLevel(max, min) {
  let maxValue = Math.ceil(max);
  let minValue = Math.floor(min);
  let interval = 0;
  console.log((max - min) / 5);
  if ((max - min) / 5 <= 0.2) {
    interval = 0.2;
    maxValue = Math.floor(maxValue);
    maxValue = Math.ceil(maxValue);
  } else if ((max - min) / 5 <= 0.5) {
    interval = 0.5;
    maxValue = Math.floor(maxValue);
    maxValue = Math.ceil(maxValue);
  } else if ((max - min) / 5 <= 1) {
    interval = 0.5;
    maxValue = Math.floor(maxValue);
    maxValue = Math.ceil(maxValue);
  } else {
    // 获取余数
    minValue = minValue - (5 - ((maxValue - minValue) % 5));
    interval = (maxValue - minValue) / 5;
  }
  return {
    interval: interval,
    maxValue: maxValue,
    minValue: minValue,
  };
}
function echarts1() {
  let max1 = Math.max(...chartData.waterLevel);
  let min1 = Math.min(...chartData.waterLevel);
  let shuiwei = waterLevel(max1, min1);
  charts1 = echarts.init(document.getElementById('water'));
  var option;

  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    dataZoom: [
      {
        // 这个dataZoom组件，默认控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
      },
    ],
    grid: {
      left: '3%', //默认10%
      right: '4%', //默认10%
      bottom: '4%', //默认60
      containLabel: true,
      //grid区域是否包含坐标轴的刻度标签
    },
    xAxis: {
      type: 'category',
      data: chartData.waterLevelName,
      axisLabel: {
        //x轴文字的配置
        show: true,
        textStyle: {
          color: '#fff',
        },
        formatter: function (val) {
          var strs = val.split(''); //字符串数组
          var str = '';
          for (var i = 0, s; (s = strs[i++]); ) {
            //遍历字符串数组
            if (i > 5 && i < 17) {
              str += s;
            }

            if (!(i % 10)) str += '\n'; //按需要求余
          }
          return str;
        },
      },
    },
    yAxis: [
      {
        splitLine: {
          //网格线
          lineStyle: {
            type: 'dashed', //设置网格线类型 dashed solid:实线
            width: 1, //y轴线的宽度
            color: '#484849',
          },
          show: true, //隐藏或显示
        },
        axisLabel: {
          //y轴文字的配置
          textStyle: {
            color: '#fff',
            margin: 15,
          },
          formatter: function (value) {
            return value.toFixed(2) + '';
          },
          // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
        },
        scale: true,
        interval: shuiwei.interval, // 步长
        min: shuiwei.minValue,
        max: shuiwei.maxValue,
      },
      {
        type: 'value',
        name: '水位：m', //单位
        nameLocation: 'end',
        //单位的样式设置
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.8)', //颜色
          padding: [15, 20, 15, -620],
        },
        scale: true,
      },
    ],
    series: [
      {
        data: chartData.waterLevel,
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#306FFF',
        },
      },
    ],
  };

  option && charts1.setOption(option);
}
function flowFn(max, min){
  let maxValue = Math.ceil(max);
  let minValue = Math.floor(min);
  let interval = 0;
  console.log((max - min) / 5);
  if ((max - min) / 5 <= 1) {
    interval = 1;
    minValue = Math.floor(minValue);
    maxValue = Math.ceil(maxValue);
    if(maxValue - minValue == 1){
        minValue = minValue - 2
        maxValue  = maxValue + 2
    }
    if(maxValue - minValue == 2){
        minValue  = minValue - 2
        maxValue  = maxValue + 1
    }

    if(maxValue - minValue == 3){
        minValue  = minValue - 1
        maxValue  = maxValue + 1
    }

    if(maxValue - minValue == 4){
        minValue  = minValue - 1
    }
  } else {
    // 获取余数
    minValue = minValue - (5 - ((maxValue - minValue) % 5));
    interval = (maxValue - minValue) / 5;
  }
  return {
    interval: interval,
    maxValue: maxValue,
    minValue: minValue,
  };
}
let charts2 = null;
function echarts2() {
  
  let max1 = Math.max(...chartData.flow);
  let min1 = Math.min(...chartData.flow);
  let liuliang2 = flowFn(max1, min1);
  charts2 = echarts.init(document.getElementById('water2'));
  var option;

  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    dataZoom: [
      {
        // 这个dataZoom组件，默认控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
      },
    ],
    grid: {
      left: '3%', //默认10%
      right: '4%', //默认10%
      bottom: '4%', //默认60
      containLabel: true,
      //grid区域是否包含坐标轴的刻度标签
    },
    xAxis: {
      type: 'category',
      data: chartData.flowName,
      axisLabel: {
        //x轴文字的配置
        show: true,
        textStyle: {
          color: '#fff',
        },
        formatter: function (val) {
          var strs = val.split(''); //字符串数组
          var str = '';
          for (var i = 0, s; (s = strs[i++]); ) {
            //遍历字符串数组
            if (i > 5 && i < 17) {
              str += s;
            }

            if (!(i % 10)) str += '\n'; //按需要求余
          }
          return str;
        },
      },
    },
    yAxis: [
      {
        type: 'value',
        name: '流量：m³/s', //单位
        nameLocation: 'end',
        //单位的样式设置
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.8)', //颜色
          padding: [15, 20, 15, 60],
        },
        splitLine: {
          //网格线
          lineStyle: {
            type: 'dotted', //设置网格线类型 dotted：虚线 solid:实线
            width: 1, //y轴线的宽度
            color: '#484849',
          },
          show: true, //隐藏或显示
        },
        axisLabel: {
          //y轴文字的配置
          textStyle: {
            color: '#fff',
            margin: 15,
          },
          formatter: function (value) {
            return value + '';
          },
          // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
        },
        scale: true,
        interval: liuliang2.interval, // 步长
        min: liuliang2.minValue,
        max: liuliang2.maxValue,
      },
    ],
    series: [
      {
        data: chartData.flow,
        type: 'line',
        smooth: true,
        itemStyle: {
          color: '#06D6ED',
        },
      },
    ],
  };

  option && charts2.setOption(option);
}
// 鼠标移出
function boxMouseleave() {
  // console.log('鼠标移出');
  circulateData();
}
// 鼠标移入
function boxMouseenter() {
  // console.log('鼠标移入');
  if (circulateFn) {
    clearInterval(circulateFn);
  }
}

// 循环轮播数据
let circulateNum = 1;
let circulateFn = null;
function circulateData() {
  console.log(chartData.weatherTitleArr);
  circulateFn = setInterval(async () => {
    await getWaterRegimenData(chartData.weatherTitleArr[circulateNum].value);
    chartData.weatherTitleName = chartData.weatherTitleArr[circulateNum].name;
    if (circulateNum == chartData.weatherTitleArr.length - 1) {
      circulateNum = 0;
    } else {
      circulateNum += 1;
    }
  }, 7000);
}
// // 数据获取
let chartData = reactive({
  seriesData: {},
  waterLevel: [], //水位数据
  waterLevelName: [],
  flow: [], //流量数据
  flowName: [],
  weatherTitleArr: [],
  weatherTitleName: '',
});
function handleData(data) {
  chartData.waterLevel = [];
  chartData.flow = [];
  chartData.waterLevelName = [];
  chartData.flowName = [];
  data.z.forEach((element) => {
    chartData.waterLevel.push(element.z);
    chartData.waterLevelName.push(element.time);
  });
  if (chartData.waterLevel.length != 0) {
    setTimeout(() => {
      echarts1();
    }, 300);
  }

  data.q.forEach((element) => {
    chartData.flow.push(element.q);
    chartData.flowName.push(element.time);
  });
  if (chartData.flow.length != 0) {
    setTimeout(() => {
      echarts2();
    }, 300);
  }
}
async function getWaterRegimenData(stcd) {
  await getWaterRegimen({ stcd: stcd }).then((res) => {
    chartData.seriesData = res.data;
    handleData(res.data);
  });
}
function processingArrays(obj) {
  let objArr = [];
  for (let i in obj) {
    objArr = [...objArr, ...obj[i]];
  }
  chartData.weatherTitleArr = [];
  objArr.forEach((element) => {
    if (element.st_type == 1) {
      chartData.weatherTitleArr.push({
        name: element.st_name,
        value: element.stcd,
      });
    }
  });
  getWaterRegimenData(chartData.weatherTitleArr[0].value);
  chartData.weatherTitleName = chartData.weatherTitleArr[0].name;
  stcd.value = chartData.weatherTitleArr[0].value;
  circulateData();
}
const subBasicStore = basicStore.$subscribe((mutation: any, state: any) => {
  if (Object.keys(state.stDetailInfo).length != 0) {
    processingArrays(state.stDetailInfo);
    subBasicStore();
  }
});
const stcd = ref();
eventBus.on('weatherBus', async (value) => {
  console.log(value);
  stcd.value = value.value;
  await getWaterRegimenData(value.value);
  chartData.weatherTitleName = value.name;
  charts1.resize();
  charts2.resize();
});

onMounted(async () => {
  if (Object.keys(basicStore.getStDetailInfo).length != 0) {
    processingArrays(basicStore.getStDetailInfo);
  }
  //二位对象拍平
  // await processingArrays();
  // 获取水情信息
  // await getWaterRegimenData();
});
onBeforeUnmount(() => {
  if (circulateFn) {
    clearInterval(circulateFn);
  }
});
</script>
<style lang="less" scoped>
.main {
  margin-top: 20px;
  box-sizing: border-box;
  padding: 2px;
  border-radius: 0px 30px 0px 30px;
  background-image: linear-gradient(200deg, rgba(40, 165, 255, 0.9) 9%, rgba(100, 255, 255, 0) 34%, rgba(40, 126, 255, 0) 66%, #28a5ff 100%);
}
.main_in {
  width: 100%;
  height: 100%;
  border-radius: 0px 30px 0px 30px;
  background: rgba(6, 37, 70, 0.9);
}
.main-title {
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  padding: 6px 20px;
  color: #dffeff;
  font-size: 16px;
  background: linear-gradient(90deg, rgba(40, 126, 255, 0.16) 0%, rgba(40, 126, 255, 0) 100%);
  margin-left: 8px;
  div {
    span {
      background: linear-gradient(0deg, #fbf70e 0%, #f4af10 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      text-fill-color: transparent;
    }
  }
}
.none-data {
  width: 150px;
  margin: 0 auto;
  padding-top: 50px;
}
</style>
