// pages/choose_rent_type/choose_rent_type.js
const {
  api,
  imgName,
  getUserInfo,
  wxLogin,
  alertTip,
  authAgainByUser
} = require('../../lib/util.js')
let timer = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgLogo: imgName('logo.png'),
    userTypes: [{
        value: 0,
        name: '公司用户'
      },
      {
        value: 1,
        name: '个人用户'
      }
    ],
    companyName: '',
    companyId: null,
    pointName: '',
    pointId: null,
    id: null, //数据id
    userType: null,
    dataError: true,
    user: null,
    hasCar: null, //用车
    status: 'normal' //normal正常  auth审核中 authFail审核驳回 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let {
      status
    } = options
    this.setData({
      user: wx.getStorageSync('user').userMapp
    })
    let that = this
    switch (status) {
      case 'auth':
        clearInterval(timer)
        timer = setInterval(() => {
          that.getStatus()
        }, 5000)
        break;
      case 'authFail':
        that.setData({
          status: 'authFail'
        })
        break;
      default:
        clearInterval(timer)
        that.setData({
          status: 'normal'
        })
        break;
    }
  },
  onShow: function() {
      this.getStatus()
  },
  onUnload() {
    clearInterval(timer)
  },
  onHide() {
    clearInterval(timer)
  },
  giveUp() {
    //放弃申请
    let that = this
    let {
      id
    } = that.data
    if (!id) {
      alertTip('请稍后重试')
      return
    }
    wx.showModal({
      title: '提示',
      content: '是否放弃申请',
      success: function(res) {
        if (res.confirm) {
          api.post('message/cancelJoin', {
            id
          }).then(res => {
            that.setData({
              status: 'normal'
            })
            clearInterval(timer)
          }).catch(err => {
            alertTip(err)
          })
        }
      }
    })
  },
  //用户选择
  radioChange(e) {
    let userType = Number(e.detail.value)
    this.setData({
      userType
    })
  },// 提交申请 
  applyFor() {
    let { companyName, companyId,pointName, pointId } = this.data
    if (!companyName) {
      alertTip('未选择公司')
      return
    }
    if (!pointName) {
      alertTip('未选择站点')
      return
    }
    let that = this
    wx.showModal({
      title: '提示',
      content: `确定申请 ${companyName} 下站点：${pointName}`,
      success: function (res) {
        if (res.confirm) {
          api.post('message/requestJoin', {
            userId: that.data.user.id,
            siteId: pointId,
            companyId: companyId,
            rentType: 0
          })
            .then(res => {
              //申请成功
              console.log(res)

              that.setData({
                status: 'auth'
              })
              wx.setStorageSync('hasTip', false)//重新申请授权驳回
              //轮询状态
              clearInterval(timer)
              that.getStatus()
              timer = setInterval(() => {
                that.getStatus()
              }, 5000)
            })
            .catch(err => {
              //轮询状态 重复申请的情况
              clearInterval(timer)
              that.getStatus()
              timer = setInterval(() => {
                that.getStatus()
              }, 5000)
              alertTip(err)
            })
        }
      }
    })

  },
  rentCar(e) {
    //个人用户开始租车
    api.get('user/getByUserId', { userId: this.data.user.id })
      .then(res => {
        console.log(res)
        // 判断是否存在未完成订单
        if (res.data.isNoPayMoney != 0) {
          // 付钱
          wx.navigateTo({
            url: '/pages/pay/pay?type=rent',
          })
          return
        }
        if (res.data.depositAmount == 0) {
          alertTip('租车前请先支付押金！', function () {
            wx.navigateTo({
              url: `/pages/pay/pay?type=deposit`,
            })
          })
          return
        }
        let user = wx.getStorageSync('user')
        user.userMapp.userType = 1
        user.userMapp.depositAmount = res.data.depositAmount
        wx.setStorageSync('user', user)
        wx.navigateTo({
          url: '/pages/device_bind/device_bind',
        })
      })
      .catch(err => {
        console.error(err)
      })
  },
  reApply() {
    //重新申请
    this.setData({
      status: 'normal',//normal正常  auth审核中 authFail审核驳回 
    })
    wx.setStorageSync('hasTip', true)
  },
  //登录页面
  resetStatus() {
    wx.reLaunch({
      url: '/pages/welcome2/welcome2',
    })
  },
  //获取审核状态
  getStatus() {
    let This = this
    api.get('message/getMessageInfo', {
      userId: This.data.user.id,
      messageType: 7//用户申请加入站点
    }, {}, true)
      .then(res => {
        let { state, id } = res.data
          This.setData({
            id
          })
        switch (state) {
          //待审核
          case 0:
            This.setData({
              status: 'auth'
            })
            break;
          //审核通过去首页
          case 1:
            clearInterval(timer)
            //存储用户类型，以这个为准
            let user = wx.getStorageSync('user')
            user.userMapp.userType = 0
            wx.setStorageSync('user', user)

            wx.redirectTo({
              url: '/pages/device_bind/device_bind',
            })
            break;
          //审核驳回
          case -1:
            if (wx.getStorageSync('hasTip')!=true){
              This.setData({
                status: 'authFail'
              })
            }            
            clearInterval(timer)
            break;
          //正常页面
          default:
            This.setData({
              status: 'normal',//normal 和 pedding
            })
            clearInterval(timer)
        }
      })
      .catch(err => {
        alertTip(err)
        console.error(err)
      })
  },  
  //获取公司
  getCompany() {
    wx.navigateTo({
      url: '/pages/search/search?type=companyByName',
    })
  },
  //获取2级网点
  getPoint() {
    wx.navigateTo({
      url: '/pages/search/search?type=byCompanyId',
    })
  },
})