<template>
  <div class="main">
    <div class="main_in" @mouseleave="boxMouseleave" @mouseenter="boxMouseenter">
      <weatherTitle :title="'水情监控'" refreshName="regimenRefreshName" />
      <div class="total222">
        <a-tabs @change="tablsOnChange" v-model:activeKey="activeKey">
          <a-tab-pane key="1">
            <template #tab>
              <span> 水文站 </span>
            </template>
            <div class="re-ul">
              <vue3-seamless-scroll :list="regimenData.regimen.st_hydro" class="scroll" :step="0.2" :hover="true" :wheel="true">
                <div
                  @click="
                    () => {
                      openModal(item.stcd), setActiveFn(item);
                    }
                  "
                  class="re-list"
                  v-for="(item, index) in regimenData.regimen.st_hydro"
                >
                  <div>
                    <div>{{ item.st_name }}</div>
                    <div>{{ item.time }}</div>
                  </div>
                  <div>
                    <div>
                      <span>水位 {{ item.z.v }}m</span>
                      <!-- <span>{{ item.up_down }}</span> -->
                      <span v-if="item.up_down == '涨'" class="re-rise">涨<ArrowUpOutlined /></span>
                      <span v-else-if="item.up_down == '落'" class="re-fall">落<ArrowDownOutlined /></span>
                      <span v-else-if="item.up_down == '平'" class="re-flat">平—</span>
                      <span v-else class="re-flat">--</span>
                    </div>
                    <div>流量 {{ item.q.v }}m³/s</div>
                  </div>
                </div>
              </vue3-seamless-scroll>
            </div>
          </a-tab-pane>
          <a-tab-pane key="2">
            <template #tab>
              <span> 水位站 </span>
            </template>
            <div class="re-ul">
              <vue3-seamless-scroll :list="regimenData.regimen.st_hydro" class="scroll" :step="0.2" :hover="true" :wheel="true">
                <div
                  @click="
                    () => {
                      openModal(item.stcd), setActiveFn(item);
                    }
                  "
                  class="re-list"
                  v-for="(item, index) in regimenData.regimen.st_waterz"
                >
                  <div>
                    <div>{{ item.st_name }}</div>
                    <div>{{ item.time }}</div>
                  </div>
                  <div>
                    <div>
                      <span>水位 {{ item.z.v }}m</span>
                      <span v-if="item.up_down == 1" class="re-rise">涨<ArrowUpOutlined /></span>
                      <span v-if="item.up_down == 0" class="re-fall">落<ArrowDownOutlined /></span>
                      <span v-if="item.up_down == 2" class="re-flat">平-</span>
                    </div>
                    <!-- <div>流量 {{ item.q }}m³/s</div> -->
                  </div>
                </div>
              </vue3-seamless-scroll>
            </div>
          </a-tab-pane>
          <template #renderTabBar="{ DefaultTabBar, ...props }">
            <component :is="DefaultTabBar" v-bind="props" :style="{ zIndex: 1, textAlign: 'center' }" />
          </template>
        </a-tabs>
      </div>
      <div class="re-echarts-title" @click="openModal(stcd)">
        <span>{{ regimenData.activeName }}&nbsp;</span>
        {{ regimenTitle }}
      </div>
      <div v-if="activeEcharts == '1' && showCharts" id="re-echarts" style="width: 100; height: 310px"></div>
      <div v-if="activeEcharts != '1' && showCharts" id="re-echarts2" style="width: 100; height: 310px"></div>
      <div v-if="!showCharts" style="width: 100; height: 310px">
        <img class="none-data" src="../../../assets/images/weatheHome/none-data.png" />
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, onMounted, reactive, onBeforeUnmount } from 'vue';
import weatherTitle from '../../../components/Title/weatherTitle.vue';
import { ArrowUpOutlined, ArrowDownOutlined, SwapRightOutlined } from '@ant-design/icons-vue';
import { getHydroMonitoring, getMonitorInfo } from '/@/api/swHome/index';
import { getNowTime } from '/@/utils/fnUtils.ts';
import { useMapStore } from '/@/store/modules/map';
// 滚动插件
import { Vue3SeamlessScroll } from 'vue3-seamless-scroll';

const mapStore2 = useMapStore();
const openModal = (item) => {
  mapStore2.setstInfo({ stcd: item });
};
const stcd = ref();
import eventBus from '/@/utils/eventBus';
let activeKey = ref('1');
let showCharts = ref(true);
eventBus.on('regimenRefreshName', () => {
  showCharts.value = true;
  activeKey.value = '1';
  activeEcharts.value = 1;
  setTimeout(() => {
    getHydroMonitoringData();
  }, 0);
});
// 计算最大值
function getmaxValue2(arr) {
  const max = Math.max(...arr);
  // 这样处理是为了不让最大值刚好到坐标轴最顶部
  return Math.ceil(max / 9.5) * 10;
}
// 计算最小值
function getminValue2(arr) {
  const min = Math.min(...arr);
  // 这样处理是为了不让最大值刚好到坐标轴最底部
  return Math.floor(min / 12) * 10;
}
// 默认选中第一个
function tablsOnChange(e) {
  tablsOnChangeNum = e;
  circulateNum = 1;
  boxMouseenter();
  if (e == 1) {
    setActiveFn(regimenData.regimen.st_hydro[0]);
  }
  if (e == 2) {
    setActiveFn(regimenData.regimen.st_waterz[0]);
  }
}
let activeEcharts = ref('1');
let regimenTitle = ref('水位流量过程线');
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 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,
  };
}
function echarts1() {
  regimenTitle.value = '水位流量过程线';
  const chart = echarts.init(document.getElementById('re-echarts'));
  let data1 = regimenData.chartsWater;
  let data2 = regimenData.chartsFlow;
  let max1 = Math.max(...data1);
  let min1 = Math.min(...data1);
  let max2 = Math.max(...data2);
  let min2 = Math.min(...data2);
  let liuliang2 = flowFn(max1, min1);
  let shuiwei = waterLevel(max2, min2);
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter(params) {
        var relVal = params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
          console.log('tooltip数据值', params[i].value);
          //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
          relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Number(params[i].value);
        }
        return relVal;
      },
    },
    dataZoom: [
      {
        // 这个dataZoom组件，默认控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
      },
      {
        // 这个dataZoom组件，也控制x轴。
        type: 'inside', // 这个 dataZoom 组件是 inside 型 dataZoom 组件
      },
    ],
    grid: {
      left: '6%', //默认10%
      right: '4%', //默认10%
      bottom: '4%', //默认60
      containLabel: true,
      //grid区域是否包含坐标轴的刻度标签
    },
    legend: {
      data: ['流量', '水位'],
      textStyle: {
        fontSize: 14, //字体大小
        color: '#ffffff', //字体颜色
      },
      // itemStyle: {
      //   color: '#fff',
      // },
    },
    xAxis: {
      type: 'category',
      data: regimenData.chartsFlowName,
      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: [
      {
        name: data1.length > 0 ? '流量：m³/s' : '',
        type: 'value',
        splitNumber: 5,
        axisLabel: {
          //y轴文字的配置
          textStyle: {
            color: '#fff',
            margin: 15,
          },
          formatter: function (value) {
            return value + '';
          },
          // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
        },
        splitLine: {
          //网格线
          lineStyle: {
            type: 'dashed', //设置网格线类型 dotted：虚线 solid:实线
            width: 1, //y轴线的宽度
            color: '#484849',
          },
          show: true, //隐藏或显示
        },
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.8)', //颜色
        },
        scale: true,
        interval: liuliang2.interval, // 步长
        min: liuliang2.minValue,
        max: liuliang2.maxValue,
      },
      {
        type: 'value',
        name: '水位：m',
        splitNumber: 5,
        axisLabel: {
          //y轴文字的配置
          textStyle: {
            color: '#fff',
            margin: 15,
          },
          formatter: function (value) {
            return value.toFixed(2) + '';
          },
          // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
        },
        splitLine: {
          //网格线
          lineStyle: {
            type: 'dotted', //设置网格线类型 dotted：虚线 solid:实线
            width: 1, //y轴线的宽度
            color: '#484849',
          },
          show: true, //隐藏或显示
        },
        nameTextStyle: {
          color: 'rgba(255, 255, 255, 0.8)', //颜色
          padding: [0, 0, 0, 30],
        },
        scale: true,
        interval: shuiwei.interval, // 步长
        min: shuiwei.minValue,
        max: shuiwei.maxValue,
      },
    ],
    series: [
      {
        name: '流量',
        // data: [820, 932, 901, 934, 1290, 1330, 1320],
        data: data1,
        type: 'line',
        smooth: true,
      },
      {
        name: '水位',
        yAxisIndex: 1,
        // data: [82, 92, 901, 934, 1290, 130, 11320],
        data: data2,
        type: 'line',
        smooth: true,
      },
    ],
  };
  option && chart.setOption(option);
}
function echarts2() {
  regimenTitle.value = '水位过程线';
  const chart = echarts.init(document.getElementById('re-echarts2'));
  let data2 = regimenData.chartsFlow;
  let max1 = Math.max(...data2);
  let min1 = Math.min(...data2);
  let liuliang2 = waterLevel(max1, min1);
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter(params) {
        var relVal = params[0].name;
        for (var i = 0, l = params.length; i < l; i++) {
          console.log('tooltip数据值', params[i].value);
          //遍历出来的值一般是字符串，需要转换成数字，再进项tiFixed四舍五入
          relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + Number(params[i].value);
        }
        return relVal;
      },
    },
    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区域是否包含坐标轴的刻度标签
    },
    legend: {
      data: ['水位'],
      textStyle: {
        fontSize: 14, //字体大小
        color: '#ffffff', //字体颜色
      },
    },
    xAxis: {
      type: 'category',
      data: regimenData.chartsFlowName,
      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',
      // max: max2 * 1.2,
      axisLabel: {
        //y轴文字的配置
        textStyle: {
          color: '#fff',
          margin: 15,
        },
        formatter: function (value) {
          return value + '';
        },
        // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
      },
      splitLine: {
        //网格线
        lineStyle: {
          type: 'dotted', //设置网格线类型 dotted：虚线 solid:实线
          width: 1, //y轴线的宽度
          color: '#484849',
        },
        show: true, //隐藏或显示
      },
      nameTextStyle: {
        color: 'rgba(255, 255, 255, 0.8)', //颜色
        padding: [0, 0, 0, 30],
      },
      scale: true,
      interval: liuliang2.interval, // 步长
      min: liuliang2.minValue,
      max: liuliang2.maxValue,
    },

    series: [
      {
        name: '水位',
        // data: [82, 92, 901, 934, 1290, 130, 11320],
        data: data2,
        type: 'line',
      },
    ],
  };
  option && chart.setOption(option);
}
// 鼠标移出
function boxMouseleave() {
  // console.log('鼠标移出');
  circulateData();
}
// 鼠标移入
function boxMouseenter() {
  console.log('鼠标移入');
  if (circulateFn) {
    clearInterval(circulateFn);
  }
}
// 循环轮播数据
let circulateNum = 1;
let circulateFn = null;
let tablsOnChangeNum = 1;
function circulateData() {
  let circulateArr = [];
  // 1是水文站，2是水位站
  if (tablsOnChangeNum == 1) {
    circulateArr = regimenData.regimen.st_hydro;
  } else {
    circulateArr = regimenData.regimen.st_waterz;
  }
  // 判断类型
  circulateFn = setInterval(async () => {
    setActiveFn(circulateArr[circulateNum]);
    if (circulateNum == circulateArr.length - 1) {
      circulateNum = 0;
    } else {
      circulateNum += 1;
    }
  }, 5000);
}
// 这里是获取数据
async function setActiveEcharts(item) {
  // 获取当前时间24小时
  let formData = {
    start_time: getNowTime(2),
    senid: item.senid,
    end_time: getNowTime(1),
  };
  let data = await getMonitorInfo(formData).then((res) => {
    return res.data;
  });
  let obj = {
    name: [],
    data: [],
  };
  data.forEach((element) => {
    obj.name.push(element.time);
    obj.data.push(element.factv);
  });
  return obj;
}
// 点击面板事件
async function setActiveFn(item) {
  stcd.value = item.stcd;
  showCharts.value = true;
  regimenData.activeName = item.st_name;
  // 判断有没有流量参数
  if (item.q) {
    //q流量，z水位
    let obj = await setActiveEcharts(item.q);
    regimenData.chartsWater = obj.data;
    regimenData.chartsWaterName = obj.name;
    let obj1 = await setActiveEcharts(item.z);
    regimenData.chartsFlow = obj1.data;
    regimenData.chartsFlowName = obj1.name;
    activeEcharts.value = '1';

    if (obj.data.length == 0 && obj1.data.length == 0) {
      showCharts.value = false;
      return;
    }
    setTimeout(() => {
      echarts1();
    }, 0);
  } else {
    //q流量，z水位
    regimenData.chartsWater = [];
    let obj1 = await setActiveEcharts(item.z);
    regimenData.chartsFlow = obj1.data;
    regimenData.chartsFlowName = obj1.name;
    activeEcharts.value = '2';
    if (obj1.data.length == 0) {
      showCharts.value = false;
      return;
    }
    setTimeout(() => {
      echarts2();
    }, 0);
  }
}
let regimenData = reactive({
  regimen: {
    st_hydro: [], //#水文站
    st_waterz: [], //#水位站
  },
  chartsWater: [],
  chartsWaterName: [],
  chartsFlow: [],
  chartsFlowName: [],
  activeName: '',
  stcd: null,
});
async function getHydroMonitoringData() {
  await getHydroMonitoring().then(async (res) => {
    regimenData.activeName = res.data.st_hydro[0].st_name;
    regimenData.regimen = res.data;
    //q流量，z水位
    let obj = await setActiveEcharts(res.data.st_hydro[0].q);
    regimenData.chartsWater = obj.data;
    regimenData.chartsWaterName = obj.name;
    let obj1 = await setActiveEcharts(res.data.st_hydro[0].z);
    regimenData.chartsFlow = obj1.data;
    regimenData.chartsFlowName = obj1.name;
    echarts1();
    circulateData();
  });
}
onMounted(async () => {
  await getHydroMonitoringData();
});
onBeforeUnmount(() => {
  if (circulateFn) {
    clearInterval(circulateFn);
  }
});
// 引入图表插件
const { proxy } = getCurrentInstance();
const echarts = proxy.$echarts;
</script>

<style lang="less" scoped>
.main {
  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);
}
.re-ul {
  // height: 480px;
  // height: 46vh;
  padding: 20px;
  overflow: auto;
}
.scroll {
  height: 440px;
  overflow: hidden;
}
.re-list {
  cursor: pointer;
  background-color: rgba(0, 139, 246, 0.1);
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
  & > div:nth-child(1) {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    div:nth-child(1) {
      font-size: 14px;
      font-weight: 500;
      color: #fff;
    }
    div:nth-child(2) {
      font-size: 12px;
      color: #4d7dc6;
    }
  }
  & > div:nth-child(2) {
    display: flex;
    justify-content: space-between;
    font-size: 16px;
    div:nth-child(1) {
      & > span:nth-child(1) {
        font-size: 18px;
        background: linear-gradient(0deg, #00f7ff 0%, #007ff6 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        text-fill-color: transparent;
        display: inline-block;
        min-width: 128px;
      }
      & > .re-rise {
        margin-left: 20px;
        color: #f90707;
        font-weight: bold;
      }
      & > .re-fall {
        margin-left: 20px;
        color: #00f793;
        font-weight: bold;
      }
      & > .re-flat {
        margin-left: 20px;
        color: #bababa;
        font-weight: bold;
      }
    }
    div:nth-child(2) {
      font-size: 18px;
      background: linear-gradient(0deg, #00f7ff 0%, #007ff6 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      text-fill-color: transparent;
    }
  }
}
.re-echarts-title {
  cursor: pointer;
  // font-weight: bold;
  color: #dffeff;
  font-size: 18px;
  text-align: center;
  padding: 5px 0;
  background: linear-gradient(to right, rgba(#007ff6, 0.1) 0%, rgba(#007ff6, 0.5) 50%, rgba(#007ff6, 0.1) 100%);
  margin-top: 10px;
  margin-bottom: 10px;
  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;
  }
}
// 修改组件样式

::v-deep(.ant-tabs-nav) {
  background: url('../../../assets/images/weatheHome/bar-bg.png') no-repeat;
  background-size: 100%;
  width: 318px !important;
  height: 48px !important;
  padding-top: 3px;
  margin: 0 auto;
}
::v-deep(.total222 .ant-tabs-nav .ant-tabs-tab-active) {
  // background: url('../../assets/images/sjx1.png') no-repeat 42px 9px;
  background: url('../../../assets/images/weatheHome/active-bar.png') no-repeat;
  // width: 45px;
  background-size: 100%;
  height: 40px;
  width: 169px;
}
::v-deep(.total222 .ant-tabs-nav > div > div:nth-child(2).ant-tabs-tab-active) {
  // background: url('../../assets/images/sjx1.png') no-repeat 42px 9px;
  // background: url('../../../assets/images/tab.png') no-repeat;
  // width: 45px;
  // background-position: 6px 3px;
  background-size: 100% 100%;
  height: 42px;
  // line-height: 42px;
  // margin-left: -6px;
}
// ::v-deep(.total222 .ant-tabs-nav > div > div:nth-child(2).ant-tabs-tab-active span) {
//   position: relative;
//   // top: 10px !important;
// }
::v-deep(.total222 .ant-tabs-nav .ant-tabs-tab) {
  background-size: 100% 100%;
  height: 40px;
  // line-height: 42px;
  padding: 12px 0px 12px 0px;
  margin: 0;
  width: 149px;
}
::v-deep(.total222 .ant-tabs-nav .ant-tabs-tab span) {
  position: relative;
  top: -4px;
  color: #377dff;
}

::v-deep(.total222 .ant-tabs-nav .ant-tabs-tab-active span) {
  color: #c9d1d9 !important;
}
::v-deep(.ant-tabs-top-bar) {
  margin-bottom: 0px !important;
}
::v-deep(.ant-tabs-ink-bar) {
  visibility: hidden;
}

::v-deep(
    .ant-tabs-top > .ant-tabs-nav::before,
    .ant-tabs-bottom > .ant-tabs-nav::before,
    .ant-tabs-top > div > .ant-tabs-nav::before,
    .ant-tabs-bottom > div > .ant-tabs-nav::before
  ) {
  border-bottom: 0px;
}
::v-deep(.ant-tabs) {
  color: #fff;
}
::v-deep(.ant-tabs-tab.ant-tabs-tab-active .ant-tabs-tab-btn) {
  color: #ffe75c;
}
::v-deep(.ant-tabs-tab) {
  // font-size: 18px;
  // font-weight: bold;
  font-size: 16px;
  font-weight: normal !important;
}
::v-deep(.ant-tabs-bar) {
  border-bottom: 0px solid #303030 !important;
}
// 修改组件样式结束
.none-data {
  width: 150px;
  margin: 0 auto;
  padding-top: 50px;
}
</style>
