<template>
  <div class="box-main">
    <div class="left-box">
      <div class="left-title"> 测站列表 </div>
      <div class="left-tree">
        <a-tree @check="checkTree" checkable :tree-data="dataCenter.treeData" v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys" v-model:checkedKeys="checkedKeys">
        </a-tree>
      </div>
    </div>
    <div>
      <div>
        <a-row>
          <a-col class="line-height-box" :span="10">
            <span class="title-form-title">日期范围：</span>
            <a-range-picker class="title-form-picker" :show-time="{ format: 'HH:mm:ss' }" v-model:value="dataCenter.time3"
              format="YYYY-MM-DD HH:mm:ss" :placeholder="['开始时间', '结束时间']" />
          </a-col>
          <a-col class="line-height-box" :span="14">
            <span class="title-form-title">时段类型：</span>
            <a-radio-group @change="changeStepSize" :options="dataCenter.groupOption"
              v-model:value="dataCenter.formData.step_size" />
          </a-col>
          <a-col class="line-height-box" :span="19">
            <span class="title-form-title">统计特征：</span>
            <a-checkbox-group @change="changeGroup" :disabled="dataCenter.formData.step_size == 'R'"
              v-model:value="dataCenter.formData.attr" :options="dataCenter.checkboxOption" />
          </a-col>
          <a-col class="line-height-box" :span="5">
            <div class="line-btn">
              <a-button class="margin-btn" @click="resetting">重置</a-button>
              <a-button class="margin-btn" type="primary" @click="queryForm">查询</a-button>
              <a-button class="margin-btn" :disabled="showDraw" type="primary" @click="drawBtn">绘图</a-button>
              <a-button class="margin-btn" type="primary" @click="exportDataFn">导出</a-button>
            </div>
          </a-col>
          <!-- <a-col class="line-height-box" :span="2">
            <div class="line-btn">
              <a-button class="margin-btn" :disabled="showDraw" type="primary" @click="drawBtn">绘图</a-button>
            </div>
          </a-col> -->
          <!-- <a-col class="line-height-box" :span="3">
            <div class="line-btn">
              <a-button class="margin-btn" :disabled="showDraw" type="primary" @click="drawBtn">绘图</a-button>
              <a-button class="margin-btn" type="primary" @click="exportDataFn">导出</a-button>
            </div>
          </a-col> -->
        </a-row>
      </div>
      <div>
        <a-table :pagination="false" class="ant-table-striped" bordered :scroll="{ x: 1000, y: `calc(100vh - 300px)` }"
          size="middle" :dataSource="dataCenter.dataSource" :columns="dataCenter.columns" />
      </div>
    </div>
    <BasicModal :maskClosable="false" :footer="null" :canFullscreen="false" @cancel="cancel" :visible="showModal" :width="1200" :title="drawTitle">
      <div>
        <div id="visible-id" style="width: 100%;height: 500px;"></div>
      </div>
    </BasicModal>
  </div>
</template>
<script lang="tsx" setup>
import { exportData } from '/@/utils/fnUtils.ts';
import { ref, onMounted, reactive, computed } from 'vue'
import { BasicModal } from '/@/components/Modal/index';
import moment from 'moment';
import * as echarts from 'echarts';
import { message, Modal } from 'ant-design-vue';
import {
  getRiverTree,
  getHistCompute
} from '/@/api/swHome/index';
import { fontWeight } from 'html2canvas/dist/types/css/property-descriptors/font-weight';
let showModal = ref(false)
let dataCenter = reactive({
  treeOriginalData: {},
  treeData: [],
  time3: [],
  tableList: {},
  formData: {
    step_size: 'R',
    attr: [],
    senid: []
  },
  groupOption: [
    { label: '实时', value: 'R' },
    { label: '小时', value: 'H' },
    { label: '日', value: 'D' },
    { label: '月', value: 'M' },
    { label: '年', value: 'Y' },
  ],
  checkboxOption: [
    { label: '整点值', value: 'v' },
    { label: '平均值', value: 'avgv' },
    { label: '最大值', value: 'maxv' },
    { label: '最大值时间', value: 'maxt' },
    { label: '最小值', value: 'minv' },
    { label: '最小值时间', value: 'mint' },
  ],
  columns: [],
  dataSource: []
})
const cancel = () => {
  showModal.value = false
}
// 计算是否显示绘制按钮
let showDraw = computed(() => {
  let type = true
  let arr = []
  checkedKeys.value.forEach(element => {
    if (typeof element === 'number') {
      arr.push(element)
    }
  });
  // 判断是否只选了一个senId
  if (arr.length != 1) {
    type = false
  }
  // 判断是否是实时
  if (dataCenter.formData.step_size != 'R') {
    if (dataCenter.formData.attr.length > 2) {
      type = false
    }
    if (dataCenter.formData.attr.length == 0) {
      type = false
    }
    let typeNumber = 0
    dataCenter.formData.attr.forEach(element => {
      if (element == 'v') {
        typeNumber++
      }
      if (element == 'avgv') {
        typeNumber++
      }
    });
    if (typeNumber == 2) {
      type = false
    }

  }
  if (dataCenter.dataSource.length == 0) {
    type = false
  }
  return !type
})
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const checkedKeys = ref<string[]>([]);
const handleTree = () => {
  console.log(dataCenter.treeOriginalData)
  dataCenter.treeData.push({
    title: dataCenter.treeOriginalData.basin_name,
    key: dataCenter.treeOriginalData.basin_name,
    children: []
  })
  let arr = []
  // 获取第二层
  for (const key in dataCenter.treeOriginalData.station) {
    if (Object.prototype.hasOwnProperty.call(dataCenter.treeOriginalData.station, key)) {
      const element = dataCenter.treeOriginalData.station[key];
      let obj = {
        title: key,
        key: key,
        children: []
      }
      element.forEach((elements, indexs) => {
        let obj2 = {
          title: elements.st_name,
          key: elements.st_name,
          children: []
        }
        elements.sensor.forEach((element3, index3) => {
          obj2.children.push({
            title: element3.sensor_name,
            key: element3.senid,
            dchar:element3.dchar,
            children: []
          })
        });
        obj.children.push(obj2)
      });
      dataCenter.treeData[0].children.push(obj)
    }
  }
}
let drawTitle = ref('')
const drawBtn = () => {
  let timeArr = []
  let valueArr = []
  // 获取名称
  drawTitle.value = dataCenter.columns[1].title
  dataCenter.dataSource.forEach(element => {
    if (element.time != '最大值' && element.time != '最小值') {
      timeArr.push(element.time)
      for (const key in element) {
        if (Object.prototype.hasOwnProperty.call(element, key)) {
          const elements = element[key];
          if (elements.indexOf('-') == -1 && elements != '最大值' && elements != '最小值') {
            valueArr.push(elements * 1)
          }
        }
      }
    }

  });
  // 判断是否是水温
  let yl = false
  dataCenter.columns.forEach(element => {
    if (element.title.indexOf('雨量') != -1) {
      yl = true
    }
  });
  showModal.value = true
  setTimeout(() => {
    setChartsFn(timeArr, valueArr, yl)
  }, 0);
}
let chart
const setChartsFn = (timeArr, valueArr, yl) => {
  if (chart) {
    chart.clear();
  }
  chart = echarts.init(document.getElementById('visible-id'));
  var option
  // if (yl) {
  option = {
    title: {
      text: drawTitle.value
    },
    grid: {
      left: '5%',
      right: '3%',
      bottom: '7%',
    },
    toolbox: {
      feature: {
        saveAsImage: {
          name: drawTitle.value
        }
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    xAxis: {
      type: 'category',
      data: timeArr,
      axisLabel: {
        //x轴文字的配置
        show: true,
        textStyle: {
          color: '#333',
        },
        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: '单位：'+dcharName.value,
      scale: true,
      axisLabel: {
        //y轴文字的配置
        textStyle: {
          color: '#333',
          margin: 15,
        },
        formatter: function (value) {
          return value + '';
        },
        // formatter: '{value} %'//y轴的每一个刻度值后面加上‘%’号
      },
      splitLine: {
        //网格线
        lineStyle: {
          type: 'dashed', //设置网格线类型 dotted：虚线 solid:实线
          width: 1, //y轴线的宽度
          color: '#ccc',
        },
        show: true, //隐藏或显示
      },
    },
    series: [
      {
        data: valueArr,
        type: yl ? 'bar' : 'line',
        smooth: true,
        markPoint: { // 设置最大值和最小值
          data: [
            {
              type: "max",
              name: "我是最大值",
              itemStyle: {color: '#B2D6FA'}, label: {color: 'red',fontWeight: 'bold'}
            },
            {
              type: "min",
              name: "我是最小值",
              itemStyle: {color: '#B2D6FA'}, label: {color: 'red',fontWeight: 'bold'}
            },
          ],
        },
      },
    ],
  };
  // }


  option && chart.setOption(option);

}
let changeGroupArr = []
const changeGroup = (e) => {
  // dataCenter.formData.attr
  if (changeGroupArr.length > e.length) {
    let arr = compareArrays(changeGroupArr, e)
    if (arr[0] == 'maxv') {
      dataCenter.formData.attr.forEach((element, index) => {
        if (element == 'maxt') {
          dataCenter.formData.attr.splice(index, 1)
        }
      });
    }
    if (arr[0] == 'maxt') {
      dataCenter.formData.attr.forEach((element, index) => {
        if (element == 'maxv') {
          dataCenter.formData.attr.splice(index, 1)
        }
      });
    }
    if (arr[0] == 'minv') {
      dataCenter.formData.attr.forEach((element, index) => {
        if (element == 'mint') {
          dataCenter.formData.attr.splice(index, 1)
        }
      });
    }
    if (arr[0] == 'mint') {
      dataCenter.formData.attr.forEach((element, index) => {
        if (element == 'minv') {
          dataCenter.formData.attr.splice(index, 1)
        }
      });
    }
  } else {
    let arr = compareArrays(changeGroupArr, e)
    if (arr[0] == 'maxv') {
      dataCenter.formData.attr.push('maxt')
    }
    if (arr[0] == 'maxt') {
      dataCenter.formData.attr.push('maxv')
    }
    if (arr[0] == 'minv') {
      dataCenter.formData.attr.push('mint')
    }
    if (arr[0] == 'mint') {
      dataCenter.formData.attr.push('minv')
    }
  }
  changeGroupArr = JSON.parse(JSON.stringify(e))
}
function compareArrays(arr1, arr2) {
  return arr1.concat(arr2).filter(function (v, i, arr) {
    return arr.indexOf(v) === arr.lastIndexOf(v);
  });
}
// 导出
const exportDataFn = () => {
  exportData(dataCenter.columns, dataCenter.dataSource, '数据校核.xlsx')
}
const setTheadName = (name) => {
  switch (name) {
    case 'v':
      return '整点值'
    case 'avgv':
      return '平均值'
    case 'maxv':
      return '最大值'
    case 'maxt':
      return '最大值时间'
    case 'minv':
      return '最小值'
    case 'mint':
      return '最小值时间'
    case 'factv':
      return '实时'
    default:
      break;
  }
}
const changeStepSize = (item) => {
  console.log(item.target.value)
  if (item.target.value == 'R') {
    dataCenter.formData.attr = []
    changeGroupArr = []
  }
}
const handleTable = () => {
  //处理头部数据
  dataCenter.columns = []
  dataCenter.dataSource = []
  dataCenter.columns.push(
    {
      title: '时间',
      dataIndex: 'time',
      key: 'time',
      width: 200,
      align: 'center'
    }
  )
  // 处理时间数据
  dataCenter.tableList.time.forEach(element => {
    dataCenter.dataSource.push({ time: element })
  });
  // 处理表头数据
  //判断实时表头
  if (dataCenter.formData.step_size == 'R') {
    dataCenter.tableList.thead.forEach(element => {

      element.value.forEach((element1, index1) => {
        let obj = {
          title: element.sensor_name,
          dataIndex: element.senid + '&' + element1,
          key: element.senid + '&' + element1,
          align: 'center',
          width: 100
        }
        dataCenter.columns.push(obj)
      });
    });
  } else {
    dataCenter.tableList.thead.forEach(element => {
      let obj = {
        title: element.sensor_name,
        dataIndex: element.sensor_name,
        key: element.sensor_name,
        align: 'center',
        children: []
      }
      element.value.forEach((element1, index1) => {
        obj.children.push({
          title: setTheadName(element1),
          dataIndex: element.senid + '&' + element1,
          key: element.senid + '&' + element1,
          align: 'center',
          width: setTheadName(element1).indexOf("时间") != -1 ? 200 : 100,
        })
      });
      dataCenter.columns.push(obj)

    });
  }
  // 处理数据体
  let tbodyArr = Object.values(dataCenter.tableList.tbody[0])
  tbodyArr.forEach((element, index) => {
    dataCenter.tableList.thead.forEach((element1, index1) => {
      element1.value.forEach((element2, index2) => {
        let name = element1.senid + "&" + element2
        dataCenter.dataSource[index][name] = element[index1][element2]
      });

    });
  });


}
const getCorrespondingOptimazeData = () => {
  getRiverTree().then(res => {
    dataCenter.treeOriginalData = res.data.data_value
    handleTree()
  })
}

const resetting = () => {
  dataCenter.time3 = []
  dataCenter.formData.step_size = 'R'
  dataCenter.formData.attr = []
  changeGroupArr = []
}

const queryForm = () => {
  dataCenter.formData.senid = []
  if (dataCenter.time3.length != 2) {
    message.warning('请选择查询时间');
    return false
  }
  if (dataCenter.formData.attr.length == 0 && dataCenter.formData.step_size != 'R') {
    message.warning('请选择统计特征');
    return false
  }
  checkedKeys.value.forEach(element => {
    if (typeof element === 'number') {
      dataCenter.formData.senid.push(element)
    }
  });
  if (dataCenter.formData.senid.length == 0) {
    message.warning('请选择测站');
    return false
  }
  dataCenter.formData.start_time = moment(dataCenter.time3[0]).format('YYYY-MM-DD HH:mm:ss')
  dataCenter.formData.end_time = moment(dataCenter.time3[1]).format('YYYY-MM-DD HH:mm:ss')
  console.log(dataCenter.formData)
  getHistCompute(dataCenter.formData).then(res => {
    dataCenter.tableList = res.data
    handleTable()
  })
}
/**
 * 点击树选择框的事件
 */
let dcharName = ref('')
const checkTree = (checkedKeys,e) => {
  if(e.checkedNodes.length == 1){
    dcharName.value = e.checkedNodes[0].props.dchar
  }
}
onMounted(() => {
  getCorrespondingOptimazeData()
})
</script>
<style scoped lang="less">
.box-main {
  display: flex;
  height: 100%;

  &>div:nth-child(1) {
    width: 300px;
    background-color: #fff;
  }

  &>div:nth-child(2) {
    flex: 1;
    margin-left: 10px;
    height: calc(100vh - 80px);
    background-color: #fff;
    padding: 10px;
    overflow: hidden;
  }
}

.left-box {
  height: calc(100vh - 80px);
  overflow: hidden;
}

.left-title {
  background-color: #f8f8f8;
  line-height: 45px;
  text-align: center;
  font-weight: 500;
  margin: 10px;
}

.left-tree {
  background-color: #f8f8f8;
  height: calc(100% - 75px);
  margin: 10px;
  overflow: auto;
}

.title-form-title {
  display: inline-block;
  width: 80px !important;
  text-align: right;
}

.title-form-picker {
  width: calc(100% - 120px) !important;
  display: inline-block;
}

.line-height-box {
  line-height: 52px;
}

.line-btn {
  text-align: right;

  .margin-btn {
    margin-right: 10px;
  }
}

// ::v-deep(.ant-table-striped .ant-table-body){
//   height: calc(100vh - 318px);
// }
</style>