<!-- 柱状图 -->
<template>
  <div class="chart" ref="chart" id="myChart2"></div>
</template>

<script>
import * as echarts from 'echarts';
import 'echarts-wordcloud';
// import { fontSize } from '@/views/groupPage/util'

import { queryBelongToRiver } from '/@/api/map/geologicalApi';
import eventBus from '/@/utils/eventBus';
import { useGeologicalStore } from '/@/store/modules/geological';
import TFMapUitl from '/@/utils/TFMapUitl.ts';
export default {
  name: 'Histogram', //
  props: {},
  data() {
    return {
      chartData: [],
    };
  },
  watch: {},
  mounted() {
    this.getBelongToRiverInfo();
  },
  methods: {
    // 查询所属河段信息
    async getBelongToRiverInfo() {
      await queryBelongToRiver().then((res) => {
        console.log('所属河段信息', res);
        this.chartData = res.result
          .filter((item) => {
            return item.value > 0;
          })
          .sort((a, b) => {
            if (a.value < b.value) {
              // a b 分别是Arr中的 56 21
              return 1; //返回正数 ，b排列在a之前
            } else {
              return -1; //返回负数 ，a排列在b之前
            }
          });

        let sshdCount = this.chartData.length;
        // this.chartData.forEach((item) => {
        //   sshdCount += item.value;
        // });
        this.$emit('getSshdTotal', sshdCount);
      });
      this.$nextTick(() => {
        this.initialChart();
      });
    },
    // 初始化柱状图
    initialChart() {
      let data = this.chartData;
      // data.push(this.chartData[0])
      // console.log(data,'data');
      const myChart2 = echarts.init(document.getElementById('myChart2'));
      //获取 最大的字的个数
      let textMax = '';
      data.forEach((t) => {
        if (t.name && textMax.length < t.name.length) {
          textMax = t.name;
        }
      });
      // 计算y轴文字的长度
      let leftPX = textMax.length * 14 + 1;
      const getArrByKey = (data, k) => {
        let key = k || 'value';
        let res = [];
        if (data) {
          data.forEach(function (t) {
            // console.log("t的数据格式",t);
            t.name = t.name + '%' + t.sshdid
            res.push(t[key]);
          });
        }
        return res;
      };
      const getSymbolData = (data) => {
        let arr = [];
        for (var i = 0; i < data.length; i++) {
          arr.push({
            value: data[i].value,
            sshdid: data[i].sshdid,
            symbolPosition: 'end',
          });
        }
        return arr;
      };
      let option = {
        // backgroundColor: 'rgba(3, 49, 79, 0.4)',
        // 整个图表偏移
        grid: {
          top: '1%',
          bottom: 10,
          //   right: 100,
          left: 100,
          //   containLabel: true
          right: 100,
        },
        xAxis: {
          // type: 'category',
          show: false,
          // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: [
          {
            barGap: '-10%',
            triggerEvent: true,
            show: true,
            inverse: true, //数据反转展示
            data: getArrByKey(data, 'name'), //自定义刻度
            axisLine: {
              show: false,
            },
            splitLine: {
              show: false,
            },
            axisTick: {
              show: false,
            },

            axisLabel: {
              cursor: 'default',
              //设置y轴的刻度
              show: true,
              interval: 0,
              color: '#fff',
              // left: -200,
              // align: 'left',
              // margin: 90,
              formatter: function (params) {
                // console.log("此时的参数", params);
                for (let i = 0; i < params.length; i++) {
                  if (params[i] == '%') {
                    // console.log("&&&&&&&&&", i);
                    params = params.substr(0, i)//下标和长度
                  }
                }
                // console.log("此时的参数111", params);
                var newParamsName = '';
                var paramsNameNumber = params.length;
                var provideNumber = 5; //每行显示个数
                var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                if (paramsNameNumber > provideNumber) {
                  for (var p = 0; p < rowNumber; p++) {
                    var tempStr = '';
                    var start = p * provideNumber;
                    var end = start + provideNumber;
                    if (p == rowNumber - 1) {
                      tempStr = params.substring(start, paramsNameNumber);
                    } else {
                      tempStr = params.substring(start, end) + '\n';
                    }
                    newParamsName += tempStr;
                  }
                } else {
                  newParamsName = params;
                }
                return newParamsName;
                // return '{title|' + value + '}';
              },
              rich: {
                title: {
                  width: 30,
                  align: 'right',
                  fontSize: 12,
                },
              },
            },
          },
        ],

        series: [
          {
            cursor: 'pointer',
            // cursor: 'default' ,
            //控制绿色小圆点
            name: 'XXX',
            type: 'pictorialBar',
            symbol:
              'image://data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADoAAAA6CAMAAADWZboaAAAAZlBMVEUAAABe3uVe3+Vf3uVf3+Zf3uVg3+Zg3+Zf3+Vi4OZh4OZg3+Z86/Bh3+Zi4Odj4Odi4OZ86/B76/B86/Bj4ed56+9x5+xn4umB7/N87PB36e+A7/N+7fF/7vJ/7vJ+7fGA7/OB7/PReX+lAAAAIXRSTlMABQkVDREmIhk3MR10LEFFPHh7cUprXE35h2XnqMLAp+mHAG9cAAAB5ElEQVRIx83WjU7CMBQFYIoiKMqU/XUboHv/l/Tce7t2XamDNSacETEmX86tlK2rx4py150o+MstMBLwWRfHKo6JCVxLnvmFGBjFQ58oF1//sUZhGy/ClSTWObgnL4O+bkeN4nY2okfNMbkRt9/vtxz8InoTsWplJSCzFxPmO8+GpSIByX3YQAuGDWtRKhKjCnxDXhF6Z4yxnZ20Wgko7BMRDmxtSGVaI4kdTIgb+zTYoJQlIMlDlmUFgrcDWWC201qSayqlTkiCddWWeV62VU0YlnpRi9VOKaSUsiyq/N0krwq2Ugt7lVpZl5BfHNiytjagMi+XYp0kCR45hMlivVQrE/uU5pXSrCB5bM6d1t2lOZItMqmliT3q5uVxqxzyW/ccfYLNKx7ZTeykMvNyac2yt2Fbc61MHLSC0rwoxbiNdlQ3GBm1NLHQsHUrtEXppR/ljNpW6DbSCoqlFiVoN6YdaFlgsSFVPs1BdT8OaB5QyQzVcaqWDows/zepxR8ObLglTrdtCRVuRNj4Rrxh+//0ke2f8KVL+Kon3GCSbmsJN9OUW3j6g0Ns+LgCij2u0h+Sghc8mlMPBMgdx5DFh59VmOVHrvmDnoNxCz3J7MFWsMuaLyR089xz/xhlfijvwutR8gv3zk6BLUUeCgAAAABJRU5ErkJggg==',
            symbolSize: [30, 30],
            symbolOffset: [20, 0],
            z: 12,
            itemStyle: {
              normal: {
                color: '#fff',
                cursor: 'pointer',
              },
            },
            label: {
              cursor: 'default',
              position: 'top', //在上方显示
            },
            // 控制圆点图标点击事件获取的数据，不加入id则查询所有数据
            data: getSymbolData(data),
          },
          {
            cursor: 'pointer',
            //控制柱状条
            name: '条',
            type: 'bar',
            showBackground: false,
            // barBorderRadius: 30,
            yAxisIndex: 0,
            data: data,
            barWidth: 5,
            // align: left,
            itemStyle: {
              normal: {
                // cursor: 'pointer',
                color: 'rgba(41, 162, 245, 1)',
                // barBorderRadius: 10
              },
              // color: '#A71A2B',
              // barBorderRadius: 4,
            },
            label: {
              normal: {
                color: '#fff',
                show: true,
                position: 'insideRight',
                distance: -35,
                textStyle: {
                  fontSize: 12,
                },
                formatter: function (a, b) {
                  return a.value + '个';
                },
              },
            },
          },
        ],

        dataZoom: [
          {
            id: 'dataZoomY',
            yAxisIndex: [0, 1],
            show: true, // 是否显示滑动条，不影响使用
            type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
            start: 0, // 默认显示0%
            // startValue: 2000000, // 从末尾开始--进行倒序
            // endValue: 4, // 一次性展示5个
            width: 6,
            borderColor: 'transparent',
            fillerColor: 'rgba(0, 126, 143,1)',
            zoomLock: true,
            showDataShadow: false, // 是否显示数据阴影 默认auto
            // backgroundColor: '#fff',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            showDetail: false, // 即拖拽时候是否显示详细数值信息 默认true
            realtime: true, // 是否实时更新
            // filterMode: 'filter',
            // handleIcon: 'circle',
            handleStyle: {
              color: 'rgba(205,205,205,0.1)',
              borderColor: 'rgba(205,205,205,0.1)',
            },
            handleSize: '80%',
            moveHandleSize: 0,
            maxValueSpan: 3,
            minValueSpan: 3,
            brushSelect: false, // 刷选功能，设为false可以防止拖动条长度改变 ************（这是一个坑）
          },
          {
            type: 'inside',
            yAxisIndex: [0, 1],
            start: 0, // 默认显示0%
            zoomOnMouseWheel: false, // 滚轮是否触发缩放
            moveOnMouseMove: true, // 鼠标滚轮触发滚动
            moveOnMouseWheel: true,
          },
        ],
      };
      // debugger;
      // 显示柱状图
      myChart2.setOption(option);
      // // 自适应布局
      // window.addEventListener("resize", function (event) {
      //     myChart2.resize();
      // });

      // 点击柱状图
      myChart2.on('click', (params) => {
        console.log('柱状图的参数', params);
        if (params.componentType == "yAxis") {
          // console.log("点击y轴所得参数", params);
          let index = 0
          for (let i = 0; i < params.value.length; i++) {
            if (params.value[i] == '%') {
              // console.log("&&&&&&&&&", i);
              index = i
            }
          }
          // console.log("此时的参数", params.value.substr(index+1,params.value.length-1));
          eventBus.emit('toSshdid', params.value.substr(index + 1, params.value.length));
          //通过点击获取地灾点数据
          if (params && params.value) {
            const geologicalStore = useGeologicalStore();
            geologicalStore.DzdxInfo({ sshdid: params.value.substr(index + 1, params.value.length), type: 'hd' }).then((tempData) => {
              const idList = [];
              if (tempData) {
                tempData.forEach((item) => {
                  var id = TFMapUitl.getId('dzd', item.id);
                  idList.push(id);
                });
                TFMapUitl.mapPointLocation_list3(map, idList);
              }
              // dzlxList.value = tempData;
            });
          }
        } else {
          eventBus.emit('toSshdid', params.data.sshdid);
          //通过点击获取地灾点数据
          if (params && params.data && params.data.sshdid) {
            const geologicalStore = useGeologicalStore();
            geologicalStore.DzdxInfo({ sshdid: params.data.sshdid, type: 'hd' }).then((tempData) => {
              const idList = [];
              if (tempData) {
                tempData.forEach((item) => {
                  var id = TFMapUitl.getId('dzd', item.id);
                  idList.push(id);
                });
                TFMapUitl.mapPointLocation_list3(map, idList);
              }
              // dzlxList.value = tempData;
            });
          }
        }
      });

      // myChart2.on('mousemove', function (params) {
      //   if (params.componentType == "yAxis") {
      //     console.log("yzhou", params);
      //     cursor: 'default'
      //   }
      // });

      // 当上面的自适应布局不其作用时，可以改换成下面这种
      setTimeout(function () {
        window.onresize = function () {
          myChart2.resize();
          // swChart.resize();
        };
      }, 200);
    },
  },
};
</script>

<style lang="less" scoped>
.chart {
  height: 100%;
  width: 100%;
  position: relative;
  // z-index:99;
  // overflow-x:auto;
  // overflow-y: auto;
  overflow: auto;
  
  
}

#myChart2 {
  div>div>canvas:hover {
    cursor: default !important;
  }
}

.chart::-webkit-scrollbar-thumb {
    background-color: #007e8f !important;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2) !important;
    border-radius: 2px;
  }
</style>
