// pages/new-renyuanguanli/renyuanguanli.js
import * as echarts from '../../ec-canvas/echarts';
const app = getApp();

//加载施工队数据
const colorArray = [{
  top: '#56c8ec',
  bottom: '#1778eb'
}, {
  top: '#56c8ec',
  bottom: '#1778eb'
},
{
  top: '#56c8ec',
  bottom: '#1778eb'
}, {
  top: '#59c5ec',
  bottom: '#1778eb'
}, {
  top: '#56c8ec',
  bottom: '#1778eb'
}, {
  top: '#56c8ec',
  bottom: '#1778eb'
}, {
  top: '#56c8ec',
  bottom: '#1778eb'
}, {
  top: '#56c8ec',
  bottom: '#1778eb'
}, {
  top: '#56c8ec',
  bottom: '#1778eb'
}
];
function initChart_1(chart_1,data_1,data_name) {
    var option_1 = {
      grid: {
          left: '0',
          right: '10%',
          bottom: '0%',
          top:'10%',
          containLabel: true
      },
      tooltip: {
          trigger: 'axis',
          axisPointer: {
              type: 'shadow'
          },
          formatter: "{b}: {c}"
      },
      xAxis: {
          show: false,                //是否显示x轴
          type: 'value'
      },
      yAxis: {
          type: 'category',
          inverse:true,               //让y轴数据逆向
          axisLabel: {
              show: true,
              textStyle: {
                  color: '#a2d4e6'       //y轴字体颜色
              },
              //定义富文本标签
              rich: {
                  lg: {
                      fontWeight: 'bold',
                      fontSize: 12,       //字体默认12
                      color: '#08C',
                      padding: [0, 5, 0, 0]
                  },
                  title: {
                      color: '#fff',
                      fontWeight: 'lighter',
                      // borderWidth: 1,
                      // borderColor: '#08c'
                      // textareaBorderColor: '#08c',
                  }
              },
              interval: 0,
              formatter: function(value) {
                if (value.length > 8) {
                  return value.substring(0, 8) + "...";
                } else {
                  return value;
                }
              }
          },
          splitLine: {show: false},   //横向的线
          axisTick: {show: false},    //y轴的端点
          axisLine: {show: false},    //y轴的线
          data: data_name
      },
      series: [
          {
              name: '数据内框',
              type: 'bar',
              itemStyle: {
                  normal: {
                      show: true,
                      color: function(params) {
                          let num = colorArray.length;
                          return {
                              type: 'linear',
                              colorStops: [{
                                  offset: 0,
                                  color: colorArray[params.dataIndex % num].bottom
                              }, {
                                  offset: 1,
                                  color: colorArray[params.dataIndex % num].top
                              }, {
                                  offset: 0,
                                  color: colorArray[params.dataIndex % num].bottom
                              }, {
                                  offset: 1,
                                  color: colorArray[params.dataIndex % num].top
                              }, {
                                  offset: 0,
                                  color: colorArray[params.dataIndex % num].bottom
                              }, {
                                  offset: 1,
                                  color: colorArray[params.dataIndex % num].top
                              }, {
                                  offset: 0,
                                  color: colorArray[params.dataIndex % num].bottom
                              }, {
                                  offset: 1,
                                  color: colorArray[params.dataIndex % num].top
                              }, {
                                  offset: 0,
                                  color: colorArray[params.dataIndex % num].bottom
                              }, {
                                  offset: 1,
                                  color: colorArray[params.dataIndex % num].top
                              }]
                          }
                      },
                      barBorderRadius: 20,
                  }
              },
              barWidth: '15',
              data: data_1,
              label: {
                  show: true,
                  position: 'right',
                  color: '#ffc31f',
                  fontSize: 12,
                  offset: [10, 0]
              },
          }
      ]
  };
  chart_1.setOption(option_1);
  return chart_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,data_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: '14%',
      textStyle: {
          rich: {
              name: {
                  fontSize: 14,
                  fontWeight: 'normal',
                  color: '#fff',
                  padding: [10, 20]
              },
              val: {
                  fontSize:25,
                  fontWeight: 'bold',
                  color: '#0ad7ec',
                  padding: [0, 0,0,20]
              }
          }
      }
  }],
    tooltip: {
      trigger: 'item',
    },
    legend: {
        orient: 'vertical',
        top: "center",
        right: "5%",
        icon: 'circle',
        data: data_name,
        textStyle: {
            color: "#fff",
            fontSize: 10
        },
        formatter(name) {
          return `${name}   ${objData_2[name].value}`
        }
    },
    series: [{
          type: 'pie',
          radius: ['55%', '80%'],
          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);
  return chart_2;
}





Page({

  /**
   * 页面的初始数据
   */
  data: {
    active:2, 
    ec_1: {
      lazyLoad: true //动态加载
    }, 
    ec_2: {
      lazyLoad: true //动态加载
    },
    gradientColor: {
      '0%': '#6588ff',
      '100%': '#7e57fe',
    },
    show:false,
    show1: false,
    jzshow:false,
    time:"今日",
    actions1: [{name: '今日',},{name: '本周',},{name: '本月',}],
    list:[],
    //安全教育
    learningRate:'0',
    passRate:'0',
    learnedNum:'0',
    notLearnedNum:'0',
    sumLearnedNum:'0',
    value1:'0',
    value2:'0',
    //安全帽
    hardHatNum:0,
    onlineNum:0,
    notOnlineNum:0,
    value3:0,
    value4:0,
    state:'day',
    //人员定位个数
    userLocation:'0',
    userLocationList:[],
    //页面跳转参数
    loginName:'',
    userName:'',
    projectId:'',
    projectName:'' ,

    initData:{}
  },

  //项目切换 返回值
  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();
  },

  onClickShow() {
    this.setData({ jzshow: true });
  },
  onClickHide() {
    this.setData({ jzshow: false });
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show1: false ,show: false});
  },
  onclick1(){
    this.setData({ show1: true });
  },
  onSelect1(event) {
    this.onClickShow();
    this.setData({
        time: event.detail.name,
    });
    var state = "";
    if(event.detail.name=="今日"){
      state = "day";
    }else if(event.detail.name == "本周"){
      state = "week"
    }else if(event.detail.name == "本月"){
      state = "month";
    }
    this.setData({
      state:state
    })
    //查询工时排行
    this.selectUserAttendance(this.data.projectId,state);
  },

  // 底部导航
  onChange(event) {
    // event.detail 的值为当前选中项的索引
    this.setData({ active: event.detail });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.onClickShow();
    //获取缓存数据
    wx.getStorage({
      key: 'userinfo',
      success:function(res){
        that.setData({
          loginName:res.data.loginName,
          userName:res.data.userName,
          projectId:app.globalData.projectId,
          projectName:app.globalData.projectName,
          initData:{text:app.globalData.projectName,id:app.globalData.projectId}
        })  
      }
    })
    this.oneComponent = this.selectComponent('#mychart-one');
    this.twoComponent = this.selectComponent('#mychart-two');
    this.getUserInfoRanks(app.globalData.projectId);
  },

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

  //初始工种分布
  init_two: function (datas_1,data_name) {
    this.twoComponent.init((canvas, width, height,dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr //解决小程序视图模糊的问题，必写
      });
      initChart_2(chart,datas_1,data_name);
      this.chart = chart;
      return chart;
    });
  },

  //页面初始化加载数据
  getUserInfoRanks:function(even){
    var that = this;

    //获取人员施工队数据
    wx.request({
      url: app.globalData.reqUrl+'/weixin/userinfo/selectUserInfoRanks',
      data:{
        "projectId":even
      },
      method:"GET",
      success:function(ranks){
        that.init_one(ranks.data.ranksNum,ranks.data.ranksName);
      }
    })

    //获取人员工种分布数据
    wx.request({
      url: app.globalData.reqUrl+'/weixin/userinfo/selectUserInfoWork',
      data:{
        "projectId":even
      },
      method:"GET",
      success:function(work){
        if(work.data == ''){
          that.init_two([{"name":'',"value":'0'}])
        }else{
          that.init_two(work.data,work.data);
        }       
      }
    })

    //获取安全教育数据
    wx.request({
      url: app.globalData.reqUrl+'/weixin/userinfo/selectUserInfoEducation',
      data:{
        "projectId":even
      },
      method:"GET",
      success:function(education){
        if(education.data!=''){
          var value1 = (education.data.learnedNum == '0' || education.data.workLabourNum == '0'?'0':(education.data.learnedNum/education.data.workLabourNum*100).toFixed(0));
          that.setData({
            value1:even==3?100:(value1>100.0?100.0:value1),
            value2:even==3?0:((education.data.passRate)>100.0?100.0:education.data.passRate),
            learnedNum:even==3?1009:education.data.learnedNum,
            notLearnedNum:even==3?0:((education.data.workLabourNum-education.data.learnedNum)<0?0:education.data.workLabourNum-education.data.learnedNum),
            sumLearnedNum:even==3?1009:education.data.attendanceNum,
          })
        }        
      }
    })

    //获取安全帽数据
    wx.request({
      url: app.globalData.reqUrl+'/weixin/userinfo/selectOnlineData',
      data:{
        "projectId":even
      },
      method:"GET",
      success:function(res){
        let hardHatNum = 0;
        let onlineNum = 0;
        let notOnlineNum = 0;
        let value3 = 0;
        let value4 = 0;
        if(res.data.code == 0){
            hardHatNum = res.data.data.hardHatNum,
            onlineNum = res.data.data.onlineNum,
            notOnlineNum = res.data.data.notOnlineNum,
            value3 = res.data.data.onlineRate,
            value4 = res.data.data.offlineRate
        }
        that.setData({
          hardHatNum:hardHatNum,
          onlineNum:onlineNum,
          notOnlineNum:notOnlineNum,
          value3:value3,
          value4:value4,
        })
      }
    })

    //工时排行
    that.selectUserAttendance(even,"day");
  },

  //工时排行
  selectUserAttendance:function(projectId,state){
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/userinfo/selectUserAttendance',
      data:{
        "projectId":projectId,
        "state":state
      },
      method:"GET",
      success:function(gsph){
        that.onClickHide();
          that.setData({
            list:gsph.data.listMap,
            userLocation:gsph.data.userLocationCount,
            userLocationList:gsph.data.userLocationList
          })
      }
    })
  },

   //跳转到项目概况页面
   XMGK:function(){
    wx.redirectTo({
      url: '../xiangmugaikuang/xiangmugaikuang'
    })
  },

  //跳转到设备管理
  SBGL:function(){
    wx.redirectTo({
      url: '../shebieguanli-jxsb/shajiangguan',
    })
  },
  //跳转到安全管控
  XMSP:function(){
    wx.redirectTo({
      //url: '../deepExcavation/index'
      url:'../newAddPage/safetyManagement/index'
    }) 
  },

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

  //跳转到地图页面
  skipUserMap:function(even){
    wx.redirectTo({
      url: '../ranyuanguanli-map/map?id='+even.currentTarget.dataset.itemid+"&index="+even.currentTarget.dataset.index+"&userLocationList="+JSON.stringify(this.data.userLocationList)+"&skipState=1"+"&state="+this.data.state
    })
  },

  //跳转到地图列表页面
  goUserMap:function(even){
    wx.redirectTo({
      url: '../ranyuanguanli-map/map?id='+even.currentTarget.dataset.itemid+"&index="+even.currentTarget.dataset.index+"&userLocationList="+JSON.stringify(this.data.userLocationList)+"&skipState=2"+"&state="+this.data.state
    })
  },

   //退出登录
   TCDL:function(){
    wx.clearStorageSync();
    wx.setStorageSync('isReload', "1")
    wx.redirectTo({
      url: '../login/login',
    })
  },

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

})