import * as echarts from '../../ec-canvas/echarts';

const app = getApp();


//加载视频监控饼图
  let datas_1 = [];
  let formatNumber_1 = function(num) {
    let reg = /(?=(\B)(\d{3})+$)/g;
    return num.toString().replace(reg, ',');
  }
  function arrayobj_1  (array, key) {
    var resObj = {}
    for (var i = 0; i < array.length; i++) {
        resObj[array[i][key]] = array[i]
    }
    return resObj
  }
  function initChart_1(chart_1,datas_1) {
    //定义参数
    let objData_1 = arrayobj_1(datas_1, 'name');
    let total_1 = datas_1.reduce((a, b) => {
      return a + b.value * 1
  }, 0);
    let title_1 = '接入数';
    var option_1 = {
      color: ["#ffac50", "#ed6942", "#9e40ec", "#1f8efa", "#06c985"],
      title: [{
        text: '{val|' + formatNumber_1(total_1) + '} \n {name|' + title_1 + '} ',
        top: '31%',
        left: '20%',
        textStyle: {
            rich: {
                name: {
                    fontSize: 14,
                    fontWeight: 'normal',
                    color: '#fff',
                    padding: [10, 0]
                },
                val: {
                    fontSize:25,
                    fontWeight: 'bold',
                    color: '#0ad7ec',
                    padding: [0, 10]
                }
            }
        }
    }],
      tooltip: {
        trigger: 'item',
      },
      legend: {
          orient: 'vertical',
          top: "center",
          right: "5%",
          icon: 'circle',
          data: ['一工区'],
          textStyle: {
              color: "#fff",
              fontSize: 10
          },
          formatter(name) {
            return `${name}   ${objData_1[name].value}`
          }
      },
      series: [{
            type: 'pie',
            radius: ['65%', '90%'],
            center: ['30%', '50%'],
            avoidLabelOverlap: false,
            label: {
                show: false,
                position: 'center'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '14'
                }
            },
            labelLine: {
                show: false
            },
            hoverAnimation: false,
            data: datas_1
        }]
    };
    chart_1.setOption(option_1);
  }
 
//机械设备饼图
  let formatNumber_2 = function(num) {
    let reg = /(?=(\B)(\d{3})+$)/g;
    return num.toString().replace(reg, ',');
  }
  function arrayobj_2  (Array, key) {
    var resObj = {}
    for (var i = 0; i < Array.length; i++) {
        resObj[Array[i][key]] = Array[i]
    }
    return resObj
  }
function initChart_2(chart_2,datas_2,datas_name) {
  //定义参数
  let objData_2 = arrayobj_2(datas_2, 'name');
  let total_2 = datas_2.reduce((a, b) => {
    return a + b.value * 1
  }, 0);
  let title_2 = '接入数';

  var option_2 = {
    color: ["#ffac50", "#ed6942", "#9e40ec", "#1f8efa", "#06c985"],
    title: [{
      text: '{val|' + formatNumber_2(total_2) + '} \n {name|' + title_2 + '} ',
      top: '31%',
      left: '20%',
      textStyle: {
          rich: {
              name: {
                  fontSize: 14,
                  fontWeight: 'normal',
                  color: '#fff',
                  padding: [10, 0]
              },
              val: {
                  fontSize:25,
                  fontWeight: 'bold',
                  color: '#0ad7ec',
                  padding: [0, 10]
              }
          }
      }
  }],
    tooltip: {
      trigger: 'item',
    },
    legend: {
        orient: 'vertical',
        top: "center",
        right: "5%",
        icon: 'circle',
        data: datas_name,
        textStyle: {
            color: "#fff",
            fontSize: 10
        },
        formatter(name) {
          return `${name}   ${objData_2[name].value}`
        }
    },
    series: [{
          type: 'pie',
          radius: ['65%', '90%'],
          center: ['30%', '50%'],
          avoidLabelOverlap: false,
          label: {
              show: false,
              position: 'center'
          },
          emphasis: {
              label: {
                  show: true,
                  fontSize: '14'
              }
          },
          labelLine: {
              show: false
          },
          hoverAnimation: false,
          data: datas_2
      }]
  };
  chart_2.setOption(option_2);
}

//劳务管理
function initChart_3(chart_3, xData_3, yData_3) {
  var option_3 = {
    color: ['#5a8df6'],
    tooltip: {
        trigger: 'axis'
    },

    grid: {
        top: '22%',
        left: '3%',
        right: '1%',
        bottom: '0%',
        containLabel: true
    },
    xAxis: [{
        type : 'category',
        boundaryGap : false,
        data : xData_3,
        axisTick: {
            show: false
        },
        axisLine: {
            lineStyle: {
                color: 'rgba(39,51,75,0.8)'
            }
        },
        axisLabel: {
            color: '#8aa3ec',
            rotate: 45,
            textStyle: {
                fontSize: 10
            },
        },
    }],
    yAxis: {
        type : 'value',
        name:"单位:个",
        nameTextStyle: {
            color: "#008fe9",
            fontSize: 11
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: "#008fe9",
                fontSize: 10
            }
        },
        splitLine: {
            show: true,
            lineStyle: {
                color: 'rgba(39,51,75,0.5)'
            }
        },
        axisLine: {
            show: true,
            lineStyle: {
                color: 'rgba(39,51,75,0.8)'
            }
        },
    },
    series: [
        {
            type: 'line',
            data: yData_3,
            symbol: 'circle',
            smooth: true,
            lineStyle: {
                color: '#5a8df6',
                width: 2
            },  
        }
    ]  
  }
  chart_3.setOption(option_3);
  return chart_3;
}


Page({
  /**
   * 页面的初始数据
   */
  data: {
    active:0,  
    show: false,
    activeNames: ["1"],  
    ec_1: {
      lazyLoad: true //动态加载
    },
    ec_2: {
      lazyLoad: true
    },
    ec_3: {
      lazyLoad: true
    },
    //参数——————————————————————————————————————
    //组织架构id
    deptId:'',
    //项目的id
    projectId:'',
    //项目名称参数
    projectNameArgs:'',
    //项目信息
    projectInfo:{},
    projectUnitsList:[],
    //视频接入数
    videoNum:'',
    //正常视频数
    videoOnline:'',
    //机械接入数
    machineryNum:'',
    //正常机械运行数
    machineryOnline:'',
    monthEarlyNum:'0',
    yangchenCount:'0',
    weather:'',
    weatherPic:'',
    temperature:'',
    //加载模板参数
    loadShow:false,
    initData:{},
    todoDb:0,
    approveDb:0,
  },

  //项目切换 返回值
  onProjectSelect(e){
    this.onClickShow();
    let projectId = e.detail.id;
    let projectName = e.detail.text;
    app.globalData.projectId = projectId;
    app.globalData.projectName = projectName;  
    this.setData({
      projectId:projectId,
      projectName:projectName
    })
    this.onLoad();
  },

  showPopup() {
    this.setData({ show: true });
  },

  onClosePopup() {
    this.setData({ show: false });
  },

  // 手风琴
  onChange1(event) {
    this.setData({
      activeName: event.detail,
    });
  },
  onOpen(event){},
  onClose(event){},

  //初始化视频监控饼图数据
  init_one: function (datas_1) {
    this.oneComponent.init((canvas, width, height,dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr //解决小程序视图模糊的问题，必写
      });
      initChart_1(chart, datas_1);
      this.chart = chart;
      return chart;
    });
  },

  //初始化机械设备饼图数据
  init_two: function (datas_2,datas_name) {
    this.twoComponent.init((canvas, width, height,dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr //解决小程序视图模糊的问题，必写
      });
      initChart_2(chart, datas_2,datas_name);
      this.chart = chart;
      return chart;
    });
  },
  
  //初始化劳务管理
  init_three: function (xData_1,yData_1) {
    this.threeComponent.init((canvas, width, height,dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr //解决小程序视图模糊的问题，必写
      });
      initChart_3(chart, xData_1,yData_1);
      this.chart = chart;
      return chart;
    });
  },

  onClickShow() {
    this.setData({ loadShow: false });
  },

  onClickHide() {
    this.setData({ loadShow: false });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onClickShow();
    this.setData({
      activeName: ["1"],
    });
    var that = this;
      //获取缓存数据
      wx.getStorage({
        key: 'userinfo',
        success:function(res){
          that.setData({
            loginName:res.data.loginName,
            nickName:res.data.nickName,
            deptName:res.data.deptName,
            roleName:res.data.roleName.split(',')[0],
            projectId:app.globalData.projectId,
            projectNameArgs:app.globalData.projectName,
            initData:{text:app.globalData.projectName,id:app.globalData.projectId}
          })
          that.awaitTask(res.data.minRoleId,res.data.deptId,res.data.loginName,res.data.userId);
        }
      })
        //根据id获取组件
        this.oneComponent = this.selectComponent('#mychart-one');
        this.twoComponent = this.selectComponent('#mychart-two');
        this.threeComponent = this.selectComponent('#mychart-three');
        this.fourComponent = this.selectComponent('#mychart-four');
        //项目基本信息
        this.getProjectBaseInfo(app.globalData.projectId);
        //项目管理信息
        this.getProjectUnitList(app.globalData.projectId);
        //视频数量
        //this.getProjectVideoAll(app.globalData.projectId);
        //机械的数据
        //this.getMachineryNum(app.globalData.projectId);
        //机械列表
        //this.getMachineryList(app.globalData.projectId);
        //视频的数据
        //this.getVideoList(app.globalData.projectId);
  },

   // 底部导航
   onChange(event) {
    // event.detail 的值为当前选中项的索引
    this.setData({ active: event.detail });
  },

  //获取项目的基本数据
  getProjectBaseInfo:function(even) {
    wx.request({
      url: app.globalData.reqUrl+'/wechat/project/getProjectFoundation',
      method:'GET',
      data:{
        id:even
      },
      success:resData=> {
          this.onClickHide()
          this.setData({
            projectInfo:resData.data
          })
           //环境监测
            //this.selectEnvirData(even);
            //加载天气信息
            //this.getWeatherData(resData.data.longitude,resData.data.latitude)
      }
    })
  },

  //加载天气数据
  getWeatherData:function(even1,even2){
        var that = this;
        wx.request({
        url: app.globalData.reqUrl+'/weixin/applets/selectWeather',
        method:"GET",
        data:{
            lng:even1,
            lat:even2,
        },
        success:function(weatherRes){
            that.setData({
                weather:weatherRes.data.weather,
                weatherPic:weatherRes.data.weatherPic,
                temperature:weatherRes.data.temperature        
            })
        }
        })
  } ,

  //获取项目的管理信息
  getProjectUnitList:function(projectId) {
      var that = this;
      wx.request({
        url: app.globalData.reqUrl+'/wechat/project/getProjectUnitList',
        method:'GET',
        data:{
            projectId:projectId
        },
        success:resData=> {
            that.onClickHide()
            that.setData ({
                projectUnitsList:resData.data           
            })
        }
      })
  },

  // 获取项目下的视频数
  getProjectVideoAll:function(even) {
    wx.request({
      url: app.globalData.reqUrl+'/weixin/video/getProjectVideoNum',
      method: 'get',
      data: {
          projectName:even
      },
      success: resData => {
          this.setData({
            videoNum:resData.data.videoAll,
            videoOnline:resData.data.videoOnline
          })
      }
    })
  },

  // 获取机械的数据
  getMachineryNum:function(event) {
      wx.request({
        url: app.globalData.reqUrl+'/mkl/machinery/getMachineryDataWest',
        data:{
          "projectId":event
        },
        method:'get',
        success:resData=> {
            this.setData({
                machineryNum:resData.data.allNum,
                machineryOnline:resData.data.onlineNum
            })
        }
      })
  },

  //机械的列表,名称
  getMachineryList:function(event) {
    var that = this;
      wx.request({
        url: app.globalData.reqUrl+'/mkl/machinery/getMachineryListWest',
        data:{
          "projectId":event
        },
        method:'GET',
        success:resData=> {
          if(resData.data==''){
              that.init_two( [{"value":"0","name":""}]);
          }else{
            that.init_two(resData.data);
          }           
        }
      })
  },

  //获取视频的列表，名称
  getVideoList:function(even) {
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/video/getProjectVideoListEc',
      method:'GET',
      data:{
        projectName:even
      },
      success:resData=> {
        that.onClickHide();
        if(resData.data.length>0){
          that.init_one(resData.data);
        } 
      }
    })
  },

  //查询劳务人员出勤数据
  selectEnvirData:function(even){
      var that = this;
      wx.request({
        url: app.globalData.reqUrl+'/weixin/userinfo/selectAttendanceNum',
        method:"GET",
        data:{
            projectId:even,
        },
        success:function(hjyj){
            that.setData({
                monthEarlyNum:hjyj.data.userCount,
                yangchenCount:hjyj.data.userCount
            })  
        }
      })

       //查询出最近一周劳务人员考勤人数
       wx.request({
        url: app.globalData.reqUrl+'/weixin/userinfo/selectLabourDayByProjectId',
        method:"GET",
        data:{
            projectId:even
        },
        success:function(sspm){
          var createTime = [];
          var userCount = [];
          for(var i=0;i<sspm.data.length;i++){
            createTime.push(sspm.data[i].createTime);
            userCount.push(sspm.data[i].userCount);
          }
          that.init_three(createTime,userCount);
        }
      })
  },

  /**
   * 拨打电话
   * @param {*} event 
   */
  calling:function(event){
    let callPhone=event.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: callPhone, 
      success:function(){
        console.log("拨打电话成功！")
      },
      fail:function(){
        console.log("拨打电话失败！")
      }
    })
  },

  //跳转到安全管控
  XMSP:function(){
      wx.redirectTo({
       url:'../safety_manage/index'
      }) 
  },
  
   //跳转到质量管理
   ZLGL:function(){
      wx.redirectTo({
       url:'../quality_manage/index'
      }) 
  },
   //跳转到进度管理
   JDGL2:function(){
    app.toast("敬请期待！");
    //  wx.redirectTo({
    //   //url: '../deepExcavation/index'
    //    url:'../../pageage/Progress-management/index'
    //  }) 
  },

  //跳转到更多功能
  GDGN:function(){
    wx.redirectTo({
    url: '../gengduogongneng/gengduogongneng'
    })                                                                
  },

    //退出登录
  TCDL:function(){
    wx.clearStorageSync();
    wx.setStorageSync('isReload', "1")
      wx.redirectTo({
        url: '../login/login',
      })
    },
  
  //修改密码
  XGMM:function(){
    wx.setStorageSync('nav-menu', "gd");
    wx.redirectTo({
      url: '../updatePassword/updatePassword'
      }) 
  },
    //返回到地图页面
    GOMAP:function(){
        wx.redirectTo({
          url: '../map/map',
        })
    },  

    //返回到工程列表页面
    goGCLB:function(){
      wx.redirectTo({
        url: '../gongchengliebiao/gongchengliebiao'
      })
    },

  //查询当前登录人的代办任务
  awaitTask(minRoleId,deptId,loginName,userId) {
    let param = {
      //"businessKey":this.data.projectId,
      "nowRole":minRoleId,
      "nowDept":deptId,
      "nowUserName":loginName,
      "nowUser":userId,
      "activeName":"await"
    }
    var that = this;
    wx.request({
      url: app.globalData.reqUrl + '/wechat/flowTask/myAwaitFlowTaskListCount',
      data:param,
      method: "post",
      success: function (res) {
        res = res.data;
        if(res.code=="200"){
          that.setData({
            todoDb:res.data.todo,
            approveDb:res.data.approve
          }) 
          console.log("db"+that.data.approveDb);
        }
      }
    })
  },
})

