<template>
  <div class="main">
    <div class="content-box">
      <div>
        <div class="title">预报方案列表</div>
        <div class="content-tree">
          <a-input-search
            v-model:value="searchValue"
            style="margin-bottom: 8px"
            placeholder="支持关键字查询"
          />
          <a-tree
            v-if="gData.length"
            :selectedKeys="selectedKeysTree"
            :expandedKeys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :tree-data="gData"
            :defaultExpandAll="true"
            :replace-fields="{
              children: 'children',
              title: 'title',
              key: 'keyid',
            }"
            @expand="onExpand"
            @select="treeSelect"
          >
            <template #title="{ title }">
              <span v-if="title.indexOf(searchValue) > -1">
                {{ title.substr(0, title.indexOf(searchValue)) }}
                <span style="color: #f50">{{ searchValue }}</span>
                {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
              </span>
              <span v-else>{{ title }}</span>
            </template>
          </a-tree>
        </div>
      </div>
      <div id="regular"></div>
    </div>
    <Loading :loading="compState.loading" :absolute="compState.absolute" :tip="compState.tip" />
  </div>
</template>
<script lang="ts" setup>
import { createVNode, defineComponent, ref, watch, onMounted, reactive } from 'vue';
import { getSimulateTree,getAutoShow } from '/@/api/swHome/index';
import { message, Modal } from 'ant-design-vue';
import moment from 'moment';
import { Loading } from '/@/components/Loading';
import * as echarts from 'echarts';
import { ImpExcel, ExcelData, jsonToSheetXlsx } from '/@/components/Excel';
let dataCenter = reactive({
  test1: 1,
  test2: '',
  activeBox: 2,
  honghaoList: [],
  disabled: false,
  keyid: null,
  showRainModal: false,
  showRainModal2: false,
  threshold: [],
  rainData: {
    dataSource: [],
    columns: [],
  },
  listData: {
    rainData: [],
    intermediateData: [],
    rainData: [],
    paramData: [],
  },
  resultList: [],
  ranges: { Today: [moment(), moment()], 'This Month': [moment(), moment().endOf('month')] },
  chartsData: {},
});
const genData = ref([]);
const dataList = [];
const generateList = (data) => {
  console.log(data);
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const key = node.title;
    dataList.push({
      key,
      title: key,
    });
    expandedKeys.value.push(node.keyid)
    if (node.children) {
      generateList(node.children);
    }
  }
};

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    console.log(node);
    if (node.children) {
      if (node.children.some((item) => item.title === key)) {
        parentKey = node.keyid;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
const compState = reactive({
  absolute: false,
  loading: false,
  tip: '加载中...',
});
const expandedKeys = ref([]);
const searchValue = ref('');
const autoExpandParent = ref(true);
const gData = ref(genData);
function setActive(e) {
  dataCenter.activeBox = e;
}
const onExpand = (keys) => {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
};
watch(searchValue, (value) => {
  const expanded = dataList
    .map((item) => {
      if (item.title.indexOf(value) > -1) {
        return getParentKey(item.key, gData.value);
      }
      return null;
    })
    .filter((item, i, self) => item && self.indexOf(item) === i);
  console.log(expanded);
  expandedKeys.value = expanded;
  searchValue.value = value;
  autoExpandParent.value = true;
});

let selectedKeysTree = ref([])
const getSimulateTreeData = () => {
  getSimulateTree().then((res) => {
    genData.value = res.data[0].children;
    gData.value = res.data[0].children;
    generateList(res.data[0].children);
    if(gData.value.length>0 && gData.value[0].children.length>0 && gData.value[0].children[0].children.length>0){
      let eData = {
        node:{
          dataRef:gData.value[0].children[0].children[0]
        }
      }
      selectedKeysTree.value = [gData.value[0].children[0].children[0].keyid]
      treeSelect('',eData)
    }
  });
};
function treeSelect(selectedKeys,e){
  selectedKeysTree.value = [e.node.dataRef.keyid]
  dataCenter.keyid = e.node.dataRef.keyid;
  getAutoShow({scheme_id:dataCenter.keyid}).then(res => {
    dataCenter.chartsData = res.data
    setCharts();
  })
}
let chart = null;
function setCharts() {
  chart = echarts.init(document.getElementById('regular'));
  let option = {
    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 (item, item1) {
            console.log(item1)
            let name = `定时模拟-雨洪对照表.xlsx`;
            let header = {
              'time': '时间',
              'rain': '面均雨量（mm）',
              'q_real': '实测流量（m³/s）',
              'q_forecast': '预测流量（m³/s）',
              'rls_optimaze': '实时校正（mm）',
              'q_calibration': '在线校正/s）',
              'q_smooth': '光滑流量（m³/s）'
            };
            let data = []
            console.log()
            dataCenter.chartsData.t.forEach((item, index) => {
              let obj = {
                time: item,
                'rain': dataCenter.chartsData['rain'][index],
                'q_real': dataCenter.chartsData['q_real'][index],
                'q_forecast': dataCenter.chartsData['q_forecast'][index],
                'rls_optimaze': dataCenter.chartsData['rls_optimaze'][index],
                'q_calibration': dataCenter.chartsData['q_calibration'][index],
                'q_smooth': dataCenter.chartsData['q_smooth'][index],
              }
              data.push(obj)
            });
            jsonToSheetXlsx({
              data,
              header: header,
              filename: name,
            });
          },
        },
        // magicType: { show: true, type: ['line', 'bar'] },
        // restore: { show: true },
        saveAsImage: {
          show: true,
          iconStyle: {
            borderColor: '#2D74E7',
          },
        },
      },
    },
    title: {
      text: '雨洪对照图',
      left: '1%',
      top: '1%',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: false
      },
      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;
      },
    },
    axisPointer: {
      link: [
        {
          xAxisIndex: 'all'
        }
      ]
    },
    legend: {
      data: ['实测流量', '预测流量', '实时校正', '在线校正', '光滑流量', '面均雨量'],
      selected:{'实测流量':true,'预测流量':true,'实时校正':false,'在线校正':false,'光滑流量':false,'面均雨量':false},
      top: '10px',
      textStyle: {
        fontSize: 12, //字体大小
        color: '#333333', //字体颜色
      },
    },
    xAxis: [
      {
        show: false,
        data: dataCenter.chartsData.t.map(function (str) {
          return str.replace(' ', '\n');
        }),
        axisTick:{
          alignWithLabel:true
        },
        axisLabel: {
          show: true,
          textStyle: {
            color: '#333333',
          },
          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;
          },
        },
      },
      {
        data: dataCenter.chartsData.t.map(function (str) {
          return str.replace(' ', '\n');
        }),
        axisTick:{
          alignWithLabel:true
        },
        gridIndex: 1,
        axisLabel: {
          show: true,
          textStyle: {
            color: '#333333',
          },
          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;
          },
        },
      },
    ],
    dataZoom: [
      {
        show: true,
        // realtime: true,

        realtime: true,
        start: 65,
        end: 100,
        xAxisIndex: [0, 1]
      },
      {
        show: false,
        start: 70,
        end: 100,
        type: 'inside',
        xAxisIndex: [0, 1]
      }
    ],
    yAxis: [
      {
        position: 'right',
        name: '降雨\n(mm)',
        nameLocation: 'center',
        nameGap: 40,
        nameRotate: 0,
        axisLabel: {
          textStyle: {
            color: '#333333',
          },
          formatter: function (value) {
            return value + '';
          },
        },
        nameTextStyle: {
          color: '#333',
          fontSize: 12,
          textAlign: 'center',
          padding: [0, 0, 0, 0], //距离坐标位置的距离
        },
        splitLine: {
          lineStyle: {
            type: 'dashed', //虚线
            color: '#484849',
          },
        },
        inverse: true,
        scale: true,
      },
      {
        // position: 'right',
        name: '流量  \n(m³/s)',
        gridIndex: 1,
        nameLocation: 'center',
        nameGap: 40,
        nameRotate: 0,
        axisLabel: {
          textStyle: {
            color: '#333333',
          },
          formatter: function (value) {
            return value + '';
          },
        },
        nameTextStyle: {
          color: '#333',
          fontSize: 12,
          textAlign: 'center',
          padding: [0, 0, 0, 0], //距离坐标位置的距离
        },
        splitLine: {
          lineStyle: {
            type: 'dashed', //虚线
            color: '#484849',
          },
        },
        scale: true,
      },
    ],
    grid: [
      {
        bottom: '70%',
        left: '100',
        right: '100',
      },
      {
        top: '30%',
        left: '100',
        right: '100',
        bottom: '100',
      },
    ],
    series: [
      {
        name: '面均雨量',
        data: dataCenter.chartsData.rain,
        type: 'bar',
        barWidth: 5, // 设置每个柱子的宽度为40
        showSymbol: false,
        lineStyle: {
          width: 1,
        },
        itemStyle: {
          color: '#00CB98',
        },
        emphasis: {
          focus: 'series',
        },
      },
      {
        name: '实测流量',
        smooth: true,
        type: 'line',
        showSymbol: false,
        data: dataCenter.chartsData.q_real,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '预测流量',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_forecast,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '实时校正',
        smooth: true,
        type: 'line',
        showSymbol: false,
        data: dataCenter.chartsData.rls_optimaze,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '在线校正',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_calibration,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
      {
        name: '光滑流量',
        type: 'line',
        showSymbol: false,
        smooth: true,
        data: dataCenter.chartsData.q_smooth,
        xAxisIndex: 1,
        yAxisIndex: 1,
      },
    ],
  };
  option && chart.setOption(option);
}
onMounted(() => {
  getSimulateTreeData();
  
});
</script>
<style scoped lang="less">
.main {
  height: 100%;
}
.content-box {
  display: flex;
  padding: 10px;
  height: 100%;
  background-color: #fff;
  & > div:nth-child(1) {
    width: 200px;
    height: 100%;
    overflow: hidden;
    .title {
      background-color: #f8f8f8;
      line-height: 45px;
      text-align: center;
      font-weight: 500;
    }
    .content-tree {
      margin-top: 10px;
      height: calc(100vh - 155px);
      background-color: #f8f8f8;
      overflow: auto;
    }
  }
  & > div:nth-child(2) {
    flex: 1;
    margin-left: 10px;
  }
}
#regular {
  height: 100%;
}
</style>

<style lang="less">
#regular table {
  cellspacing: 0;
  *border-collapse: collapse;
  /* IE7 and lower */
  border-spacing: 0;
  width: 100%;
  // position: relative;
  padding-top: 40px;
}

#regular thead {
  position: absolute;
  left: 0px;
  top: 44px;
  width: 100%;
}

#regular .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;
}

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

}

#regular .bordered th:nth-child(1) {
  width: 40%;
}

#regular .bordered th:nth-child(2) {
  width: 10%;
}

#regular .bordered th:nth-child(3) {
  width: 10%;
}

#regular .bordered th:nth-child(4) {
  width: 10%;
}
#regular .bordered th:nth-child(5) {
  width: 10%;
}

#regular .bordered th:nth-child(6) {
  width: 10%;
}

#regular .bordered th:nth-child(7) {
  width: 10%;
}

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

#regular .bordered td:nth-child(1) {
  width: 40%;
}

#regular .bordered td:nth-child(2) {
  width: 10%;
}

#regular .bordered td:nth-child(3) {
  width: 10%;
}

#regular .bordered td:nth-child(4) {
  width: 10%;
}

#regular .bordered td:nth-child(5) {
  width: 10%;
}


#regular .bordered td:nth-child(6) {
  width: 10%;
}


#regular .bordered td:nth-child(7) {
  width: 10%;
}

#regular .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);
}

#regular .bordered td:first-child,
#regular .bordered th:first-child {
  border-left: none;
}

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

#regular .bordered tr {
  width: 100%;
  display: flex;
}

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

#regular .bordered tbody {
  padding-top: 36px;
}

#regular .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;
}

#regular .bordered {
  margin-top: 36px;
}
</style>

