<template>
  <div>
    <span class="title-1"  >总公司销售趋势</span>
    <div class="text-1">
      <div id="texttotalsellgas" style="text-align: left"></div>
    </div>
    <img class="img-bottom" src="/static/NewManageHome/1.gif" />
  </div>
</template>

<script>
  import * as Util from '../../../Util'
  import * as DataSql from '../../../stores/DataSql'
  import co from 'co'

  export default {
    name: "TextTotalsellgas",
    props: {
      listenheight: String,
    },
    data() {
      return {
        xc: '',
        newyeardata: [],
        oldyeardata: [],
        year: '',
        usertag3: false,
        resdata: [],
        resdataold: [],
        timer:'',
      }
    },
    beforeDestroy() {
      //清除定时器
      clearInterval(this.timer);
    },
    methods: {
      setBar() {

        this.xc = this.$echarts.init(document.getElementById('texttotalsellgas'))
        var scale=this.$parent.$parent.scale
        var xAxisData = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12',''];

        var legendData = ["" + eval(this.year + '-0'), "" + eval(this.year + '-1')];
        var serieData = [];
        var metaDate = [];
        let data0 = []
        let data1 = []
        // for(var i=this.newyeardata.length-1;i>-1;i--){
        //   data0.push(this.newyeardata[i].value)
        //   data1.push(this.oldyeardata[i].value)
        // }
        for (var i = 0; i < 12; i++) {
          var l = false
          for (var j = 0; j < this.newyeardata.length; j++) {
            if (xAxisData[i] == this.newyeardata[j].name) {
              l = true
              data0.push(this.newyeardata[j].value)
              break
            }
          }
          if (!l) {
            data0.push(1)
          }
        }
        for (var i = 0; i < 12; i++) {
          var l = false
          for (var j = 0; j < this.oldyeardata.length; j++) {
            if (xAxisData[i] == this.oldyeardata[j].name) {
              l = true
              data1.push(this.oldyeardata[j].value)
              break
            }
          }
          if (!l) {
            data1.push(0)
          }
        }
        // data0.push(this.newyeardata)
        // data1.push(this.oldyeardata)
        let datascale=[]
        var i=0
        data0.forEach(function (s) {
           if(s!=0&&data1[i]!=0){
             var v=(s/data1[i]).toFixed(3)*100
             datascale.push(v)
           }else {
             datascale.push(0)
           }
          i++
        })

        metaDate.push(data0)
        metaDate.push(data1)
        var colors=['#6fd9d0','#f29961']
        for (var v = 0; v < legendData.length; v++) {
          var serie = {
            name: legendData[v],
            type: 'bar',
            barWidth: '30%',
            itemStyle: {
              barBorderRadius: [16,16,0,0],
              color:colors[v],
            },
            // emphasis:{
            //   itemStyle:{
            //     color:'#ffff2c'
            //   }
            // },
            z:2,
            data: metaDate[v]
          }
          serieData.push(serie)
        }
        var serie1 = {
          name: '占比',
          type: 'line',
          symbol: "circle",
          yAxisIndex: 1,
          symbolSize: 5 ,
          itemStyle: {
            normal: {
              lineStyle: {
                width: 1,
                shadowBlur: 10 ,
                shadowOffsetY: 15 ,
              }
            }
          },
          data: datascale
        }

        serieData.push(serie1)
       legendData.push('占比')
        var colors = ["#f7cb32", "#6fd9d0"];
        var xname = '      月份\n(' + eval(this.year + '-1') + '-' + eval(this.year + '-0') + ')'
        this.xc.setOption({
          title: {
            text: '',
            textAlign: 'left',
            textStyle: {color: "#FFFFFF", fontSize: 12 , fontWeight: "normal"}
          },
          legend: {
            itemGap: 20,
            width: '90%',
            show: true,
            // left: "right",
            right:'4%',
            data: legendData,
            y: '0',
            // padding: [0, 25, 0, 0],
            // padding: [0, 25*scale, 0, 0],
            itemWidth: 20 ,
            itemHeight: 10 ,
            textStyle: {
              padding:[0,10,0,0],
              fontSize: 14 ,
              color: '#95bad7'          // 图例文字颜色
            },
            formatter: function (params) {
            if(params=='占比'){
              return params
            }
              return params + "年"
            }
          },
          color: colors,
          grid: {left: '5%', top: "24%",  right: "5%", width: '88%', height: '70%', containLabel: true},
          tooltip: {
              textStyle:{
                  fontSize:16
              },
            alwaysShowContent:true,
            position: function(point, params, dom, rect, size) {
              //其中point为当前鼠标的位置，size中有两个属性：viewSize和contentSize，分别为外层div和tooltip提示框的大小
              var x = point[0]; //
              var y = point[1];
              var viewWidth = size.viewSize[0];
              var viewHeight = size.viewSize[1];
              var boxWidth = size.contentSize[0];
              var boxHeight = size.contentSize[1];
              var posX = 0; //x坐标位置
              var posY = 0; //y坐标位置
              if (x < boxWidth) { //左边放不开
                posX = 5;
              } else { //左边放的下
                posX = x - boxWidth;
              }

              if (y < boxHeight) { //上边放不开
                posY = 5;
              } else { //上边放得下
                posY = y - boxHeight;
              }
              return [posX, posY];
            },
            formatter: function (params) {
              if (params[0].axisValue == '') {
                return ''
              }
              var result = ''
              params.forEach(function (item) {
                var s = item.value
                // console.log('valueresult---------------------------------')

                var sary = s.toString().split('.')
                // console.log(sary)
                var l = 3
                for (var i = sary[0].toString().length - 1; i > -1; i--) {
                  if (sary[0].toString().length - i == l) {
                    if (i == 0) {
                      continue
                    }
                    sary[0] = sary[0].slice(0, i) + ',' + sary[0].slice(i, sary[0].toString().length)
                    l = l + 4
                  }
                }
                var valueresult = ''
                if (sary.length > 1) {
                  valueresult = sary[0] + '.' + sary[1].substring(0,2)
                } else {
                  valueresult = sary[0]
                }
                 if(item.seriesName=='占比'){
                   result +="<span style='font-weight: normal'>"+ item.marker + " 占&nbsp;&nbsp;&nbsp;&nbsp;比  &nbsp;&nbsp;&nbsp;<span style=\"color:#e1e52a;font-weight: bolder\">" + Math.floor(valueresult * 100) / 100 + "</span></span></br>";
                 }else {
                   result +="<span style=\"text-align: left;font-weight: normal\">"+  item.marker + " " + item.seriesName + "年 &nbsp;&nbsp; <span style=\"color:#e1e52a;font-weight: bolder\">" + valueresult.toString()    + "</span></span></br>";
                 }
              });
              return "<div style='text-align: center;height: 1px;font-weight: normal'>"+params[0].axisValue + '月份</div><br/>' + result
            },
            backgroundColor:'#01396d',
            // borderColor :'rgba(13, 109, 180)',
            borderWidth:0,
            hideDelay:100,
            triggerOn:'mousemove',
            enterable:true,
            padding:10,
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            },
            extraCssText: 'width: auto;height: auto;',
          },
          xAxis: [
            {
              name: '月份',
              type: 'category',
              boundaryGap: true,
              nameTextStyle: {
                fontSize: 12 ,
                color: '#15dce2',
                padding: [38, 0, 0, -20],
              },
              axisLine: {show: true, lineStyle: {color: '#04669e', width: 1}},
              axisLabel: {interval: 0, textStyle: {color: '#95bad7', fontSize: 14 }},
              axisTick: {show: false},
              data: xAxisData,
            },
          ],
          yAxis: [
            {
              name: '金额/元',
              nameTextStyle: {
                color:'#15dce2',
                fontSize: 14 ,
                padding: [0, 35 , 0, 0],
              },
              axisTick: {show: false},
              axisLine: {show: true, lineStyle: {color: '#08738e', fontSize: 14 }},
              splitLine: {show: true, lineStyle: {type: 'dashed', color: '#004371'}},
              axisLabel: {
                textStyle: {color: '#95bad7', fontSize: 14 * scale}, formatter: function (params) {
                  if (params > 9999) {
                    return params / 10000 + "万"
                  }
                  // else if(params>999){
                  //    return params/10000+"万"
                  //  }
                  else
                    return params
                }
              },
            },
            {
              name: '%',
              position: 'right',
              nameTextStyle: {
                color:'#15dce2',
                fontSize: 14 ,
                padding: [0, 0, 0, 0],
              },
              axisTick: {show: false},
              splitLine: {show: false, lineStyle: {type: 'dashed', color: '#004371'}},
              axisLine: {show: true, lineStyle: {color: '#08738e', fontSize: 14 }},
              axisLabel:{show:true,color:'#95bad7'}
            },
          ],
          series: serieData
        })
        let idx = -1;
        var dataLen=data1.length
        var oroptionmapjsonr_charts1=this.xc
       this.timer= setInterval(()=>{
          idx = (idx+ 1) % 12;
          oroptionmapjsonr_charts1.dispatchAction({
            type: 'showTip',
            seriesIndex: 1,
            dataIndex: idx
          });

        }, 3000)
      },
      linesql(year, resultname) {
        // 拼接sql，请求后台
        let sqldata = DataSql.getData(this,  'salegas',{startDate:year}, resultname)
        co(sqldata)
      },
      datapress(data, parm) {
        console.log(data, parm, '销售同比数据')
        var year = ''
        if (parm == 'newyeardata') {
          year = this.year
        }
        if (parm == 'oldyeardata') {
          year = eval(this.year + '-1')
        }
        var month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
        for (var i = 0; i < 12; i++) {
          let item = {}
          var l = 0
          for (var j = 0; j < data.length; j++) {
            if (year + '-' + month[i] == data[j].name) {
              l++
              item.name = month[i]
              item.value = data[j].value
              this[parm].push(item)
            }
          }
          if (l == 0) {
            item.name = month[i]
            item.value = 0
            this[parm].push(item)
          }
        }
      },
      resize() {
        // this.$parent.$parent.changeresize(this.xc)
      }
    },
    watch: {
      'resdataold': {
        deep: true,
        handler(val) {
          this.datapress(this.resdataold, "oldyeardata")
        }
      },
      'resdata': {
        deep: true,
        handler(val) {
          this.datapress(this.resdata, "newyeardata")
        }
      },
      // 监听用户数据并进行绘图
      'newyeardata': {
        deep: true,
        handler(val) {
          if (this.newyeardata.length > 0 && this.oldyeardata.length > 0) {
            this.setBar()
            this.$parent.loaddata++
          }
        }
      },
      // 监听用户数据并进行绘图
      'oldyeardata': {
        deep: true,
        handler(val) {
          if (this.newyeardata.length > 0 && this.oldyeardata.length > 0) {
            this.setBar()
            this.$parent.loaddata++
          }
        },
        immediate: true
      },
      //监听浏览器大小变化
      'listenheight': {
        deep: true,
        handler(val) {
          if (this.listenheight !== '') {
            // this.$parent.$parent.changeresize(this.xc)
          }
        },
      }
    },
    ready() {
      // this.setBar()
      this.year = Util.toStandardDateString()
      this.year = this.year.toString().substring(0, 4)
      this.linesql(this.year, "resdata")
      this.linesql(eval(this.year + '-1'), "resdataold")
    }
  }
</script>

<style scoped>
</style>
