<template>
  <div>
    <div class="label t1" @click="drillclick">{{title}}</div>
    <div style="height: 48%;width: 100%;padding: 2%;">
      <div id="usernum" class="d0"></div>
      <!--<div class="d1">-->
      <!--&lt;!&ndash;<div class="flex" style="height: 30%; text-align: center; padding-top: 5%;" v-for="item in model">&ndash;&gt;-->
      <!--&lt;!&ndash;<span class="f24">{{item.num}}</span>&ndash;&gt;-->
      <!--&lt;!&ndash;<span class="f12">{{item.name}}</span>&ndash;&gt;-->
      <!--&lt;!&ndash;</div>&ndash;&gt;-->
      <!--</div>-->
    </div>
    <div style="height: 51%; width: 100%;padding: 2%;">
      <div id="userdatatwo"></div>
    </div>
  </div>
</template>

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

  export default {
    name: "user-number",
    props: {
      increaseuser: Number,
      listenheight: String,
      f_filiale: String,
    },
    data() {
      return {
        title: '用户数量',
        usernum: [],
        increaseuser: 0,
        totaluser: [
          {name: '现有总用户', value: 0},
          {name: '开发用户数', value: 0},
          {name: '潜在用户数', value: 0},
        ],
        totaluserstring: [
          {name: '现有总用户', value: 0},
          {name: '开发用户数', value: 0},
          {name: '潜在用户数', value: 0},
        ],
        barscale: [],
        usernumstring: [],
        usertag0: false,
        usertag5: false,
        resdata: [],
        resdataapply: [],
        timer:''
      }
    },
    beforeDestroy() {
      //清除定时器
      clearInterval(this.timer);
    },
    methods: {
      //绘制echarts图
      setBar(id) {
        this.xc = this.$echarts.init(document.getElementById(id))
        this.BarScale()
        DataSql.dataunitarray(this, 'totaluser', 'totaluserstring')
        var echartsData = this.totaluserstring
        var scale=this.$parent.$parent.$parent.scale
        var warnImg = "../../../../static/ManageHomePic/椭圆4.png"
        var grade = ['图片', '图片', '图片']
        let cost = []
        var l = this.barscale.length
        for (var i = 0; i < l; i++) {
          cost[l - 1 - i] = this.barscale[i]
        }
        var data = {
          grade: grade,
          visits: this.totaluser,
          totalCost: [1, 1, 1],
          cost: cost,
        }
        var rich = {
          yellow: {
            align: 'center',
            color: '#f3c832',
            padding: [6, 0,0,0],
            fontSize: 16 * scale
          },
          white: {
            align: 'center',
            color: '#fff',
            fontSize: 12 * scale
          },
        }
        this.xc.setOption({
          title: {
            text: '',
            x: 'left',
            y: 'top',
            textStyle: {
              color: '#fff',
              fontSize: 18*scale
            }
          },
          grid: {left: '16%', top: "12%", bottom: "5%", right: "30%", containLabel: true},
          xAxis: {
            show: false,
          },
          yAxis: {
            type: 'category',
            axisLabel: {
              formatter: function (value) {
                //判断是否要显示预警
                return '{warnValue|}'
              },
              rich: {
                //这里的rich，下面有解释
                warnValue: {
                  //这里的warnValue对应上面的标签名
                  height: 20*scale,
                  align: 'center',
                  backgroundColor: {
                    image: warnImg  	//这个warnImg是上面定义的图片var warnImg = "img/warn.png";
                  }
                }
              },
              margin: 10,
              show: true,
              color: '#15dce2',
              fontSize: 12*scale
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            data: data.grade
          },
          series: [{
            type: 'bar',
            barGap: '-100%',
            label: {
              normal: {
                show: true,
                position: 'right',
                // lineHeight:25,
                formatter: function (param) {

                  var l = data.visits.length
                  return '{yellow|' + echartsData[l - 1 - param.dataIndex]['value'] + '}\n{white|' + echartsData[l - 1 - param.dataIndex]['name'] + '}';
                },
                rich: rich,
              }
            },
            barWidth: '25%',
            itemStyle: {
              normal: {
                borderColor: 'rgba(1,207,242,0.05)',
                borderWidth: 2,
                barBorderRadius: 15*scale,
                color: '#003d4c',
              },
            },
            z: 1,
            data: data.totalCost,
          }, {
            type: 'bar',
            barGap: '-99%',
            barWidth: '25%',
            itemStyle: {
              normal: {
                barBorderRadius: 12*scale,
                color: {
                  type: 'linear',
                  x: 0,
                  x1: 1,
                  colorStops: [{
                    offset: 0,
                    color: '#6fd9d0'
                  }, {
                    offset: 1,
                    color: '#6fd9d0'
                  }]
                }
              },
            },
            max: 1,
            labelLine: {
              show: true,
            },
            z: 2,
            data: data.cost,
          }]
        }, true)
      },
      //绘制用户类型分布饼图
      setUserType() {
        this.xc = this.$echarts.init(document.getElementById('userdatatwo'))
        var scale = 1
        DataSql.dataunitarray(this, 'usernum', 'usernumstring')
        var echartData = this.usernum
        var echartData1 = this.usernumstring
        var legendname = []
        this.usernum.forEach(function (s) {
          legendname.push(s.name)
        })
        var rich = {
          blue: {
            color: '#15dce2',
            fontSize: 12 * scale,
            align: 'center',
            padding: [10, 0]
          }
        }
        var scale = 1
        var total = 0; //用户总和
        var result = ''
        echartData.forEach(function (value) {
          total += value.value;
        });
        var index = total.toString().length
        if (index > 4) {
          var t = total.toString().substring(0, index - 4)
          var s = total.toString().substring(index - 4, index - 3)
          var l = total.toString().substring(index - 3, index - 2)
          if (l > 4) {
            s = eval(s + '+1')
          }
          if (s > 9) {
            s = 0
            t = eval(t + '+1')
          }
          result = t + '.' + s + '万'
        } else {
          result = total
        }
        this.xc.setOption({
          title: [
            {
              text: '总用户数',
              x: 45*scale+'%',
              y: '24%',
              textStyle: {
                color: '#ffffff',
                fontSize: 10 * scale,
              }
            },
            {
              text: result,
              x: 43*scale+'%',
              y: '28%',
              padding: [15*scale, 20*scale],
              textStyle: {
                color: '#00e2ea',
                fontSize: 10 * scale,

              }
            }],
          tooltip: {
            show: true,
            alwaysShowContent:true,
            backgroundColor:'rgba(2, 59, 63, 0.45)',
            // borderColor :'rgba(13, 109, 180)',
            borderWidth:0,
            hideDelay:100,
            triggerOn:'mousemove',
              padding:10*scale,
              textStyle:{
                  fontSize:16*scale
              },
            formatter: function (params) {
              return  params.marker + " " + params.name + "  <span style=\"color:#e1e52a;font-weight: bolder\">&nbsp;&nbsp;" + params.value + "</span>"
            },
            enterable: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];
            },
            extraCssText:'width: auto;height:auto;',
          },
          legend: {
            orient: 'horizontal',
            icon: 'circle',
            x: 'center',
            y: '80%',
            itemGap: 20,
            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%', '30%'],
            //   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: ['40%', '60%'],
              center: ['50%', '34%'],
              hoverAnimation: false,
              color: ['#6fd9d0', '#ede61f', '#6d9bdc'],
              minAngle: 15,//最小角度
              startAngle: 60, //起始角度
              label: {
                show:false
                // normal: {
                //   borderWidth: 20 * scale,
                //   borderRadius: 4,
                //   formatter: function (params, ticket, callback) {
                //     for (var i = 0; i < echartData1.length; i++) {
                //       if (echartData1[i].name == params.name) {
                //         return '{blue|' + params.name + '}{blue|' + echartData1[i].value + '}\n';
                //       }
                //     }
                //   },
                //   padding: [0, -102 * scale],
                //   rich: rich,
                // }
              },

              labelLine: {
                show:false
                // normal: {
                //   length: 15 * scale,
                //   length2: 100 * 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);
                //       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%', '30%'],
            //   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)
        let idx = 0;
        var dataLen=echartData.length
        var oroptionmapjsonr_charts=this.xc
        this.timer=setInterval(()=>{
          // 取消之前选中的图形
          oroptionmapjsonr_charts.dispatchAction({
            type: 'pieUnSelect',
            seriesIndex: 0,
            dataIndex: idx,
          });

          idx = (idx+ 1) % dataLen;
          //console.log(app.currentIndex);
          // 选中当前图形
          oroptionmapjsonr_charts.dispatchAction({
            type: 'pieSelect',
            seriesIndex: 0,
            dataIndex: idx
          });
          oroptionmapjsonr_charts.dispatchAction({
            type: 'showTip',
            seriesIndex: 0,
            dataIndex: idx
          });
        }, 3000)
      },
      //请求后台数据
      searchdata() {
        var self = this
        let sqldata = DataSql.getData(this, 'usernum',{f_filiale:this.$parent.$parent.f_filiale}, "resdata")
        co(sqldata)
        let sqldataone = DataSql.getData(this,'userapply',{f_filiale:this.$parent.$parent.f_filiale}, 'resdataapply')
        co(sqldataone)
      },
      // 用户数据比例化
      BarScale() {
        var s = this.totaluser[0]
        for (var i = 1; i < this.totaluser.length; i++) {
          if (s.value < this.totaluser[i].value) {
            s = this.totaluser[i]
          }
        }
        var l = s.value * 1.3
        this.barscale = []
        for (var i = 0; i < this.totaluser.length; i++) {
          if (l == 0) {
            this.barscale.push(0)
          }
          this.barscale.push(this.totaluser[i].value / l)
        }
      },
      // 三级页面点击入口
      drillclick() {
        var initdatatr = {
          startDate: eval(Util.toStandardDateString().toString().substring(0, 4) + '-4') + '-01-01 00:00:00',
          endDate: Util.toStandardDateString() + ' 00:00:00',
          param: '',
          param1: '',
          listparam: '',
        }
        this.$emit('drill', 'usernum', 'usernumbers', this.title, initdatatr)
        this.$emit('drilldata', this.totaluser)
      },
    },
    watch: {
      'resdata': {
        deep: true,
        handler(val) {
          this.usernum = []
          let result = {}
          result.name = '民用'
          result.value = this.resdata[0]['民用']
          this.usernum.push(result)
          let result1 = {}
          result1.name = '非民用'
          result1.value = this.resdata[0]['非民用']
          this.usernum.push(result1)
          let result2 = {}
          result2.name = '民用锅炉'
          result2.value = this.resdata[0]['民用锅炉']
          this.usernum.push(result2)
        }
      },
      // 监听用户数据并进行绘图
      'usernum': {
        deep: true,
        handler(val) {
          var value = this.usernum[0].value + this.usernum[1].value + this.usernum[2].value
          this.totaluser[0].value = value
          this.setUserType()
          this.$parent.loaddata++
        }
      },
      //监听用户增长模块的数据,更新计算潜在用户数
      // 'increaseuser': {
      //   deep: true,
      //   handler(val) {
      //     console.log(this.increaseuser, '潜在用户数据')
      //     this.totaluser[2].value = this.increaseuser
      //   },
      //   immediate: true
      // },
      // 监听用户数据并进行绘图
      'totaluser': {
        deep: true,
        handler(val) {
          if (this.totaluser[0].value > 0 && this.totaluser[1].value > 0 && this.totaluser[2].value > 0) {
            this.setBar('usernum')
          }
          this.$parent.loaddata++
        },
      },
      //监听浏览器大小变化
      'listenheight': {
        deep: true,
        handler(val) {
          if (this.listenheight !== '') {
            // this.$parent.$parent.changeresize(this.xc)
          }
        },
      },
      'resdataapply': {
        deep: true,
        handler(val) {
          if (this.resdataapply[0].totalnum > 0) {
            this.totaluser[1].value = this.resdataapply[0].f_applycount?this.resdataapply[0].f_applycount:0
            this.totaluser[2].value = this.resdataapply[0].f_installnum?this.resdataapply[0].f_installnum:0
          }

          console.log(this.resdataapply, '报建数据')

        }
      },
      'f_filiale'(){
        this.searchdata()
      }
    },
    ready() {
      this.searchdata()
    }
  }
</script>

<style scoped>
  .label {
    margin-left: 1%;
    font-size: 1.85rem;
    color: #fff;
    width: 100%;
    height: 9%;
  }

  .d1 {
    margin-top: 10%;
    width: 30%;
    height: 80%;
    float: right;
  }

  .d0 {
    padding-left: 9%;
    width: 100%;
    height: 100%;
    float: left;
  }

  .f24 {
    font-size: 0.85em;
    color: #f3c832;
  }

  .f12 {
    font-size: 0.85em;
    color: #ffffff;
  }
  .t1{
    color: #4bf2ff;
  }
</style>
