import * as echarts from '../../ec-canvas/echarts';
import * as lf from '../../ec-canvas/echarts-liquidfill';
let chart = null;
function initChart(canvas, width, height, dpr) {
  chart = echarts.init(canvas, lf, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  var options111 = {
    series: [{
      type: 'liquidFill',
      data: [],
      color: ['#128cec'],//主体填充颜色
      center: ['50%', '50%'],//中心位置
      radius: '72%',//大小
      outline: {
        show: false
      },
      backgroundStyle: {
        color: '#cceaff'
      },
      label: {
        show: true,
        color: '#128cec',
        insideColor: '#ffffff',
        fontSize: 20,
        fontWeight: 'bold',
        align: 'center',
        baseline: 'middle',
        position: 'inside',
        formatter: function (p) {
          //console.log(p);
          if (isNaN(p.value)) {
            return '启动充电中';
          }
          return (p.value * 100).toFixed(2) + '%' + '\n' + '当前电量';
        }
      }
    }]
  };
  chart.setOption(options111);
  return chart;
}


let log = require('../../utils/log.js');
var chargingPng;
var chargingStatus;
var chargingStatusFlag = true;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderid: null,
    userId: null,
    chargPileId: null,
    chargingRate: 0,
    chargingTime: '',
    yczds:'',
    totalMoney:'',
    cdscdy:0,
    cdscdl:0,
    chargingOrder: null,
    chargPile: null,
    ec: {
      onInit: initChart
    }
  },
  drawCircle: function(step) {
      var newoption = chart.getOption();
      newoption.series[0].data[0] = parseFloat(step / 100.0).toFixed(2);
      chart.setOption(newoption, true);
      // console.info(newoption)
      // console.info(step)
      // console.info(newoption.series[0].data[0])
  },
  stopCharging(e) {
    wx.showLoading({
      title: '结束充电中...',
      mask: true
    });
    clearInterval(chargingStatus);
    let {
      orderid,
      userId,
      chargPileId
    } = this.data;

    log.info('[充电中]', '[结束充电]', '[请求]', {
      chargPileId,
      userId,
      orderid
    });
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/chargstop',
      data: {
        chargPileId,
        userId,
        orderid
      },
      method: 'POST',
      success(res) {
        wx.hideLoading();
        let {
          data
        } = res;
        log.info('[充电中]', '[结束充电]', '[响应]', data);
        if (data && data.code == 200) {
          //wx.showModal({
          //showCancel: false,
          //content: '结束充电成功'
          //});
          log.info('[充电中]', '[结束充电]', '[成功跳转订单支付界面]', data);
          let url = `/pages/order/order?orderid=${orderid}&userId=${userId}&chargPileId=${chargPileId}`;
          setTimeout(()=>{
            wx.redirectTo({
              url
            });
          },3000)


        } else {
          log.info('[充电中]', '[结束充电]', '[失败data null||data.code<>200]', data);
          wx.showModal({
            showCancel: false,
            content: '结束充电失败',
            confirmColor:'#00AADD',
          });

        }
      },
      fail(err){ 
       wx.hideLoading();
       wx.showModal({
         showCancel: false,
         content: '结束充电失败',
         confirmColor:'#00AADD',
       });
      log.info('[充电中]', '[结束充电]', '[fail]', err );
      }
    });
  },
  showChargingPng1() {
    var i = 0;
    let that = this;
    if (that.data.chargingOrder && that.data.chargingOrder.soc && that.data.chargingOrder.soc != 0) {
      chargingPng = setInterval(function() {
        if (i <= that.data.chargingOrder.soc) {
          that.drawCircle(i);
          that.setData({
            chargingRate: i
          });
          i++;
        } else {
          //console.log(chargingPng);
          clearInterval(chargingPng);
        }
      }, 20);
    }
  },
  showChargingPng() {
    if (this.data.chargingOrder && this.data.chargingOrder.soc && this.data.chargingOrder.soc != 0) {
      this.drawCircle(this.data.chargingOrder.soc);
      this.setData({
        chargingRate: this.data.chargingOrder.soc
      });   
    }
  },
  /**
   * 生命周期函数--监听页面加载
  */ 
  onLoad: function(options) {
    //console.log(options);
    let {
      orderid,
      userId,
      chargPileId
    } = options;
    log.info('[充电中]', '[加载完成]', '[参数]', {
      orderid,
      userId,
      chargPileId
    });
    this.setData({
      orderid,
      userId,
      chargPileId
    });
    if (!orderid||orderid=="null"){
      orderid=undefined;
    }
    let that = this;
    log.info('[充电中]', '[获取订单状态]', '[请求]', {
      chargPileId,
      userId,
      orderid
    });
    wx.request({
      url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatchargstatus',
      data: {
        chargPileId,
        userId,
        orderid
      },
      method: 'POST',
      success(res) {

        let {
          data
        } = res;
        // data.code = 500
        log.info('[充电中]', '[获取订单状态]', '[响应]', data);
        if (data && data.code == 200) {
          let {
            result: chargingOrder
          } = data;
          let {
            chargPileId,
            soc: chargingRate
          } = chargingOrder;
          let orderid_r = chargingOrder.orderid;
          //console.log(chargingOrder);
          log.info('[充电中]', '[获取充电桩]', '[请求]', chargPileId);
          wx.request({
            url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargPile',
            // data: chargPileId,
            data:{
              chargPileId:chargPileId,
              userId: userId
            },
            method: 'POST',
            success(res1) {
              //console.log(res1.data);
              res1.data = res1.data.result
              if (res1.data) {
                let {
                  data: chargPile
                } = res1;
                log.info('[充电中]', '[获取充电桩]', '[响应]', chargPile);
                that.setData({
                  chargPile
                });
              }
            }
          });
          console.log("chargingOrder.chargPileStatus   " + chargingOrder.chargPileStatus);
          if (chargingOrder.chargPileStatus == 1) { //启动中，继续轮训
            log.info('[充电中]', '[初次订单状态判定]', '[chargPileStatus状态1启动中，继续轮训]', data)
            that.setData({
              chargingOrder,
              chargPileId,
              orderid: orderid_r
            });
          } else if (chargingOrder.chargPileStatus == 2) { //充电中，继续轮训
            //console.log(chargingOrder.chargPileStatus == 2);
            if (chargingOrder.ljcdsj || chargingOrder.ljcdsj == 0) {
              var chargingTimeHour = Math.floor(chargingOrder.ljcdsj / 60);
              if (chargingTimeHour <= 9) {
                chargingTimeHour = '0' + chargingTimeHour;
              }
              var chargingTimeMinute = chargingOrder.ljcdsj % 60;
              if (chargingTimeMinute <= 9) {
                chargingTimeMinute = '0' + chargingTimeMinute
              }
              var chargingTime = chargingTimeHour + ":" + chargingTimeMinute + ":00";
            }
            var totalMoney = (parseFloat(chargingOrder.ycdfje) + parseFloat(chargingOrder.ycfwfje)).toFixed(2);
            var cdscdl = parseFloat(chargingOrder.cdscdl).toFixed(2);
            var cdscdy = parseFloat(chargingOrder.cdscdy).toFixed(2);
            var yczds = parseFloat(chargingOrder.yczds).toFixed(2);
            that.setData({
              chargingOrder,
              chargPileId,
              chargingTime,
              orderid: orderid_r,
              totalMoney,
              cdscdl,
              cdscdy,
              yczds
            });
            that.showChargingPng();

          } else if (chargingOrder.chargPileStatus == 3) { //充电完成，适用于主动拔枪
            clearInterval(chargingStatus);
            log.info('[充电中]', '[初次订单状态判定]', '[chargPileStatus状态3跳转到订单支付界面]', data);
            let {
              orderid,
              userId,
              chargPileId
            } = that.data;
            let url = `/pages/order/order?orderid=${orderid_r}&userId=${userId}&chargPileId=${chargPileId}`;
            wx.redirectTo({
              url
            });
          } else if (chargingOrder.chargPileStatus == 4) { //启动异常，回退界面
            clearInterval(chargingStatus);
            log.info('[充电中]', '[初次订单状态判定]', '[chargPileStatus状态4启动异常删除订单]', data);
            wx.showModal({
              showCancel: false,
              content: '开启充电失败',
              confirmColor:'#00AADD',
            });
            that.delOrder(orderid_r);
            console.log(orderid_r);
          }
        } else if (data && data.code == 500) {
          let {
            result: chargingOrder
          } = data;
          let {
            chargPileId,
            soc: chargingRate
          } = chargingOrder;
          let orderid_r = chargingOrder.orderid;
          //console.log(chargingOrder);
          log.info('[充电中]', '[获取充电桩]', '[请求]', chargPileId);
          // 查询桩信息
          wx.request({
            url: getApp().globalData.postHeadAgreement + '/restapi/wechat/chargPile',
            // data: chargPileId,
            data:{
              chargPileId:chargPileId,
              userId: userId
            },
            method: 'POST',
            success(res1) {
              //console.log(res1.data);
              res1.data = res1.data.result
              if (res1.data) {
                let {
                  data: chargPile
                } = res1;
                log.info('[充电中]', '[获取充电桩]', '[响应]', chargPile);
                that.setData({
                  chargPile
                });
              }
            }
          });
          console.log("进入");
        //   console.info("ddddddddddddddddddddddddddd")
        //   console.info(orderid)
        //   console.info(userId)
        //   console.info(chargPileId)
        //   console.info("ddddddddddddddddddddddddddd")
        // 取消跳转逻辑
          // clearInterval(chargingStatus);
          log.info('[充电中]', '[充电轮训]', '[chargPileStatus状态3跳转到订单支付界面]', data);
          // let url = `/pages/order/order?orderid=${orderid}&userId=${userId}&chargPileId=${chargPileId}`;
          // wx.redirectTo({
          //   url
          // });
        }else{
          console.log(res);
        }
      },
      fail(err) {
        // var chargingOrder = {chargStatus:1};
        //   that.setData({
        //     chargingOrder
        //   });
      }
    });
  },

  delOrder(orderId){
    // if (orderId){
    if (false){
      log.info('[充电中]', '[删除订单]', '[请求]', { "orderid": orderId });
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/exceptOrder',
        data: {"orderid":orderId},
        method: 'POST',
        success(res1) {
          console.log(res1.data);
          log.info('[充电中]', '[删除订单]', '[响应]', res1.data);
          //if (res1.data ) {
            
          //}
          wx.navigateBack();
        }
      });
    } 
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(e) {
    clearInterval(chargingStatus);
    this.showChargingPng();
    let {
      orderid,
      userId,
      chargPileId
    } = this.data;
    if (!orderid || orderid == "null") {
      orderid = undefined;
    }
    let that = this;
    chargingStatus = setInterval(function() {
      if(!chargingStatusFlag){
        return;
      }
      let chargPileIdCache = chargPileId;
      let userIdCache = userId;
      let orderidCache = orderid;
      wx.request({
        url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/wechatchargstatus',
        data: {
          chargPileId,
          userId,
          orderid
        },
        method: 'POST',
        success(res) {
          let {
            data
          } = res;

          if (data && data.code == 200) {
            let {
              result: chargingOrder
            } = data;
            let {
              chargPileId,
              soc: chargingRate
            } = chargingOrder;
            let orderid_r = chargingOrder.orderid;
            //console.log(chargingOrder.chargPileStatus);
            if (chargingOrder.chargPileStatus == 1) { //启动中，继续轮训
              log.info('[充电中]', '[充电轮训]', '[chargPileStatus状态1启动中，继续轮训]', data);
              that.setData({
                chargingOrder,
                chargPileId,
                orderid: orderid_r
              });
            } else if (chargingOrder.chargPileStatus == 2) { //充电中，继续轮训
              if (chargingOrder.ljcdsj || chargingOrder.ljcdsj == 0) {
                var chargingTimeHour = Math.floor(chargingOrder.ljcdsj / 60);
                if (chargingTimeHour <= 9) {
                  chargingTimeHour = '0' + chargingTimeHour;
                }
                var chargingTimeMinute = chargingOrder.ljcdsj % 60;
                if (chargingTimeMinute <= 9) {
                  chargingTimeMinute = '0' + chargingTimeMinute
                }
                var chargingTime = chargingTimeHour + ":" + chargingTimeMinute + ":00";
              }
              var cdscdl = parseFloat(chargingOrder.cdscdl).toFixed(2);
              var cdscdy = parseFloat(chargingOrder.cdscdy).toFixed(2);
              var totalMoney = (parseFloat(chargingOrder.ycdfje) + parseFloat(chargingOrder.ycfwfje)).toFixed(2);
              var yczds = parseFloat(chargingOrder.yczds).toFixed(2);
              // var orderid = orderid_r;
              that.setData({
                chargingOrder,
                chargPileId,
                chargingTime,
                chargingRate,
                orderid:orderid_r,
                cdscdl,
                cdscdy,
                totalMoney,
                yczds
              });
              that.drawCircle(chargingRate);
              console.info("-----------")
              console.info(that.data.orderid)
              console.info(orderid)
              console.info(orderid_r)
              console.info("-----------")
            } else if (chargingOrder.chargPileStatus == 3) { //充电完成，适用于主动拔枪
              clearInterval(chargingStatus);
              log.info('[充电中]', '[充电轮训]', '[chargPileStatus状态3跳转到订单支付界面]', data);
              let {
                orderid,
                userId,
                chargPileId
              } = that.data;
              let url = `/pages/order/order?orderid=${orderid_r}&userId=${userId}&chargPileId=${chargPileId}`;
              wx.redirectTo({
                url
              });
            } else if (chargingOrder.chargPileStatus == 4) { //启动异常，回退界面
              clearInterval(chargingStatus);
              log.info('[充电中]', '[充电轮训]', '[chargPileStatus状态4启动异常删除订单]', data);
              wx.showModal({
                showCancel: false,
                content: '开启充电失败',
                confirmColor:'#00AADD',
              });
              console.log(orderid_r);
              that.delOrder(orderid_r);
            } else if (chargingOrder.chargPileStatus == 5) { //订单被删除
                clearInterval(chargingStatus);
                log.info('[充电中]', '[充电轮训]', '[chargPileStatus状态5订单被删除]', data);
                wx.showModal({
                  showCancel: false,
                  content: '开启充电失败',
                  confirmColor:'#00AADD',
                });
                console.log(orderid_r);
                that.delOrder(orderid_r);
              }
          } else if (data && data.code == 500) {
              if(data.msg == '没有充电桩实时充电状态'){
                let url = `/pages/index/index`;
                wx.reLaunch({
                  url
                });
              }
            // console.info("ddddddddddddddddddddddddddd")
            // console.info(that.data.orderid)
            // console.info(userIdCache)
            // console.info(chargPileIdCache)
            // console.info("ddddddddddddddddddddddddddd")
            clearInterval(chargingStatus);
            log.info('[充电中]', '[充电轮训]', '[chargPileStatus状态3跳转到订单支付界面]', data);
            let url = `/pages/order/order?orderid=${that.data.orderid}&userId=${userIdCache}&chargPileId=${chargPileIdCache}`;
            wx.redirectTo({
              url
            });
          }else{
            console.log("2222222222222222222222222222");
            console.log(res);
            console.log(data);
            console.log(data.code);
            console.log(data && data.code == 500);
            console.log("2222222222222222222222222222");
          }
        }
      });
    }, 5000);
    // }, 5000);
  },
  phoneCall(e) {
    wx.makePhoneCall({
      phoneNumber: getApp().globalData.helpPhoneNum
    });
  },
  exceptionWarn(){

    let userInfo = wx.getStorageSync('userInfo');
    let isLogin = wx.getStorageSync('isLogin');
    let that = this;
    
    wx.showModal({
        title: '提示',
        content: '如果您无法正常结束充电，请提交申诉（一小时内最多提交两次）',
        confirmText: '提交',
        showCancel:true,
        confirmColor:'#00AADD',
        cancelColor:'#00AADD',
        success: function (res1) {
          if(!res1.confirm){
            return;
          }
          chargingStatusFlag = false;
          wx.request({
            url: getApp().globalData.postHeadAgreement + '/restapi/pileLog/applyDeleteChargPileLog',
            data: {
                loginName: userInfo.loginName,
                orderid:that.data.orderid
            },
            method: 'POST',
            success: function (res) {
                console.info(res);
                if(res.data.code == 200){
                    clearInterval(chargingStatus);
                    chargingStatusFlag = false;
                    wx.showModal({
                        title: '提示',
                        content: '申诉成功，异常订单已删除',
                        confirmColor:'#00AADD',
                        showCancel: false,
                        success: function (res1) {
                            if (res1.confirm) {
                                let url = `/pages/index/index`;
                                wx.reLaunch({
                                  url
                                });
                            
                            }
                        }
                    })

                }else{
                    chargingStatusFlag = true;
                    console.info(res.data.msg)
                    wx.showModal({
                        title: '提示',
                        content: '申诉失败, ' + res.data.msg + '。如有疑问请拨打客服电话4009608068',
                        confirmColor:'#00AADD',
                        showCancel: false,
                        // success: function (res1) {
                        //     if (res1.confirm) {
                        //         wx.switchTab({
                        //             url: '/pages/index/index'
                        //         })
                        //     }
                        // }
                    })
                }
            },
            fail(e) {
            chargingStatusFlag = true;
            console.log("删除车辆失败");
            log.info('[删除车辆]','[fail]', e);
            }
          });
        }
      });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    clearInterval(chargingStatus);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearInterval(chargingStatus);
  },

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

  },

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

  },

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

  }
})