// pages/ucenter/control/batteryControl.js


var selectPopup1;
var selectPopup2;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    code: '202007221111110201',
    s1_index: -1,
    select1_text: '点击选择',
    select2_text: '点击选择',
    select1_arr:[],
    select2_arr:[],
    select1_index:-1,
    select2_index:-1,
    batteryByStation: {},
    chargPile:{
        // chargPileName:'测试电池包',
        // chargPileId:'202007221111110201',
        // address:'雁塔区小寨西路',
        // wxTest:'wxTest',
        chargPileName:'',
        chargPileId:'',
        address:'',
        wxTest:'wxTest',
    },
    cars:[],
    carIndex: -1,
    locations:[],
    locationIndex: -1,
    wxTest:{
        msg:'uuddudududud',
        index:0,
        t: new Date().valueOf(),
        tnum: 0,
    },
    tractorTaskTypeIndex: -1,
    tractorTaskTypeList:[
      {
          "txt": "装载电池包",
          "val": 2
      },
      {
          "txt": "卸载电池包",
          "val": 3
      },
      {
          "txt": "离开电池包",
          "val": 4
      }
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    // let {code} = options
    // this.setData({
    //     code
    // })



    wx.request({
        url: getApp().globalData.postHeadAgreement +'/restapi/wechat/ivCar',
        data: {
        },
        method: 'POST',
        success(res) {
            let cars = res?.data?.result?res?.data?.result:[]
            that.setData({
                cars
            })
        }
    })

    wx.request({
        url: getApp().globalData.postHeadAgreement +'/restapi/wechat/ivParkPoint',
        data: {
        },
        method: 'POST',
        success(res) {
            console.info(res);
            let locations = res?.data?.result?res?.data?.result:[]
            that.setData({
                locations
            })
        }
    })

        let userInfo = wx.getStorageSync('userInfo');
      // 加载下拉框
      wx.request({
          url: getApp().globalData.postHeadAgreement + '/restapi/wechat/batteryByStation',
          // data: charePileId,
          data:{
            chargPileId: '1771052602050748417',
            userId: userInfo.userId
          },
          method: 'POST',
          success(res) {
            res = res.data
            let batteryByStation = res.result
            let select1_arr = Object.keys(batteryByStation).sort().map(it=>{
                let regex = /chargStationName=(.*?)(,|")/;
                let match = it.match(regex);
                return match && match[1]?match[1]:it
            })
            let ee = {
                "detail":{
                    "value":0
                }
            }
            that.setData({
                batteryByStation,
                select1_arr,
            })

          },
          fail(e) {
            getApp().showNetworkError();
          }
        });
       


    // wx.showToast({
    //     title: that.data.code,
    //     icon: 'success',
    //     duration: 2000
    //   })
  },
  loadSelect2(){
    let that = this;
    let index1 = that.data.select1_index
    let batteryByStation = that.data.batteryByStation;
    let key = Object.keys(batteryByStation).sort()[index1]
    let select2_arr = batteryByStation[key].map(it=>it.chargPileName)
    that.setData({
        select2_arr,
    })

  },
  bindPickerChange1(e){
    let index = e.detail.value
    let text = this.data.select1_arr[index]
    this.setData({
        select1_index: index,
        select1_text: text,
        select2_index: -1,
        select2_text: '点击选择',
        chargPile:{}
    })
    this.loadSelect2()
  },
  bindPickerChange2(e){
    let that = this;
    let index = e.detail.value
    let text = this.data.select2_arr[index]

    let index1 = that.data.select1_index
    let batteryByStation = that.data.batteryByStation;
    let key = Object.keys(batteryByStation).sort()[index1]
    console.info(index1)
    console.info(index)
    console.info(key)
    console.info(batteryByStation[key])
    let code = batteryByStation[key].map(it=>it.chargPileId)[index]
    this.setData({
        select2_index: index,
        select2_text: text,
        code
    })
    that.loadCode()
  },
  loadCode(){
    let that = this


    let index1 = that.data.select1_index
    let batteryByStation = that.data.batteryByStation;
    let key = Object.keys(batteryByStation).sort()[index1]
    let chargPile = batteryByStation[key][that.data.select2_index]
    // let userInfo = wx.getStorageSync('userInfo');
    // wx.request({
    //     url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargPile',
    //     data: {
    //       chargPileId:that.data.code,
    //       userId: userInfo.userId
    //     },
    //     method: 'POST',
    //     success(res) {
    //     //   log.info('[首页]', '[获取扫一扫充电桩]', '[响应]', res.data);
    //     console.info(res)
    //     if (!res.data || res.data.code == 500) {
    //         wx.showModal({
    //           showCancel: false,
    //           content: res && res.data && res.data.msg ? res.data.msg :'无效的终端编号',
    //           confirmColor:'#00AADD',
    //         });
    //     }else{
    //         let chargPile = res.data.result;
            that.setData({
                chargPile
            })
    //     }

    //     },
    //     fail(e) {
    //       getApp().showNetworkError();
    //     }
    //   });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    selectPopup1 = this.selectComponent("#selectpopup1");
    selectPopup2 = this.selectComponent("#selectpopup2");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  upBtn(){
    let that = this;
    // if(that.wxTestDebug(that,'u') > 4){
    //     return ;
    // }
    that.bettyControl(1)
  },
  downBtn(){
    let that = this;
    // if(that.wxTestDebug(that,'d') > 4){
    //     return ;
    // }
    that.bettyControl(2);
  },
  pauseBtn(){
    let that = this;
    // if(that.wxTestDebug(that,'d') > 4){
    //     return ;
    // }
    that.bettyControl(3);
  },
  bettyControl(bettyControl){
    let that = this;
    wx.showLoading({
      title: '控制电池中。。。',
      mask: true
    })
    wx.request({
        url: getApp().globalData.postHeadAgreement +'/restapi/pileLog/bettyControl',
        data: {
            bettyControl,
            chargPileId: that.data.chargPile.chargPileId
        },
        method: 'POST',
        success(res) {
            console.info(res)
            wx.hideLoading()
            wx.showToast({
                icon: 'none',
                title: res.data.msg,
                duration: 1000
              })
        }
     })
  },
  wxTestDebugClick(){
    let that = this
    if(new Date().valueOf() - that.data.wxTest.t <= 1000){
        that.data.wxTest.tnum = that.data.wxTest.tnum + 1
    }else{
        that.data.wxTest.tnum = 0
    }
    that.data.wxTest.t = new Date().valueOf()
    if(that.data.wxTest.tnum > 10){
        wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechat/wxTest/switch',
            data: {
            },
            method: 'GET',
            success(res) {
                that.data.wxTest.tnum = 0
                wx.showToast({
                    title: "调试模式: " + res.data.msg,
                    duration: 1000
                  })
            }
         })
    }

  },
  wxTestDebug(that,s){
    // let that = this;

    if(that.data.wxTest.msg.length == that.data.wxTest.index + 1){
        wx.request({
            url: getApp().globalData.postHeadAgreement +'/restapi/wechat/wxTest/switch',
            data: {
            },
            method: 'GET',
            success(res) {
                wx.showToast({
                    title: "调试模式: " + res.data.msg,
                    duration: 1000
                  })
            }
         })
         idx = 0;
         that.setData({
             wxTest:{
                 msg:that.data.wxTest.msg,
                 index: idx,
             }
         })
         return;
    }
    let idx = 0
    if(that.data.wxTest.msg.substr(that.data.wxTest.index,1) == s){
        idx = that.data.wxTest.index + 1
        that.setData({
            wxTest:{
                msg:that.data.wxTest.msg,
                index: idx,
            }
        })
    }else{
        idx = 0;
        that.setData({
            wxTest:{
                msg:that.data.wxTest.msg,
                index: idx,
            }
        })
    }
    return idx;
  },
  carTap(e){
    let  carIndex =  e.currentTarget.dataset.idx;
    this.setData({
        carIndex
    })
  },
  locationTap(e){
    let  locationIndex =  e.currentTarget.dataset.idx;
    this.setData({
        locationIndex
    })

  },
  tractorTaskTypeTap(e){
    let  tractorTaskTypeIndex =  e.currentTarget.dataset.idx;
    this.setData({
        tractorTaskTypeIndex
    })
},
  submit(){
     let that = this;


     if(this.data.carIndex==-1){
        wx.showToast({
          icon: 'none',
          title: '请选择车辆',
          duration: 1000
        })
        return ;
     }
     if(this.data.locationIndex==-1){
        wx.showToast({
          icon: 'none',
          title: '请选择点位',
          duration: 1000
        })
        return ;
     }
     if(this.data.tractorTaskTypeIndex==-1){
        wx.showToast({
          icon: 'none',
          title: '请选择任务类型',
          duration: 1000
        })
        return ;
     }
      let car = this.data.cars[this.data.carIndex];
      let location = this.data.locations[this.data.locationIndex]
      wx.showModal({
        title: '提示',
        content: '是否调度当前车辆？' + car.carName + "|" + location.pointShowName,
        complete: (res) => {
          if (res.cancel) {
            
          }
      
          if (res.confirm) {
            wx.showLoading({
                title: '调度车辆中。。。',
                mask: true
            })
            let userInfo = wx.getStorageSync('userInfo');
            // userId: 
            wx.request({
                url: getApp().globalData.postHeadAgreement +'/restapi/wechat/createIvCarRequirement?' 
                + 'finalTargetParkPointId=' + location.id
                + '&carId=' + car.id
                // + '&chargePileId=' + that.data.chargPile.id
                + '&chargePileId=12'
                + '&userId=' + userInfo.userId
                // + '&requirementType=' + that.data.tractorTaskTypeList[that.data.tractorTaskTypeIndex]['val'],
                + '&requirementType=0',
                data:{
                    // "finalTargetParkPointId":location.id,
                    // "carId":car.id,
                    // "chargePileId":that.data.chargPile.chargPileId,
                    // "userId":userInfo.userId,
                    // "requirementType":that.data.tractorTaskTypeList[that.data.tractorTaskTypeIndex]['val'],
                },
                method: 'POST',
                success(ress) {
                    if(ress && ress.statusCode==200){
                        let iid = ress.data.result.id;
                        console.info(iid);
                        console.info("11111111111111111");
                        wx.request({
                            url: getApp().globalData.postHeadAgreement +'/restapi/wechat/xingshen',
                            data: {
                                // capacityResourceId: car.id,
                                // targetParkPointId: location.id,
                                // tractorTaskType: that.data.tractorTaskTypeList[that.data.tractorTaskTypeIndex]['val'],
            
                                // ivCarId:car.id,
                                // targetParkPointId: 1,
                                // capacityResourceId: location.id,
                                // tractorTaskType: that.data.tractorTaskTypeList[that.data.tractorTaskTypeIndex]['val'],
            
                                carId:car.id,
                                parkPointId: location.id,
                                carRequirementId: iid,
                                tractorTaskType: that.data.tractorTaskTypeList[that.data.tractorTaskTypeIndex]['val'],
                            },
                            method: 'POST',
                            success(res) {
                                wx.hideLoading();
                                if(res.statusCode==200){
                                    if(res.data.code==200){
                                        wx.showToast({
                                            icon: 'success',
                                            title: res.data.msg,
                                            duration: 1000
                                        })
                                    }else{
                                        wx.showToast({
                                            icon: 'none',
                                            title: '调度失败：' + res.data.msg,
                                            duration: 1000
                                        })
                                    }
                                }else{
                                    wx.showToast({
                                        icon: 'none',
                                        title: '调度失败',
                                        duration: 1000
                                    })
                                }
                            }
                         })
                    }
                },

            })

          }
        }
      })
  },
  goToScanResult(){
    let userInfo = wx.getStorageSync('userInfo');
    let that = this;
    wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargPile',
        // data: charePileId,
        data:{
          chargPileId: that.data.chargPile.chargPileId,
          userId: userInfo.userId
        },
        method: 'POST',
        success(res) {
          //console.log(res.data);
        //   log.info('[首页]', '[获取微信扫一扫充电桩]', '[响应]', res.data);
          if (!res.data || res.data.code == 500) {
            //没有该充电桩信息
            wx.showModal({
              showCancel: false,
              content: res && res.data && res.data.msg ? res.data.msg :'无效的终端编号',
              confirmColor:'#00AADD',
            });
          } else {
            res.data = res.data.result
            //充电状态0：离线、1：故障、2：空闲中、3：充电中、4：欠压故障、5：过压故障、6：过电流故障、8：预约、9：在线升级、10：操作中、11:已插枪等
            if (!res.data.chargstatus || res.data.chargstatus == 0 || res.data.chargstatus == 1 || res.data.chargstatus == 4 || res.data.chargstatus == 5 || res.data.chargstatus == 6 || res.data.chargstatus == 9) {
              //充电桩故障

              wx.showModal({
                showCancel: false,
                content: '终端故障，维修中',
                confirmColor:'#00AADD',
              });
            } else if (res.data.chargstatus == 3 || res.data.chargstatus == 8 || res.data.chargstatus == 10) {
              wx.showModal({
                showCancel: false,
                content: '正在充电中',
                confirmColor:'#00AADD',
              });
            } else if (res.data.chargstatus == 2 || res.data.chargstatus == 11) {
              wx.setStorage({
                key: "scan_chargpile",
                data: res.data
              });
            //   log.info('[首页]', '[微信扫一扫充电桩空闲跳转去充电界面]');
              let url = `/pages/scan_result/scan_result`;
              wx.navigateTo({
                url
              });
            }
          }
        },
        fail(e) {
          getApp().showNetworkError();
        }
      });
},
goToRecycle(){
  wx.showModal({
    title: '提示', 
    content: '是否进行电池包回收?',
    showCancel: true, 
    cancelText: '取消',
    confirmText: '确认',
    confirmColor: '#00AADD',
    success (res) {
      if (res.confirm) {
        console.log('用户点击了确认');
     wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/wechat/callCarRequirementJob',
      data:{},
      method: 'POST',
      success(res) {
        console.log("返回结果res：",res);
        if (!res.data || res.data.code == 1) {
          wx.showModal({
            showCancel: false,
            content: res && res.data && res.data.msg ? res.data.msg :'暂无电池包需要回归补电',
            confirmColor:'#00AADD',
          });
        } else {   
          wx.showModal({
            showCancel: false,
            content: res && res.data && res.data.msg ? res.data.msg :'调用成功',
            confirmColor:'#00AADD',
          });
        }
      },
    });
    }
    },
    fail(err) {
      getApp().showNetworkError();
    }
  });
},



})