import {HttpResetClass} from 'vue-client'

//请求当前公司的小区
export function select(self, param, condition) {
  var items = '\'f_residential_area\' value,F_RESIDENTIAL_AREA label'
  var tablename = 't_area'
  var sqlcondition = {items: items, tablename: tablename, condition: condition}
  let load = new HttpResetClass()
  load.load("POST", "/api/af-revenue/sql/singleTableParam",
    {data: sqlcondition},
    {resolveMsg: null, rejectMsg: null})
    .then((res) => {
      console.log(res.data, param, '返回数据')
      let children = []
      res.data.forEach((area) => {

        var result = {label: area.label, value: Math.random(), name: area.value}
        children.push(result)
      })
      for (var i = 0; i < self.drillparam.length; i++) {
        var s = self.drillparam[i]
        if (s.name == param) {
          self.drillparam[i] = {label: s.label, value: s.value, name: s.name, children: children}
        }
      }
      console.log(self.drillparam, '子列')
    })
}

//请求后台数据
export function getData(self, sqlname,condition) {
  console.log("---------------echart的condition",condition)
  let load = new HttpResetClass();
  load.load("POST", 'api/af-revenue/sql/jyd'+sqlname,
    {data: condition},
    {resolveMsg: null, rejectMsg: null})
    .then((res) => {
      console.log(res.data, '返回数据')
      self.sqlobtaindata = res.data
    })
}

//时间类柱状图数据整合
export function DataIntegration(data) {
  var cachedata = data
  var param = []
  console.log(cachedata, '待整合数据')
  param.push(cachedata[0].type)
  // 获取时间下的分类
  for (var i = 1; i < cachedata.length; i++) {
    var l = 0
    for (var j = 0; j < param.length; j++) {
      if (param[j] != cachedata[i].type) {
        l++
      }
    }
    if (l == param.length) {
      param.push(cachedata[i].type)
    }
  }
// 按照分类进行时间划分
  var result = []
  for (var i = 0; i < param.length; i++) {
    var item = {}
    var chilrenlist = []
    data.forEach(function (s) {
      if (s.type == param[i]) {
        var h = {}
        h.name = s.name
        h.value = s.value
        chilrenlist.push(h)
      }
    })
    item.name = param[i]
    item.value = chilrenlist
    result.push(item)
  }
  return result
}

//绘制饼状图
export function setPie(self, id, data) {
  console.log(data, '饼状图数据')
  // 获取显示区域
  self.xc = self.$echarts.init(document.getElementById(id))
  var scale = 0.8
  // 获取图例
  var legendname = []
  data.forEach(function (s) {
    legendname.push(s.name)
  })
  // 获取数据
  var echartData = data
  // 自定义样式
  var rich = {
    white: {
      color: "#fff",
      align: 'center',
      fontSize: 12 * scale,

      padding: [4, 0]
    },
    blue: {
      color: '#e1e52a',
      fontSize: 12 * scale,
      align: 'center',
      padding: [6, 0]
    },
    hr: {
      borderColor: '#64d8d4',
      width: '100%',
      borderWidth: 0.5,
      height: 0,
    },
  }
  var total = 0;
  var result = ''
  // 数据求和
  data.forEach(function (value) {
    total += value.value;
  });
  // 数据进行处理，增加单位万
  var index = total.toString().length
  if (index > 4) {
    var i = total.toString().substring(0, index - 4)
    var s = total.toString().substring(index - 4, index - 3)
    result = i + '.' + s + '万'
  } else {
    result = total
  }
  var s = ""
  for (var i = 4; i > 0; i--) {
    if (result.length < i) {
      s = "\t" + s
    }
  }
  result = s + result

  console.log(echartData, legendname, '绘图样式数据')
  // 绘图
  self.xc.setOption({
    title: [
      {
        text: '总用户数',
        x: '44%',
        y: '33%',
        textStyle: {
          color: '#ffffff',
          fontSize: 12 * scale,
        }
      },
      {
        text: result,
        x: '41%',
        y: '38%',
        padding: [15, 20],
        textStyle: {
          color: '#00e2ea',
          fontSize: 12 * scale,

        }
      }],
    legend: {
      orient: 'horizontal',
      icon: 'circle',
      x: 'center',
      y: '80%',
      itemWidth: 20 * scale,
      itemHeight: 10 * scale,
      textStyle: {
        fontSize: 12 * scale,
        padding: [0, 0, 0, 4],
        color: '#ffffff'
      },
      data: legendname
    },
    series: [
      {
        name: 'Line 1',
        type: 'pie',
        animation: false,
        clockWise: false,
        radius: ['25%', '26%'],
        center: ['50%', '40%'],
        itemStyle: {
          normal: {
            label: {
              show: false
            },
            labelLine: {
              show: false
            },
          }
        },
        hoverAnimation: false,
        tooltip: {
          trigger: 'axis'
        },
        data: [{
          value: 100,
          name: '02',
          itemStyle: {
            normal: {
              color: '#29b7ff',//未完成的圆环的颜色
              label: {
                show: false
              },
              labelLine: {
                show: false
              }
            }
          }
        }]
      },
      {
        name: '总用户数',
        type: 'pie',
        radius: ['30%', '40%'],
        center: ['50%', '40%'],
        hoverAnimation: false,
        color: ['#6fd9d0', '#ede61f', '#6d9bdc'],
        minAngle: 15,//最小角度
        startAngle: 60, //起始角度
        label: {
          normal: {
            borderWidth: 1,
            borderRadius: 4,
            backgroundColor: '#004b5c',
            borderColor: '#64d8d4',
            formatter: function (params, ticket, callback) {
              var total = 0; //用户总数量
              var percent = 0;
              echartData.forEach(function (value, index, array) {
                total += value.value;
              });
              if( params.name.toString().length>6){
                var s= params.name.toString().substring(6, params.name.toString().length)
                return '{white|     ' + params.name.substring(0,6) + '\n'+s+'}\n{hr|}\n{yellow|     ' + params.value + '}{blue|    ' + percent + '%}';

              }
              console.log(params.name,'cccccc')
              percent = ((params.value / total) * 100).toFixed(1);
              return '{white|' + params.name + '}\n{hr|}\n{blue|  ' + params.value + '}{blue|   ' + percent + '%}';
            },
            rich: rich,
          }
        },

        labelLine: {
          normal: {
            length: 15 * scale,
            length2: 20 * scale,
            lineStyle: {
              formatter: function (params, ticket, callback) {
                var total = 0; //用户总数量
                var percent = 0; //用户占比
                echartData.forEach(function (value, index, array) {
                  total += value.value;
                });
                percent = ((params.value / total) * 100).toFixed(1);
                if( params.name.toString().length>6){
                  var s= params.name.toString().substring(6, params.name.toString().length)
                  return '{white|     ' + params.name.substring(0,6) + '\n'+s+'}\n{hr|}\n{yellow|     ' + params.value + '}{blue|    ' + percent + '%}';

                }
                console.log(params.name,'cccccc')
                return '{white|     ' + params.name + '}\n{hr|}\n{yellow|     ' + params.value + '}\n{blue|    ' + percent + '%}';
              },
            }
          }
        },
        data: echartData
      }, {
        name: 'Line 2',
        type: 'pie',
        animation: false,
        clockWise: false,
        radius: ['44%', '45%'],
        center: ['50%', '40%'],
        itemStyle: {
          normal: {label: {show: false}, labelLine: {show: false},}
        },
        hoverAnimation: false,
        tooltip: {
          show: false
        },
        data: [{
          value: 100,
          name: '02',
          itemStyle: {
            normal: {color: '#29b7ff', label: {show: false}, labelLine: {show: false}}
          }
        }]
      }]
  }, true)
  self.xc.on("click", self.eConsole)
}

//绘制柱状图
export function setBar(self, id, data, xname, yname, seriename, idname, namesubif) {
  console.log(data, '柱状图数据')
  self.xc = self.$echarts.init(document.getElementById(id))
  var scale = 0.8
  var xAxisData = [];
  var legendData = [];
  var serieData = [];
  var metaDate = []
  var xlegen = []
  for (var i = 0; i < data.length; i++) {
    legendData[i] = data[i].name
    metaDate.push(data[i].value)
    var xnamechildren = []
    var cachedata = data[i].value
    cachedata.forEach(function (s) {
      xnamechildren.push(s.name)
    })
    xlegen.push(xnamechildren)
  }

  xAxisData = xlegen[0]
  for (var i = 1; i < xlegen.length; i++) {
    if (xlegen[i].length > xAxisData.length) {
      xAxisData = xlegen[i]
    }
  }
  xAxisData.push("")
  var tooltype = ''
  console.log(xname)
  if (xname != '') {
    tooltype = xname.substring(0, 1)
  }
  console.log(xAxisData, '系列名')
  var h = []
  metaDate.forEach(function (s) {
    var l = []
    for (var i = 0; i < xAxisData.length; i++) {
      var flag = 0
      for (var j = 0; j < s.length; j++) {
        if (s[j].name == xAxisData[i]) {
          flag++
          l.push(s[j])
        }
      }
      if (flag == 0) {
        l.push({name: xAxisData[i], value: 0})
      }
    }
    h.push(l)
  })
  metaDate = h
  var xname1 = '       ' + xname
  var color = []
  color = getcolor(idname, xAxisData.length - 1)
  console.log(legendData,'图例名')
  if(typeof legendData[0]=="undefined"){
    legendData=[]
    legendData.push(seriename)
  }
  if (JSON.stringify(color) == '[]') {
    color = ["#2EF7F3", '#ffe8cb', '#ff9000']
    for (var v = 0; v < legendData.length; v++) {
      var serie = {
        name: legendData[v],
        type: "bar",
        barWidth: '30%',
        barGap: "15%",
        boundaryGap:true,
        itemStyle: {
          normal: {
            color: color[v],
            label: {
              show: true,
              textStyle: {
                color: "#fff"
              },
              position: "top",
              formatter: function (p) {
                var index = p.value.toString().length
                if(p.value <= 0){
                  return ""
                }
                // if (index > 9) {
                //   return p.value.toString().substring(0, index - 9) + '亿'
                // } else if (index > 4) {
                //   return p.value.toString().substring(0, index - 4) + '万'
                // }
                  return p.value

              }
            }
          }
        },
        data: metaDate[v],
      }
      serieData.push(serie)
    }
  } else {
    for (var v = 0; v < legendData.length; v++) {
      var serie = {
        name: legendData[v],
        type: "bar",
        barWidth: '25%',
        barGap: "15%",
        itemStyle: {
          normal: {
            color: function (params) {
              let colorList = color;
              return colorList[params.dataIndex];
            },
            label: {
              show: true,
              textStyle: {
                color: "#fff"
              },
              position: "top",
              formatter: function (p) {

                var index = p.value.toString().length
                if(p.value <= 0){
                  return ""
                }
                // if (index > 9) {
                //   return p.value.toString().substring(0, index - 9) + '亿'
                // } else if (index > 4) {
                //   return p.value.toString().substring(0, index - 4) + '万'
                // }else {
                //   return p.value
                // }
              }
            }
          }
        },
        data: metaDate[v],
      }
      serieData.push(serie)
    }
  }


  console.log(legendData, xAxisData, metaDate, serieData, '柱状图绘图参数')
  var colors = ["#036BC8", "#4A95FF", "#5EBEFC", "#2EF7F3", "#FFFFFF"]
  self.xc.setOption({
    title: {text: '', textAlign: 'left', textStyle: {color: "#fff", fontSize: "16*scale", fontWeight: "normal"}},
    color: colors,
    grid: {left: '5%', top: "18%", bottom: "8%", right: "5%", containLabel: true},
    dataZoom: [{
      type: 'inside',
      show: true,
      xAxisIndex: [0],
      left: '50%',
      bottom: -5,
      start: 2,
      end: 90 //初始化滚动条
    }],
    legend: {
      top: 0,
      textStyle: {
        color: '#fff',
      },
      data: legendData,
    },
    tooltip: {
      formatter: function (params) {
        if (params[0].axisValue == '') {
          return ''
        }
        var result = ''
        params.forEach(function (item) {
          result += item.marker + " " + item.seriesName + " : " + item.value + "</br>";
        });
        return params[0].axisValue + tooltype + ' <br/> ' + result
      },
      axisPointer: {type: 'line', lineStyle: {width: 0}},
      trigger: 'axis',
      extraCssText: 'width: auto;height: auto;'
    },
    xAxis: [
      {
        name: xname1,
        type: 'category',
        nameTextStyle: {
          fontSize: 14 * scale,
          color: '#15dce2',
          padding: [40 * scale, 0, 0, -70 * scale],
        },
        axisLine: {show: true, lineStyle: {color: '#04669e', width: 1}},
        axisLabel: {
          interval: 0, textStyle: {color: '#ffffff', fontSize: 14 * scale},
          formatter: function (value, index) {
            if (!namesubif) {
              return value
            }
            //进行客户名称截取换行
            var s = ''
            // 长度超过4个字符进行换行
            if (value.toString().length > 3 && value.toString().length < 8) {
              var s0 = value.toString().substring(0, 4)
              var s1 = value.toString().substring(4, value.toString().length)
              s = s0 + '\n' + s1
              return s
            }
            // 长度超过8个字符进行再次换行
            if (value.toString().length > 7 && value.toString().length < 12) {
              var s0 = value.toString().substring(0, 4)
              var s1 = value.toString().substring(4, 8)
              var s2 = value.toString().substring(8, value.toString().length)
              s = s0 + '\n' + s1 + '\n' + s2
              return s
            }
            // 长度超过12个字符进行再次换行
            if (value.toString().length > 11) {
              var s0 = value.toString().substring(0, 4)
              var s1 = value.toString().substring(4, 8)
              var s2 = value.toString().substring(8, 12)
              var s3 = value.toString().substring(12, value.toString().length)
              s = s0 + '\n' + s1 + '\n' + s2 + '\n' + s3
              return s
            }

            s = value.toString()

            return s;
          }
        },
        axisTick: {show: false},
        data: xAxisData,
      },
    ],
    yAxis: [
      {
        name: yname,
        nameTextStyle: {
          fontSize: 14 * scale,
          padding: [-10 * scale, 35 * scale, 0, 0],
        },
        axisTick: {show: false},
        splitLine: {show: true, lineStyle: {type: 'dashed', color: '#004371'}},
        axisLabel: {interval: 0, textStyle: {color: '#15dce2', fontSize: 14 * scale},
          formatter: function (value) {
            var index = value.toString().length
            if (index > 9) {
              return value.toString().substring(0, index - 9) + '亿'
            } else if (index > 4) {
              return value.toString().substring(0, index - 4) + '万'
            }
            return value
          }},
        axisLine: {show: false, lineStyle: {color: '#15dce2', fontSize: 14 * scale}},
      },
    ],
    series: serieData
  }, true)
  console.log('绘图成功')
  self.xc.on("click", self.eConsole)
}


var parseColor = function (hexStr) {
  return hexStr.length === 4 ? hexStr.substr(1).split('').map(function (s) {
    return 0x11 * parseInt(s, 16);
  }) : [hexStr.substr(1, 2), hexStr.substr(3, 2), hexStr.substr(5, 2)].map(function (s) {
    return parseInt(s, 16);
  })
};

var pad = function (s) {
  return (s.length === 1) ? '0' + s : s;
};

// 获取渐变色值
export function gradientColors(start, end, steps, gamma) {
  var i, j, ms, me, output = [], so = [];
  gamma = gamma || 1;
  var normalize = function (channel) {
    return Math.pow(channel / 255, gamma);
  };
  start = parseColor(start).map(normalize);
  end = parseColor(end).map(normalize);
  for (i = 0; i < steps; i++) {
    ms = i / (steps - 1);
    me = 1 - ms;
    for (j = 0; j < 3; j++) {
      so[j] = pad(Math.round(Math.pow(start[j] * me + end[j] * ms, 1 / gamma) * 255).toString(16));
    }
    output.push('#' + so.join(''));
  }
  return output;
}


var getcolor = function (idname, num) {


  let color = {
    longnotbuygas: ['#ffe8cb', '#ff9000'],
  }
  if (typeof color[idname] != "undefined") {
    return gradientColors(color[idname][0], color[idname][1], num, 2.2)
  }
  return []
}

