<template>
  <div class="main">
    <div class="top-form">
      <a-row>
        <a-col class="form-box" :span="5">
          <div> 监测站点： </div>
          <div>
            <a-select
              class="custom-input sitemore"
              placeholder="监测站点"
              :maxTagCount="2"
              :maxTagTextLength="4"
              @change="changeStid"
              v-model:value="dataCenter.formData.stcd"
              :options="dataCenter.st_options"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="5">
          <div> 要素： </div>
          <div>
            <a-select
              class="custom-input sitemore"
              placeholder="要素"
              :maxTagCount="2"
              :maxTagTextLength="4"
              v-model:value="dataCenter.formData.dchar"
              :options="dataCenter.ys_options"
              mode="multiple"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="5">
          <div> 对比年份： </div>
          <div>
            <a-select
              class="custom-input sitemore"
              v-model:value="dataCenter.formData.compare"
              :options="dataCenter.yrarOptions"
              mode="tags"
              :maxTagCount="1"
              placeholder="对比年份"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="9">
          <div> 查询时间： </div>
          <div>
            <!-- 小时查询 -->
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'H'"
              :value="dataCenter.timeData.time"
              :show-time="{ format: 'HH:mm:ss' }"
              format="YYYY-MM-DD HH:mm:ss"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              :allowClear="true"
            />
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'D'"
              :value="dataCenter.timeData.time"
              format="YYYY-MM-DD"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              :allowClear="true"
            />
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'M'"
              :value="dataCenter.timeMonth"
              format="YYYY-MM"
              valueFormat="YYYY-MM"
              :placeholder="['开始时间', '结束时间']"
              @change="onChange"
              :mode="['month', 'month']"
              @panelChange="monthPanelChange"
              :allowClear="true"
            />
            <a-range-picker
              v-if="dataCenter.formData.step_size == 'Y'"
              :value="dataCenter.timeYear"
              format="YYYY"
              valueFormat="YYYY"
              :placeholder="['开始时间', '结束时间']"
              @panelChange="yearPanelChange"
              :mode="['year', 'year']"
              :allowClear="true"
            />
          </div>
        </a-col>
        <a-col class="form-box" :span="5">
          <div> 时段类型： </div>
          <div>
            <a-radio-group @change="changeGroup" v-model:value="dataCenter.formData.step_size">
              <a-radio
                v-for="(item, index) in dataCenter.sd_options"
                :key="index"
                :value="item.value"
                >{{ item.label }}</a-radio
              >
            </a-radio-group>
          </div>
        </a-col>
        <a-col class="form-box" :span="8">
          <div> 统计特征： </div>
          <div>
            <!-- :disabled="dataCenter.attrDisable" -->
            <a-radio-group v-model:value="dataCenter.formData.attr">
              <a-radio
                v-for="(item, index) in dataCenter.tz_options"
                :key="index"
                :value="item.value"
                >{{ item.label }}</a-radio
              >
            </a-radio-group>
          </div>
        </a-col>
        <a-col class="btn-list" :span="8">
          <a-button @click="resetting">重置</a-button>
          <a-button class="cha" type="primary" @click="queryData">查询</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="content-box">
      <div class="sub-title"
        >分析结果
        <img
          v-if="dataCenter.type == 1"
          src="../../../assets/images/sw-home/icon20-active.png"
          alt=""
        />
        <img
          @click="setBoxTable(1)"
          v-if="dataCenter.type != 1"
          src="../../../assets/images/sw-home/icon20.png"
          alt=""
        />
        <img
          v-if="dataCenter.type == 2"
          src="../../../assets/images/sw-home/icon21-active.png"
          alt=""
        />
        <img
          @click="setBoxTable(2)"
          v-if="dataCenter.type != 2"
          src="../../../assets/images/sw-home/icon21.png"
          alt=""
        />
        <img
          v-if="dataCenter.type == 3"
          src="../../../assets/images/sw-home/icon23-active.png"
          alt=""
        />
        <img
          @click="setBoxTable(3)"
          v-if="dataCenter.type != 3"
          src="../../../assets/images/sw-home/icon23.png"
          alt=""
        />
        <img
          v-if="dataCenter.type == 4"
          src="../../../assets/images/sw-home/icon22-active.png"
          alt=""
        />
        <img
          @click="setBoxTable(4)"
          v-if="dataCenter.type != 4"
          src="../../../assets/images/sw-home/icon22.png"
          alt=""
        />
      </div>
    </div>
    <div class="box-content">
      <div
        :class="{
          'one-box': dataCenter.type == 1,
          'two-box': dataCenter.type == 2,
          'therr-box': dataCenter.type == 3,
          'four-box': dataCenter.type == 4,
        }"
        :id="`charts-box-${index}`"
        v-for="(item, index) in dataCenter.chartsData"
        :key="index"
      ></div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { BasicTable, useTable } from '/@/components/Table';
import screenImg from '/@/assets/images/sw-home/all-icon.png';
import * as echarts from 'echarts';
import moment from 'moment';
import {
  getRiverTree,
  getDataAllElements,
  getManyStAnalyze,
  getSingleStAnalyze,
} from '/@/api/swHome/index';
import { getNowTime } from '/@/utils/fnUtils.ts';
let dataCenter = reactive({
  timeYear: [],
  timeMonth: [],
  attrDisable: true,
  type: 2,
  st_options: [],
  ys_options: [],
  yrarOptions: [],
  tableDataModal: {
    table_head: [],
    table_value: [],
  },
  sd_options: [
    // { label: '实时', value: 'R' },
    { label: '小时', value: 'H' },
    { label: '日', value: 'D' },
    { label: '月', value: 'M' },
    { label: '年', value: 'Y' },
  ],
  tz_options: [
    { label: '整点值', value: 'v' },
    { label: '平均值', value: 'avgv' },
    { label: '最大值', value: 'maxv' },
    { label: '最小值', value: 'minv' },
  ],
  yearTime: {
    time: [],
  },
  timeData: {
    time: [getNowTime(2), getNowTime(1)],
  },
  chartsData: {},
  formData: {
    step_size: 'H',
    dchar: [],
    attr: 'v',
    start_time: '',
    end_time: '',
    stcd: '',
    compare: [],
  },
});
function setBoxTable(e) {
  dataCenter.type = e;
  console.log(dataCenter.chartsData);
  dataCenter.chartsData.forEach((element) => {
    setTimeout(() => {
      element.dom.resize();
    }, 300);
  });
}
function onChange(value, dateString) {
  console.log(dateString);
  dataCenter.timeData.time = dateString;
}
function changeGroup() {
  dataCenter.timeData.time = [];
}
// 年份选择
function yearPanelChange(value) {
  dataCenter.timeData.time = [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')];
  dataCenter.timeYear = [moment(value[0]).format('YYYY'), moment(value[1]).format('YYYY')];
}
// 月份选择
function monthPanelChange(value) {
  dataCenter.timeData.time = [
    moment(value[0]).format('YYYY-MM'),
    moment(value[1]).format('YYYY-MM'),
  ];
  dataCenter.timeMonth = [moment(value[0]).format('YYYY-MM'), moment(value[1]).format('YYYY-MM')];
}
function queryData() {
  getHistoryWaterData();
}
// function changeDchar({ target }) {
// if (target.value == 'R') {
//   dataCenter.attrDisable = true;
//   dataCenter.formData.attr = '';
// } else {
//   dataCenter.attrDisable = false;
//   dataCenter.formData.attr = 'avgv';
// }
// }
// 查询展示数据
function getHistoryWaterData() {
  dataCenter.chartsData = []
  dataCenter.formData.start_time = dataCenter.timeData.time[0];
  dataCenter.formData.end_time = dataCenter.timeData.time[1];
  getSingleStAnalyze(dataCenter.formData).then((res) => {
    // processingData(data);
    let data = JSON.parse(JSON.stringify(res.data));
    let dchar_type = [];
    if (res.data.hasOwnProperty('dchar_type')) {
      dchar_type = res.data.dchar_type;
      delete data.dchar_type;
    }
    processingData(data, dchar_type);
  });
}
function processingData(data, dchar_type) {
  // 处理表格数据
  let arr = [];
  for (const key in data) {
    let dataArr = {};
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      const element = data[key];
      dataArr.name = key;
      dataArr.nameList = [];
      dataArr.value = [];
      for (const key1 in element) {
        if (Object.prototype.hasOwnProperty.call(element, key1)) {
          const element1 = element[key1];
          // console.log(element1);
          dataArr.nameList.push(key1);
          let elementObj = {
            name: key1,
            time: [],
            value: [],
          };
          element1.forEach((element2) => {
            elementObj.time.push(element2.time);
            elementObj.value.push(element2.value);
          });
          dataArr.value.push(elementObj);
        }
      }
    }
    arr.push(dataArr);
  }
  // console.log(arr);
  dataCenter.chartsData = arr;
  setTimeout(() => {
    chartsArrBox(dataCenter.chartsData, dchar_type);
  }, 300);
}
function setunit(name) {
  // 电压:V,  雨量:mm,  水位:m,  温度:℃,  风向:°,  风速:m/s,
  // 流量:m³/s,  气象气压:hPa,  湿度:%,  土壤热通量:Qs,辐射:Ci,
  // 二氧化碳浓度:ppm,  水汽浓度:kg/h
  let arr = [
    { name: '电压', nuit: 'V' },
    { name: '雨量', nuit: 'mm' },
    { name: '水位', nuit: 'm' },
    { name: '温度', nuit: '℃' },
    { name: '风向', nuit: '°' },
    { name: '风速', nuit: 'm/s' },
    { name: '流量', nuit: 'm³/s' },
    { name: '气象气压', nuit: 'hPa' },
    { name: '湿度', nuit: '%' },
    { name: '土壤热通量', nuit: 'Qs' },
    { name: '辐射', nuit: 'Ci' },
    { name: '二氧化碳浓度', nuit: 'ppm' },
    { name: '水汽浓度', nuit: 'kg/h' },
  ];
  let text = '';
  arr.forEach((element) => {
    if (name.indexOf(element.name) != -1) {
      text = element.nuit;
    }
  });
  return text;
}
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 chartsArrBox(arr, dchar_type) {
  arr.forEach((element, index) => {
    let chart = echarts.init(document.getElementById(`charts-box-${index}`));
    let fullFlag;
    let option = {
      title: {
        text: `${element.name}(${setunit(element.name)})`,
        textStyle: {
          fontSize: 14,
          color: '#2D74E7',
        },
      },
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: element.nameList,
      },
      grid: {
        left: '6%',
        right: '6%',
        bottom: '6%',
        containLabel: true,
      },
      toolbox: {
        right: 26,
        feature: {
          dataView: {
            show: true,
            readOnly: true,
            iconStyle: {
              borderColor: '#2D74E7',
            },
            // lang: [' ', '关闭', '导出Excel'],
            optionToContent: function (opt) {
              let axisData = opt.xAxis[0].data; //坐标数据
              let series = opt.series; //折线图数据
              let tdHeads = '<th>时间</th>'; //表头
              let tdBodys = ''; //数据
              series.forEach(function (item) {
                //组装表头
                tdHeads += `<th>${item.name}</th>`;
              });
              let table = `<table  id="tableExcel" class="bordered"><thead><tr>${tdHeads} </tr></thead><tbody>`;
              for (let i = 0, l = axisData.length; i < l; i++) {
                for (let j = 0; j < series.length; j++) {
                  //组装表数据
                  tdBodys += `<td>${series[j].data[i]}</td>`;
                }
                table += `<tr><td>${axisData[i]}</td>${tdBodys}</tr>`;
                tdBodys = '';
              }
              table += '</tbody></table>';
              return table;
            },
            // contentToOption: function (opts) {
            //   document.getElementById(`charts-box-${index}`).table2excel({
            //     exclude: '.noExl', //过滤位置的 css 类名
            //     filename: '导出文件名称', //文件名称
            //     name: '导出文件名称',
            //     exclude_img: true,
            //     exclude_links: true,
            //     exclude_inputs: true,
            //   });
            // },
          },
          // magicType: { show: true, type: ['line', 'bar'] },
          // restore: { show: true },
          saveAsImage: {
            show: true,
            iconStyle: {
              borderColor: '#2D74E7',
            },
          },
          myFull: {
            show: true,
            title: '全屏查看',
            icon: 'image://' + screenImg,
            iconStyle: {
              color: '#2D74E7',
            },
            onclick: () => {
              fullFlag = true;
              let elements = document.getElementById(`charts-box-${index}`);

              // 一些浏览器的兼容性
              if (elements.requestFullScreen) {
                // HTML W3C 提议
                elements.requestFullScreen();
              } else if (elements.msRequestFullscreen) {
                // IE11
                elements.msRequestFullScreen();
              } else if (elements.webkitRequestFullScreen) {
                // Webkit (works in Safari5.1 and Chrome 15)
                elements.webkitRequestFullScreen();
              } else if (elements.mozRequestFullScreen) {
                // Firefox (works in nightly)
                elements.mozRequestFullScreen();
              }

              // 退出全屏
              if (elements.requestFullScreen) {
                document.exitFullscreen();
              } else if (elements.msRequestFullScreen) {
                document.msExitFullscreen();
              } else if (elements.webkitRequestFullScreen) {
                document.webkitCancelFullScreen();
              } else if (elements.mozRequestFullScreen) {
                document.mozCancelFullScreen();
              }
              setTimeout(() => {
                element.dom.resize();
              }, 100);
            },
          },
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: element.value[0].time,
      },
      yAxis: {
        type: 'value',
        scale:true,
      },
      series: [
        // {
        //   name: 'Email',
        //   type: 'line',
        //   stack: 'Total',
        //   data: [120, 132, 101, 134, 90, 230, 210],
        // },
      ],
    };
    element.dom = chart;
    element.value.forEach((item, indexs) => {
      option.series.push({
        name: item.name,
        type: dchar_type[index],
        data: item.value,
      });
    });
    option && chart.setOption(option);
  });
}
// 查询所有站点
async function getDataData() {
  await getRiverTree().then((res) => {
    let arr = [];
    console.log(res.data.data_value.station);
    for (const key in res.data.data_value.station) {
      if (Object.prototype.hasOwnProperty.call(res.data.data_value.station, key)) {
        const element = res.data.data_value.station[key];
        element.forEach((element) => {
          arr.push({
            label: element.st_name,
            value: element.stcd,
          });
        });
      }
    }
    dataCenter.st_options = arr;
    dataCenter.formData.stcd = dataCenter.st_options[0].value;
    getDataAllElementsFn([dataCenter.st_options[0].value])
  });
  
}
const changeStid = (e) => {
    getDataAllElementsFn([e])
  }
async function getDataAllElementsFn(ids) {
  await getDataAllElements({station:ids}).then((res) => {
    res.data.forEach((element) => {
      element.label = element.dchar_name;
      element.value = element.dchar;
    });
    dataCenter.ys_options = res.data;

    dataCenter.formData.dchar = [
      dataCenter.ys_options[0].value,
      dataCenter.ys_options[1].value,
      dataCenter.ys_options[2].value,
      dataCenter.ys_options[3].value
    ];
  });
  getHistoryWaterData();
}
function resetting() {
  getDataData();
}
function checkFull() {
  //判断浏览器是否处于全屏状态 （需要考虑兼容问题）
  //火狐浏览器
  let isFull =
    document.mozFullScreen ||
    document.fullScreen ||
    //谷歌浏览器及Webkit内核浏览器
    document.webkitIsFullScreen ||
    document.webkitRequestFullScreen ||
    document.mozRequestFullScreen ||
    document.msFullscreenEnabled;
  if (isFull === undefined) {
    isFull = false;
  }
  return isFull;
}
function fnResize() {
  setTimeout(() => {
    dataCenter.chartsData.forEach((element) => {
      element.dom.resize();
    });
  }, 100);
}
onMounted(async () => {
  let arrdaya = [];
  // 获取当前年份
  let date = new Date();
  let year = date.getFullYear();
  for (let index = year; index >= 2000; index--) {
    arrdaya.push({
      label: index,
      value: index,
    });
  }
  dataCenter.yrarOptions = arrdaya;
  dataCenter.formData.compare = [year,year-1];
  getDataData();
  window.onresize = function () {
    if (!checkFull()) {
      // 退出全屏后要执行的动作
      fnResize();
    }
  };
});
</script>
<style scoped lang="less">
.main {
  margin: 10px;
  height: calc(100% - 20px);
  background-color: #fff;
}
.top-form {
  background-color: #fff;
  padding: 12px 10px 12px 10px;
}
.btn-list {
  text-align: right;
}
.cha {
  margin-left: 10px;
}
.form-box {
  display: flex;
  & > div:nth-child(1) {
    width: 90px;
    text-align: right;
    line-height: 32px;
  }
  & > div:nth-child(2) {
    flex: 1;
  }
}
::v-deep .top-form .ant-select {
  width: 100%;
}
::v-deep .top-form .ant-radio-group {
  line-height: 32px;
}
.title-name {
  text-align: center;
  font-size: 18px;
  line-height: 40px;
}
.box-content {
  display: flex;
  height: calc(100vh - 248px);
  overflow: auto;
  width: 100%;
  flex-wrap: wrap;
  & > div {
    width: 49.9%;
    // height: 50%;
  }
  & > .one-box {
    width: 99.9%;
    // height: 100%;
    height: 100%;
  }
  & > .two-box {
    width: 49.9%;
    height: 50%;
  }
  & > .therr-box {
    width: 33.33333%;
    height: 50%;
  }
  & > .four-box {
    width: 33.33333%;
    height: 33.333333%;
  }
}
.right-box {
  width: 400px;
  height: 100%;
  overflow: auto;
  margin-left: 20px;
  position: relative;
  ul {
    // position: relative;
    li {
      display: flex;
      line-height: 45px;
      & > div {
        // flex: 1;
        text-align: center;
      }
      & > div:nth-child(1) {
        min-width: 180px;
      }
      & > div:nth-child(2) {
        flex: 1;
      }
      & > div:nth-child(3) {
        flex: 1;
      }
    }
    li:nth-child(1) {
      position: absolute;
      width: 100%;
    }
    li:nth-child(2) {
      padding-top: 45px;
    }
  }
}
.form-box {
  margin-bottom: 10px;
}
.content-box {
  text-align: center;
  font-size: 18px;
  border-top: 1px solid #dedede;
  position: relative;
  padding-top: 10px;
  height: 40px;
  .sub-title {
    padding-left: 10px;
    border-left: 4px solid #2d74e7;
    text-align: left;
    font-size: 10px;
    position: absolute;
    left: 0px;
    top: 15px;
    img {
      margin-left: 10px;
      font-size: 18px;
      position: relative;
      // top: -2px;
      cursor: pointer;
      display: inline-block;
    }
    .active-icon {
      color: #377dff !important;
    }
  }
}
</style>
<style lang="less">
table {
  cellspacing: 0;
  *border-collapse: collapse; /* IE7 and lower */
  border-spacing: 0;
  width: 100%;
}
.bordered tr:hover {
  background: #fbf8e9;
  -o-transition: all 0.1s ease-in-out;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}

.bordered th {
  padding: 7px;
  text-align: center;
  cellspacing: 0;
}

.bordered td {
  padding: 7px;
  text-align: center;
  cellspacing: 0;
}

.bordered th {
  background-image: -webkit-gradient(linear, left top, left bottom, from(#ebf3fc), to(#dce9f9));
  background-image: -webkit-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: -moz-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: -ms-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: -o-linear-gradient(top, #ebf3fc, #dce9f9);
  background-image: linear-gradient(top, #ebf3fc, #dce9f9);
}
.bordered td:first-child,
.bordered th:first-child {
  border-left: none;
}

.bordered tr:nth-of-type(2n) {
  background: #ffffff;
  cursor: pointer;
}
.bordered tr:nth-of-type(2n + 1) {
  background: #f7fafc;
  cursor: pointer;
}

.bordered tbody tr:hover {
  background: #fbf8e9;
  -o-transition: all 0.1s ease-in-out;
  -webkit-transition: all 0.1s ease-in-out;
  -moz-transition: all 0.1s ease-in-out;
  -ms-transition: all 0.1s ease-in-out;
  transition: all 0.1s ease-in-out;
}
</style>
