// pages/queueCar/index.js
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    str:'&emsp;',
    payStatus : false,
    isClose: true, //判断当前页面是打开还是返回页还是切换页面 true是切换页面 false是返回
    loginStatus: wx.getStorageSync('loginStatus') ? wx.getStorageSync('loginStatus') : false,
    roleCodeList: wx.getStorageSync('roleCodeList') ? wx.getStorageSync('roleCodeList') : '',
    accountType: '',

    appointmentClassifyArray: [
      { label:'充电预约',value:'1' },
      { label:'管桩预约',value:'2' },
      { label:'其他预约',value:'3' },
    ], //预约类型

    searchVal: '',
    codeNum:0,

    //分页
    limit: 10,
    requestStatu: '加载中...',
    page: 1,
    totalPages: 1,
    more: false,
    nomore: '',
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const roleCodeList = wx.getStorageSync('roleCodeList')
    let loginStatus = wx.getStorageSync('loginStatus')
    this.setData({
      searchVal: '',
      roleCodeList: roleCodeList ? roleCodeList : '',
      loginStatus: loginStatus ? loginStatus : false
    })
    //动态tabbar
    // if (roleCodeList == 'bizAdmin') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list2,
    //   })
    // } else if(roleCodeList == 'send') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list3,
    //   })
    // } else if(roleCodeList == 'sale') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list4,
    //   })
    // } else if(roleCodeList == 'customer') {
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list5,
    //   })
    // } else if (roleCodeList=='driver'||roleCodeList==''){
    //   this.getTabBar().setData({
    //     list: app.globalData.allList[0].list1,
    //   })
    // }
    // if (typeof this.getTabBar === 'function' && this.getTabBar()) {
    //   this.getTabBar().setData({
    //     selected: 0
    //   })
    // }
    if(wx.getStorageSync('loginStatus')){
      this.getListFun();
    }

  },

  //获取排队信息
  getInfoFun: function () {
    //详情
    app.request.requestGetApi(app.API.appletQueueLicense, {}, this, function (res, _that) {
      let data = res.data.data;
      wx.stopPullDownRefresh();
      _that.setData({
        info: data
      })

    })
  },

  //取消排队
  cancelPd: function (e) {
    let _this = this;
    let { id,licenseNumber } = e.currentTarget.dataset
    if (this.data.loginStatus) {
      wx.showModal({
        title: '提示',
        content: `确定取消车辆【${licenseNumber}】排队？`,
        success: function (res) {
          if (res.confirm) {
            app.request.POST({
              url: app.API.lineUpCancel,
              params: {
                id: id
              },
              page: _this,
              isLoadingTxt: '取消中...',
              successFun: true
            }).then(res => {
              wx.showToast({
                title: '取消成功',
                icon: 'success',
                duration: 1000,
                mask: true
              })
              _this.getListFun(); //刷新列表
            })

          }
        }
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '登录后可操作',
        duration: 1500
      })
    }

  },

  //车辆调度
  adjustOrder: function (e) {
    let _this = this;
    let { id, orderId, licenseNumber } = e.currentTarget.dataset
    if (this.data.loginStatus) {
      wx.showModal({
        title: '提示',
        content: `确定对车辆【${licenseNumber}】进行调度？`,
        success: function (res) {
          if (res.confirm) {
            app.request.POST({
              url: app.API.lineUpAdjust,
              params: {
                id: id,
                orderId:orderId
              },
              page: _this,
              isLoadingTxt: '调度中...',
              successFun: true
            }).then(res => {
              wx.showToast({
                title: '调度成功',
                icon: 'success',
                duration: 1000,
                mask: true
              })
              _this.getListFun(); //刷新列表
            })

          }
        }
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '登录后可操作',
        duration: 1500
      })
    }

  },

  //登录
  toLogin: function () {
    wx.redirectTo({
      url: '../login/index?page=index',
    })
  },

  //页面跳转
  toLink: function (e) {
    let { url } = e.currentTarget.dataset
    wx.navigateTo({
      url: url
    })
  },

  //授权手机号登录
  getPhoneNumber: function (e) {
    let _this = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      app.request.requestPostApi(app.API.wxlogin + '?code=' + e.detail.code, {
        'code': e.detail.code
      }, _this, function (res, sourceObj) {
        // 登录成功保存token和登录状态在缓存中
        let getData = res.data.data;
        wx.setStorageSync('loginStatus', true); //登录状态
        wx.setStorageSync('Authorization', getData.token); //token
        wx.setStorageSync('phone', getData.phone); //手机号码
        wx.setStorageSync('accountType', getData.accountType); //账号类型
        wx.setStorageSync('name', getData.name); //名称
        wx.setStorageSync('account', getData.account); //账号
        wx.setStorageSync('id', getData.id); //账号
        _this.onShow()
        //重新设置底部tabbar
        const accountType = wx.getStorageSync('accountType')
        if (accountType != 1) {
          sourceObj.getTabBar().setData({
            list: app.globalData.list,
          })
        } else {
          sourceObj.getTabBar().setData({
            list: app.globalData.list2,
          })
        }
        wx.showModal({
          title: '温馨提示',
          content: '为更好的促进与您的交流，服务号需要向您发送消息',
          confirmText: "同意",
          cancelText: "拒绝",
          success(res) {
            if (res.confirm) {
              wx.requestSubscribeMessage({
                tmplIds: ["kJHrL39stnuaPO4ruYcNb7_1Wxc-JGlllaM79iDk9zE"], //所选模板的模板ID,可以有多个
                success: function (res) {
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                  wx.getSetting({
                    withSubscriptions: true,
                    success(res) {
                      console.log(res, res.subscriptionsSetting)
                    }
                  })
                },
                fail: function (err) {
                  console.log("获取消息推送授权失败", err);
                  wx.switchTab({
                    url: '/pages/index/index',
                  })
                }
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
      });

    }
  },

  //搜索框请求S
  onChange(e) {
    this.setData({
      searchVal: e.detail,
    });
  },
  onSearch: function (event) {
    this.setData({
      searchVal: event.detail
    })
    this.getListFun();
  },
  onCancel: function () {
    this.setData({})
  },
  toSearch: function (event) {
    this.getListFun();
  },

  //列表
  getListFun: function () {
    this.setData({
      page: 1
    })
    let params = {
      current: this.data.page,
      size: this.data.limit,
      licenseNumber:this.data.searchVal,
      appointmentFlag:'1'
    }
    app.request.pageFirst({
      url: app.API.lineUpList,
      page: this,
      params: params
    })
  },

  // 支付
  paySubmit: function (e) {
    // this.setData({
    //   payStatus : true,
    // })
    let _this = this
    let clearId = null
    if(e.currentTarget.dataset.warnType=='1'||this.data.codeNum > 0){
      return false
    }
    //60秒倒计时
    this.setData({
      codeNum : 60,
    })
    wx.showLoading({
      title: '等待支付...',
      mask: true
    })
    wx.login({
      success: (res) => {
        let formData = {
          id: e.currentTarget.dataset.id,
          code: res.code,
          //money: e.currentTarget.dataset.money //e.currentTarget.dataset.money //支付金额
        };
        wx.request({
          url: app.API.appointmentPay,
          method: 'POST',
          data: formData,
          header: {
            //'content-type': 'application/json',
            'Authorization': wx.getStorageSync('Authorization') ? 'Bearer ' + wx.getStorageSync('Authorization') : '' //'Bearer ' + 
          },
          success: function (res) {
            let obj = res.data;
            wx.hideLoading()
            wx.requestPayment({
              'timeStamp': obj.timeStamp,
              'nonceStr': obj.nonceStr,
              'package': obj.package,
              'signType': obj.signType,
              'paySign': obj.paySign,
              'success': function (payres) {
                _this.getInfoFun()
                // _this.setData({
                //   payStatus : false
                // })
                //支付成功后查询订单
                app.request.requestPostApi(app.API.payorder, {
                  id: e.currentTarget.dataset.id,
                  code: '123',
                }, _this, function (payorderRes, that) {
                  let payorderData = payorderRes.data.data;
                  console.log(payorderData)
                })

                if(clearId) clearInterval(clearId)
                clearId = setInterval(() => {
                  let getNumber = _this.data.codeNum - 1
                  _this.setData({
                    codeNum : getNumber
                  })
                  if (_this.data.codeNum == 0) {
                    clearInterval(clearId);
                  }
                }, 1000);
              },
              'fail': function (res) {
                console.log('支付失败',res)
                if(clearId) clearInterval(clearId)
                clearId = setInterval(() => {
                  let getNumber = _this.data.codeNum - 1
                  _this.setData({
                    codeNum : getNumber
                  })
                  if (_this.data.codeNum == 0) {
                    clearInterval(clearId);
                  }
                }, 1000);
                // _this.setData({
                //   payStatus : false
                // })
                // Notify({ type: 'danger', message: '您已取消支付,可在订单中完成支付' });
                console.log("申请支付，支付失败！ res:" + res);
                Dialog.alert({
                  title: '提示',
                  message: '支付失败或已取消支付',
                }).then(() => {})
                
              }
            })
          },
          fail:function(res){
            //倒计时
            if(clearId) clearInterval(clearId)
            clearId = setInterval(() => {
              let getNumber = _this.data.codeNum - 1
              _this.setData({
                codeNum : getNumber
              })
              if (_this.data.codeNum == 0) {
                clearInterval(clearId);
              }
            }, 1000);
          }
        })

      },
    })
  },

  //完成装载
  toCompleteLoading: function (e) {
    let _this = this;
    if (this.data.loginStatus) {
      wx.showModal({
        title: '提示',
        content: '确定完成装货？',
        success: function (res) {
          if (res.confirm) {
            app.request.requestPostApi(app.API.completeLoading, {id:e.currentTarget.dataset.id}, _this, function (res, that) {
              if (res.data.code == '200') { //退出登录
                that.getListFun()
                wx.showToast({
                  title: '操作成功',
                  icon: 'success',
                  duration: 2000,
                  complete: function () {
                    setTimeout(function () {}, 1500) //延迟时间 
                  }
                })
              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '出错了',
                  icon: 'none',
                  duration: 1500,
                  mask: true
                })
              }
            });
          }
        }
      })
    } else {
      wx.showToast({
        icon: 'none',
        title: '登录后可操作',
        duration: 1500
      })
    }

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      searchVal: ''
    })
    if (wx.getStorageSync('loginStatus')) {
      this.getListFun();
    } else {
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.page++;
    let params = {
      current: this.data.page,
      size: this.data.limit,
      licenseNumber:this.data.searchVal,
      appointmentFlag:'1'
    }
    app.request.pageOther({
      url: app.API.lineUpList,
      page: this,
      params: params,
      loadType: true //加载类型，是否是下拉加载
    });
  },

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

  }
})