import PipeQueryHelper from "./PipeQueryHelper.js";
/**
 * 该类用于管网统计
 */
class PipeStatisticsHelper {
  constructor() {}
  static viewer = null;

  static setViewer(val) {
    this.viewer = val;
  }

  /**
   * 管线类图层统计
   * @param recordsets 
   * @param tableName 
   * @param fieldName 
   */
  static settingStatisticsTable(options = {
    recordsets: [],
    tableName: '',
    fieldName: '',
    fieldCaption: '',
    NULLCaption: '', //空值是指定属性名
  }) {
    let data = [];
    let allLayerLength = 0;
    options.recordsets.forEach(dataset => {
      const features = dataset.features;
      let featureType = {};
      let rowindex = 0;
      features.forEach(feature => {
        let subtype = feature.attributes[options.fieldName];
        if (options.NULLCaption && subtype === "") {
          subtype = options.NULLCaption;
        }
        const pipelen = feature.attributes["PIPE_LENGTH"];
        if (featureType.hasOwnProperty(subtype)) {
          featureType[subtype] = parseFloat(featureType[subtype]) + parseFloat(pipelen);
        } else {
          featureType[subtype] = parseFloat(pipelen);
        }
      });
      const layername = _.find(PipeQueryHelper.pipe, layer => {
        return layer.mapname === dataset.datasetName;
      }).title;
      const rowcount = Object.getOwnPropertyNames(featureType).length;
      let layerTotalLength = 0;
      for (let i in featureType) {
        const lineLen = parseFloat((parseFloat(featureType[i])).toFixed(4));
        layerTotalLength += lineLen;
        if (rowindex === 0) {
          data.push({
            "layer": layername,
            "fieldvalue": i,
            "count": lineLen,
            "rowspan": rowcount + 1
          });
          rowindex += 1;
        } else {
          data.push({
            "layer": layername,
            "fieldvalue": i,
            "count": lineLen,
            "rowspan": 0
          });
        }
      }
      if (rowcount === 0) {
        data.push({
          "layer": layername,
          "fieldvalue": "",
          "count": layerTotalLength.toFixed(2),
          "rowspan": 1
        });
      } 
      // else {
      //   data.push({
      //     "layer": layername,
      //     "fieldvalue": "小计",
      //     "count": layerTotalLength.toFixed(2),
      //     "rowspan": 0
      //   });
      // }
      // allLayerLength += layerTotalLength;
    });
    // data.push({
    //   "layer": "",
    //   "fieldvalue": "合计",
    //   "count": allLayerLength.toFixed(2),
    //   "rowspan": 1
    // });

    console.log('data', data);

    return data;
  }
  /**
   * 管点类图层统计
   * @param recordsets 
   * @param tableName 
   * @param fieldName 
   */
  static settingPointStatisticsTable(options = {
    recordsets: [],
    tableName: '',
    fieldName: '',
    fieldCaption: '',
    target: null
  }) {

    let data = [];
    let allLayerLength = 0;
    options.recordsets.forEach(dataset => {
      const features = dataset.features;
      let featureType = {};
      let rowindex = 0;
      features.forEach(feature => {
        const subtype = feature.attributes[options.fieldName];
        if (featureType.hasOwnProperty(subtype)) {
          featureType[subtype] = parseInt(featureType[subtype]) + 1;
        } else {
          featureType[subtype] = 1;
        }
      });
      const layername = _.find(PipeQueryHelper.pipe, layer => {
        return layer.mapname === dataset.datasetName;
      }).title;
      const rowcount = Object.getOwnPropertyNames(featureType).length;
      let layerTotalLength = 0;
      for (let i in featureType) {
        layerTotalLength += parseInt(featureType[i]);
        if (rowindex === 0) {
          data.push({
            "layer": layername,
            "fieldvalue": i,
            "count": featureType[i],
            "rowspan": rowcount + 1
          });
          rowindex += 1;
        } else {
          data.push({
            "layer": layername,
            "fieldvalue": i,
            "count": featureType[i],
            "rowspan": 0
          });
        }
      }
      if (rowcount === 0) {
        data.push({
          "layer": layername,
          "fieldvalue": "",
          "count": layerTotalLength,
          "rowspan": 1
        });
      } else {
        data.push({
          "layer": layername,
          "fieldvalue": "小计",
          "count": layerTotalLength,
          "rowspan": 0
        });
      }
      allLayerLength += layerTotalLength;
    });
    data.push({
      "layer": "",
      "fieldvalue": "合计",
      "count": allLayerLength,
      "rowspan": 1
    });

    return data;
  }
  /**
   * 分段统计
   * @param options 
   */
  static settingSectionStatistics(options = {
    recordsets: [],
    tableName: '',
    s_fieldName: '',
    e_fieldName: '',
    fieldCaption: '',
    sectionTable: null,
    target: null
  }) {
    let data = [];
    let allLayerLength = 0;
    options.recordsets.forEach(dataset => {
      const features = dataset.features;
      let featureType = [];
      const tbdata = options.sectionTable.data();
      const tableRowLength = tbdata.length;
      for (let i = 0; i < tableRowLength; i++) {
        const row = tbdata[i];
        const upper = parseFloat(row["upper"]);
        const lower = parseFloat(row["lower"]);
        featureType.push({
          "upper": upper,
          "lower": lower,
          "title": lower + "~" + upper,
          "length": 0
        });
      }
      let rowindex = 0;
      features.forEach(feature => {
        const startDep = feature.attributes[options.s_fieldName];
        const endDep = feature.attributes[options.e_fieldName];
        const pipelen = feature.attributes["PIPE_LENGTH"];
        featureType.forEach(item => {
          if ((startDep >= item["lower"] && startDep < item["upper"]) || (endDep >= item["lower"] && endDep < item["upper"])) {
            item["length"] += parseFloat(pipelen)
          }
        });
      });
      const layername = _.find(PipeQueryHelper.pipe, layer => {
        return layer.mapname === dataset.datasetName;
      }).title;
      const rowcount = featureType.length;
      let layerTotalLength = 0;
      for (let j = 0; j < rowcount; j++) {
        const lineLen = parseFloat((parseFloat(featureType[j]["length"])).toFixed(4));
        layerTotalLength += lineLen;
        if (rowindex === 0) {
          data.push({
            "layer": layername,
            "fieldvalue": featureType[j]["title"],
            "count": lineLen,
            "rowspan": rowcount + 1
          });
          rowindex += 1;
        } else {
          data.push({
            "layer": layername,
            "fieldvalue": featureType[j]["title"],
            "count": lineLen,
            "rowspan": 0
          });
        }
      }
      if (rowcount === 0) {
        data.push({
          "layer": layername,
          "fieldvalue": "",
          "count": layerTotalLength.toFixed(2),
          "rowspan": 1
        });
      } else {
        data.push({
          "layer": layername,
          "fieldvalue": "小计",
          "count": layerTotalLength.toFixed(2),
          "rowspan": 0
        });
      }
      allLayerLength += layerTotalLength;
    });
    data.push({
      "layer": "",
      "fieldvalue": "合计",
      "count": allLayerLength.toFixed(2),
      "rowspan": 1
    });
    return data;
  }
  /**
   * 统计图表
   */
  static addPipeStatisticsChart(name = '', data = [], target = null, geometryType = "line") {
    const container = document.createElement('div');
    container.setAttribute("style", "height:99%;width:99%;");
    container.id = "chart_" + target.baseClass;
    let chartData = {};
    let tabledatas = [];
    for (let i = 0, length = data.length; i < length; i++) {
      tabledatas.push(data[i]);
    }
    tabledatas.forEach(row => {
      if (row.layer !== "" && row.fieldvalue !== "小计" && row.layer !== "合计") {
        if (row.rowspan === 1) {
          chartData[row.layer] = {
            "total": row.count,
            "sub": [{
              "name": row.fieldvalue,
              "count": row.count
            }]
          };
        } else {
          if (chartData.hasOwnProperty(row.layer)) {
            chartData[row.layer].sub.push({
              "name": row.fieldvalue,
              "count": row.count
            })
          } else {
            chartData[row.layer] = {
              "total": 0,
              "sub": []
            };
            chartData[row.layer].total = tabledatas.find(item => {
              return item.layer === row.layer && item.fieldvalue === "小计";
            }).count;
            chartData[row.layer].sub.push({
              "name": row.fieldvalue,
              "count": row.count
            })
          }
        }
      }
    })
    const yAxisName = geometryType === "line" ? "长度(m)" : "数量";
    const seriesName = geometryType === "line" ? "管线长度" : "管点个数";
    let xAxis = [];
    let seriesdata = [];
    //let data3d=[];
    for (let key in chartData) {
      xAxis.push(key);
      seriesdata.push(chartData[key].total);
      //data3d.push([key,0,chartData[key].total]);
    }
    const width = this.viewer.scene.drawingBufferWidth * 0.8;
    target.popup.setSizeWithoutBtns(width, 500);
    target.popup.show(name, container.outerHTML, true);
    const firstPieData = chartData[tabledatas[0].layer]["sub"].map(item => {
      if (parseFloat(item["count"]) === 0.0) {
        return {
          name: item.name,
          value: item.count,
          itemStyle: {
            color: 'rgba(255,255,255,0)',
            borderWidth: 1,
            borderColor: '#000'
          }
        }
      } else {
        return {
          name: item.name,
          value: item.count
        };
      }
    });
    const firstPie = {
      name: tabledatas[0].layer,
      type: 'pie',
      data: firstPieData,
      center: ["88%", "45%"],
      radius: "44%",
      markPoint: {
        symbol: 'circle',
        symbolSize: 0.01,
        label: {
          show: true,
          position: 'inside',
          formatter: tabledatas[0].layer,
          fontSize: 16
        },
        data: [{
          x: width * 0.86,
          y: 440 * 0.8
        }]
      },
      z: 100
    }
    const options = {
      title: "",
      grid: {
        right: "25%"
      },
      xAxis: {
        data: xAxis,
        axisLabel: {
          interval: 0
        }
      },
      tooltip: {},
      yAxis: {
        name: yAxisName
      },
      toolbox: {
        feature: {
          saveAsImag: {}
        }
      },
      series: [{
        name: seriesName,
        type: "bar",
        data: seriesdata,
        label: {
          show: true, //是否展示  
          position: 'top', //在顶端
          textStyle: {
            fontWeight: 'bolder',
            fontSize: '14',
            fontFamily: '微软雅黑'
          }
        }
      }, firstPie]
    }
    const eChart = echarts.init(target.popup.domObj.find("#chart_" + target.baseClass)[0]);
    eChart.setOption(options);
    eChart.on('click', (params) => {
      if (!chartData[params.name]) {
        return;
      }
      const pipdata = chartData[params.name]["sub"].map(item => {
        return {
          name: item.name,
          value: item.count
        };
      });
      const pie = {
        name: params.name,
        type: 'pie',
        data: pipdata,
        center: ["88%", "45%"],
        radius: "44%",
        markPoint: {
          symbol: 'circle',
          symbolSize: 0.01,
          label: {
            show: true,
            position: 'inside',
            formatter: params.name,
            fontSize: 16
          },
          data: [{
            x: width * 0.86,
            y: 440 * 0.8
          }]
        },
        z: 100
      }
      if (options.series.length === 2) {
        options.series[1] = pie
      } else {
        options.series.push(pie);
      }
      //eChart.clear();
      eChart.setOption(options);
    })
  }
}
export default PipeStatisticsHelper;
