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

//加载最近一周运行时长
function initChart_1(chart_1, datas_1, datas_2) {
  var option_1={
    grid: {
        top: "20%",
        bottom: "18%",
        left:"0%",
        right:"0%"
    },
    tooltip: {
        trigger: "axis",
        axisPointer: {
            type: "shadow",
            label: {
                show: true
            }
        }
    },
    xAxis: {
        data: datas_2,
        axisLine: {
            show: false //隐藏X轴轴线
        },
        axisTick: {
            show: false //隐藏X轴刻度
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: "#ebf8ac", //X轴文字颜色
                fontSize:'10'
            }
        }
    },
    yAxis: [{
        type: "value",
        nameTextStyle: {
            color: "#ebf8ac"
        },
        splitLine: {
            show: false
        },
        axisTick: {
            show: false
        },
        axisLine: {
            show: false
        },
    },
        {
            type: "value",
            nameTextStyle: {
                color: "#ebf8ac"
            },
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisLabel: {
                show: true,

            }
        },

    ],
    series: [{
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        smooth: true, //平滑曲线显示
        showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize:7, //标记的大小
        itemStyle: {
            //折线拐点标志的样式
            color: "#fd9820"
        },
        lineStyle: {
            color: "#fd9820"
        },
        areaStyle:{
            color: "rgba(5,140,255, 0.2)"
        },
        label: {
            show: true,
            position: 'top',
            textStyle: {
                color: '#ffffff',
                fontSize:'10'
            }
        },
        data: datas_1
    },
        {

            type: "bar",
            barWidth: 12,
            itemStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: "#51d7ff"
                    },
                        {
                            offset: 1,
                            color: "#3637a3"
                        }
                    ])
                }
            },
            data:datas_1
        }
    ]
};
  chart_1.setOption(option_1);
  return chart_1;
}

//一周油耗
function initChart_2(chart_2, datas_1, datas_2) {
  var option_2={
    grid: {
        top: "20%",
        bottom: "18%",
        left:"0%",
        right:"0%"
    },
    tooltip: {
        trigger: "axis",
        axisPointer: {
            type: "shadow",
            label: {
                show: true
            }
        }
    },
    xAxis: {
        data:datas_2,
        axisLine: {
            show: false //隐藏X轴轴线
        },
        axisTick: {
            show: false //隐藏X轴刻度
        },
        axisLabel: {
            show: true,
            textStyle: {
                color: "#ebf8ac", //X轴文字颜色
                fontSize:'10'
            }
        }
    },
    yAxis: [{
        type: "value",
        nameTextStyle: {
            color: "#ebf8ac"
        },
        splitLine: {
            show: false
        },
        axisTick: {
            show: false
        },
        axisLine: {
            show: false
        },
    },
        {
            type: "value",
            nameTextStyle: {
                color: "#ebf8ac"
            },
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
            axisLabel: {
                show: true,

            }
        },

    ],
    series: [{
        type: "line",
        yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
        smooth: true, //平滑曲线显示
        showAllSymbol: true, //显示所有图形。
        symbol: "circle", //标记的图形为实心圆
        symbolSize:7, //标记的大小
        itemStyle: {
            //折线拐点标志的样式
            color: "#fd9820"
        },
        lineStyle: {
            color: "#fd9820"
        },
        areaStyle:{
            color: "rgba(5,140,255, 0.2)"
        },
        label: {
            show: true,
            position: 'top',
            textStyle: {
                color: '#ffffff',
                fontSize:'10'
            }
        },
        data: datas_1
    },
        {

            type: "bar",
            barWidth: 12,
            itemStyle: {
                normal: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: "#51d7ff"
                    },
                        {
                            offset: 1,
                            color: "#3637a3"
                        }
                    ])
                }
            },
            data:datas_1
        }
    ]
};
  chart_2.setOption(option_2);
  return chart_2;
}


Page({
  /**
   * 页面的初始数据
   */
  data: {
    ec_1: {
      lazyLoad: true //动态加载
    },
    ec_2: {
      lazyLoad: true //动态加载
    },
    option1: [],
    value1: '',
    currentId: '',   //传值与list id 相同
    showPopup: false,
    show:false,
    bottom: "500rpx",
    showUp: false,
    list:[ {
      id:1,
      machine_key:"",
      name:"挖掘机12312",
      model:"z51110",
      state:"运行",
      class:"machinery_state_yx",
      battery:"50",
      workingHours:"8小时55分钟",
      oilCapacity:"358L",
      proportion:"80%",  
      projectName: "西安地铁8号西安大白杨站智慧工地111", 
    }],
    lists:[],
    height:"",
    longitude:'',
    latitude:'',
    markers: [],
    index:'',
    machineryTotalList:[],
    projectId:'',
    projectName:'',
    machineKey:"",
    //机械初始经纬度信息
    machineLongitude:'',
    machineLatitude:'',
    machineMarkers:[],
    //刷新字段
    initialMachineKey:"",
    timeLevenStatus:0,
  },

  //页面加载
  onClickShow() {
    this.setData({ show: true });
  },
  onClickHide() {
    this.setData({ show: false });
  },
  upward() {
    this.setData({ showUp: true });
    this.setData({ bottom:  "500rpx" });
    this.selectMachineryRun(this.data.projectId,this.data.initialMachineKey,this.data.machineryTotalList);
  },
  downward() {
    this.setData({ showUp: false });
    this.setData({ bottom:  "50rpx" });
  },
  showPopup() {
    this.setData({ showPopup: true });
  },
  onClose() {
    this.setData({ showPopup: false });
    this.setData({ showType: false });
  },
  selectList(event){
    this.onClickShow();
    //加载数据
    this.selectMachineryRun(this.data.projectId,event.currentTarget.dataset.machinekey,this.data.machineryTotalList);
    let timeLevenStatus = this.data.timeLevenStatus;
    if(timeLevenStatus == 0){
      this.selectMachineryWeekTime(event.currentTarget.dataset.machinekey);
    }else{
      this.selectMachineryWeekTankLeven(event.currentTarget.dataset.machinekey);
    }
    this.setData({ 
      showPopup: false,
      index:event.currentTarget.dataset.index,
      showUp: true ,
      currentId:event.currentTarget.dataset.machinekey
     });
  },
  optionChange(event){
    this.onClickShow();
    var category = "";
    var option1 = this.data.option1;
    for(var i = 0;i<option1.length;i++){
      if(option1[i].value == event.detail){
        category = option1[i].text
      }
    }
    this.selectMachineryList(this.data.projectId,category);
  },

  //页面初始化
  onLoad: function (option) {
    this.onClickShow();
    var that = this
    //调用wx.getSystemInfo接口，然后动态绑定组件高度
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: res.windowHeight
        })
      }
    }),
    //获取缓存中数据
    wx.getStorage({
      key: 'userinfo',
      success:function(res){
        that.setData({
          userInfo:res.data,
          index:option.index,
          projectId:app.globalData.projectId,
          projectName:app.globalData.projectName,
          initialMachineKey:option.machineKey,
          currentId:option.machineKey
        })
      }
    })
    this.oneComponent = this.selectComponent('#mychart-one');
    this.twoComponent = this.selectComponent('#mychart-two');
    if(option.skipState =="1"){
      this.setData({ showUp: true })
      //页面初始化加载单个机械设备信息
      this.selectMachineryRun(app.globalData.projectId,option.machineKey,JSON.parse(option.machineryTotalList));
    }else{
      this.setData({ showPopup:true })
    }   
    
    //记载最近一周机械运行数据
    this.selectMachineryWeekTime(option.machineKey);
    //查询出机械列表
    this.selectMachineryList(app.globalData.projectId,option.type,option.skipState);
    //查询出机械类型
    this.selectMachineCategory(app.globalData.projectId);

}, 

  //加载运行轨迹数据
  init_one: function (datas_1,datas_2) {
    this.oneComponent.init((canvas, width, height,dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr //解决小程序视图模糊的问题，必写
      });
      initChart_1(chart,datas_1,datas_2);
      this.chart = chart;
      return chart;
    });
  },

  //加载油耗数据
  init_two: function (datas_1,datas_2) {
    this.twoComponent.init((canvas, width, height,dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr //解决小程序视图模糊的问题，必写
      });
      initChart_2(chart,datas_1,datas_2);
      this.chart = chart;
      return chart;
    });
  },

  //查询出单个机械设备的基础数据
  selectMachineryRun:function(event,event1,event2){
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/machicnery/selectMachineryRun',
      data:{
        "projectId":event,
        "machineKey":event1
      },
      method:"GET",
      success:function(res){
        if(res.data.partMachineryList.length >0){
          var markers = [];
          for(var i=0;i<event2.length;i++){              
              if(event2[i].machine_key ==event1){
                var marker = {id:event2[i],longitude:res.data.partMachineryList[0].longitude,latitude:res.data.partMachineryList[0].latitude,machineKey:res.data.partMachineryList[0].machine_key,iconPath:"http://fileimg.makalu.cc/10127f663a454adea855fc852e715dd5.png",width: 40, height: 40};
                markers.push(marker);  
              }else{
                var marker = {id:event2[i],longitude:event2[i].longitude,latitude:event2[i].latitude,machineKey:event2[i].machine_key
                }
                markers.push(marker);  
              }
          }
          that.setData({
            list:res.data.partMachineryList,
            markers:markers,
            longitude:res.data.partMachineryList[0].longitude,
            latitude:res.data.partMachineryList[0].latitude,
            machineLongitude:res.data.partMachineryList[0].longitude,
            machineLatitude:res.data.partMachineryList[0].latitude,
            machineMarkers:markers,
          })
        }
        that.onClickHide();
      }
    })
  },

  //查询出机械列表
  selectMachineryList:function(event,category,skipState){
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/machicnery/selectMachineryRun',
      data:{
        "projectId":event,
        "category":(category=="全部")?"":category,
      },
      method:"GET",
      success:function(res){
        var event2  = res.data.totalMachineryList;
        if(event2.length>0){
          var markers = [];         
          for(var i=0;i<event2.length;i++){                    
              var marker = {id:event2[i],longitude:event2[i].longitude,latitude:event2[i].latitude,machineKey:event2[i].machine_key }          
              markers.push(marker);               
          }
          if(skipState == "1"){
            that.setData({
              lists:event2,
              machineryTotalList:event2,
            })
          }else{
            that.setData({
              lists:event2,
              markers:markers,
              longitude:event2[0].longitude,
              latitude:event2[0].latitude,
              machineryTotalList:event2,
            })
          }         
        }else{
          that.setData({
            lists:[],
            markers:[],
            longitude:'',
            latitude:'',
          })
        }
        that.onClickHide();
      }
    })
  },

   //查询出机械类型
   selectMachineCategory:function(event){
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/machicnery/selectMachineCategory',
      data:{
        "projectId":event,
        "type":"map"
      },
      method:"GET",
      success:function(res){
        that.onClickHide();
        that.setData({
          option1:res.data
        })   
      }
    })
  },

  //查询出最近一周运行数据
  selectMachineryWeekTime:function(event){
    var that = this;
    wx.request({
      url: app.globalData.reqUrl+'/weixin/machicnery/selectMachineryWeekTime',
      data:{
        "machineKey":event
      },
      method:"GET",
      success:function(res){
        that.onClickHide();
        that.init_one(res.data.valueList,res.data.timeList);
      }
    })
  },

  //查询出最近一周油耗
  selectMachineryWeekTankLeven:function(event){
      var that = this;
      wx.request({
        url: app.globalData.reqUrl+'/weixin/machicnery/selectMachineryWeekTankLeven',
        data:{
          "machineKey":event
        },
        method:"GET",
        success:function(res){
          that.onClickHide();
          that.init_two(res.data.valueList,res.data.timeList);
        }
      })
  },

  ///向左切换
  changeLeftData:function(event){
    this.onClickShow();
    var machineryTotalList = this.data.machineryTotalList;
    var projectId = this.data.projectId;
    if(this.data.index == "0"){
      app.toast("已经到头了，无法进行点击");
      this.onClickHide();
    }else{
      this.selectMachineryRun(projectId,machineryTotalList[this.data.index-1].machine_key,machineryTotalList);
      let timeLevenStatus = this.data.timeLevenStatus;
      if(timeLevenStatus == 0){
        this.selectMachineryWeekTime(machineryTotalList[this.data.index-1].machine_key);
      }else{
        this.selectMachineryWeekTankLeven(machineryTotalList[this.data.index-1].machine_key);
      }
      this.setData({
        machineKey:machineryTotalList[this.data.index-1].machine_key,
        index:this.data.index-1,
        currentId:machineryTotalList[this.data.index-1].machine_key,
      })
    }
  },

  //向右切换
  changeRightData:function(event){
    this.onClickShow();
    var machineryTotalList = this.data.machineryTotalList;
    var projectId = this.data.projectId;
    if(this.data.index == (machineryTotalList.length-1)){
      app.toast("已经到头了，无法进行点击");
      this.onClickHide();
    }else{
      this.selectMachineryRun(projectId,machineryTotalList[(this.data.index-1+2)].machine_key,machineryTotalList);
      let timeLevenStatus = this.data.timeLevenStatus;
      if(timeLevenStatus == 0){
        this.selectMachineryWeekTime(machineryTotalList[(this.data.index-1+2)].machine_key);
      }else{
        this.selectMachineryWeekTankLeven(machineryTotalList[(this.data.index-1+2)].machine_key);
      }
      this.setData({
        machineKey:machineryTotalList[(this.data.index-1+2)].machine_key,
        index:this.data.index-1+2,
        currentId:machineryTotalList[(this.data.index-1+2)].machine_key,
      })
    }
  },

  //点击定位点切换机械
  getListByMachineKey:function(event){
    this.onClickShow();
    this.selectMachineryRun(this.data.projectId,event.markerId.machine_key,this.data.machineryTotalList);
    let timeLevenStatus = this.data.timeLevenStatus;
    if(timeLevenStatus == 0){
      this.selectMachineryWeekTime(event.markerId.machine_key);
    }else{
      this.selectMachineryWeekTankLeven(event.markerId.machine_key);
    }
    var markers = this.data.markers;
    var index = "";
    for(var i = 0;i<markers.length;i++){
      if(markers[i].machineKey == event.markerId.machine_key){
        index = i;
      }
    }
    this.setData({
      index:index,
      showUp: true,
      currentId:event.markerId.machine_key
    })
  },


  //获取机械定位
  machineLocation:function(event){
    this.setData({
      longitude:this.data.machineLongitude,
      latitude:this.data.machineLatitude,
      markers:this.data.machineMarkers
    })
  },

  //获取个人定位
  personalLocation:function(even){
    this.setData({
      longitude:app.globalData.initialLon,
      latitude:app.globalData.initialLat,
      markers:app.globalData.markers,
    })
  },

  //切换最近一周工作时长和油耗
  cutTimeLeven(event){
    let machineKey = event.currentTarget.dataset.machinekey;
    this.onClickShow();
    if(event.detail.index == "0"){
      this.selectMachineryWeekTime(machineKey);
      this.setData({timeLevenStatus:0});
    }else{
      this.selectMachineryWeekTankLeven(machineKey);
      this.setData({timeLevenStatus:1});
    }
  },

  //返回设备管理首页
  goRYGL:function(event){
    wx.redirectTo({
      url: '../shebieguanli-jxsb/shajiangguan'
    })
  },

})