// pages/detail/appointment/index.js
import api from '../../../utils/Api.js'
import Schedule from '../../../utils/Schedule.js'
import Wx from '../../../utils/Wx.js'
const {
  $Toast
} = require('../../../iview/base/index');
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    nickname: {},
    detail: {},
    phone: '',
    formPhone: '',
    date: '',
    remark: '',
    loading: false,
    sessionId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      })
    }

    // 获取session id
    let that = this
    this.getSessionKey(function(sid) {
      that.setData({
        sessionId: sid
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let that = this
    wx.showNavigationBarLoading()
    wx.showLoading({
      title: '加载中...',
    })
    new Schedule().task(this.getDetailData).delay(1200).task(() => {
      wx.hideNavigationBarLoading()
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.setData({
      nickname: app.globalData.userInfo.nickname
    })
    if (app.globalData.userInfo.phone && app.globalData.userInfo.phone.length > 0) {
      this.setData({
        phone: app.globalData.userInfo.phone
      })
    }
  },

  getDetailData: function() {
    api.project.detail({
      id: this.data.id
    }).then(res => {
      if (!res.code) {
        console.log(res.data)
        this.setData({
          detail: res.data
        })
      }
    })
  },
  // 打开位置
  handleMap: function() {
    wx.openLocation({
      latitude: parseFloat(this.data.detail.latitude),
      longitude: parseFloat(this.data.detail.longitude),
    })
  },
  handlePhoneAuth: function(event) {
    // 获取session key
    let encryptedData = event.detail.encryptedData
    let iv = event.detail.iv
    let that = this
    // 检查session key是否过期，如果过期的话，那么就获取新的再请求，否则直接请求
    wx.checkSession({
      success: function(res) {
        //session_key未过期，直接操作
        let sessionId = that.data.sessionId
        api.getPhoneNumber({
          sessionId: sessionId,
          encryptedData: encryptedData,
          iv: encodeURIComponent(iv)
        }).then(res => {
          if (!res.code) {
            $Toast({
              content: '手机号授权成功',
              type: 'success'
            });
            that.setData({
              phone: res.data.phone
            })
            // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
            if (app.globalData.userInfo) {
              app.globalData.userInfo.phone = res.data.phone
            }
          } else {
            $Toast({
              content: res.msg,
              type: 'error'
            });
          }
        })
      },
      fail: function() {
        console.log('checkSession fail!')
        // session_key 已过期，进行登录操作，提示错误
        // 获取session id
        let that = this
        this.getSessionKey(function(sid) {
          that.setData({
            sessionId: sid
          })
          // 授权手机号
          api.getPhoneNumber({
            sessionId: sid,
            encryptedData: encryptedData,
            iv: encodeURIComponent(iv)
          }).then(res => {
            if (!res.code) {
              $Toast({
                content: '手机号授权成功',
                type: 'success'
              });
              that.setData({
                phone: res.data.phone
              })
              // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
              if (app.globalData.userInfo) {
                app.globalData.userInfo.phone = res.data.phone
              }
            } else {
              $Toast({
                content: res.msg,
                type: 'error'
              });
            }
          })
        })
      }
    })

    // Wx.login().then(res => {
    //   let encryptedData = event.detail.encryptedData
    //   let iv = event.detail.iv
    //   this.decodePhoneData(res.code, encryptedData, iv)
    // })
  },

  /**
   * 获取服务器端 session key
   */
  getSessionKey(callback) {
    Wx.login().then(res => {
      if (res.errMsg == 'login:ok') {
        api.getSessionKey({
          code: res.code
        }).then(res => {
          if (res.code == 0) {
            typeof callback == "function" && callback(res.data)
          } else {
            $Toast({
              content: res.msg,
              type: 'error'
            });
          }
        })
      } else {
        $Toast({
          content: 'wx.login失败',
          type: 'error'
        });
      }
    })
  },

  /**
   * 解密手机号数据
   */
  decodePhoneData: function(code, encryptedData, iv) {
    let that = this
    api.getPhoneNumber({
      code: code,
      encryptedData: encryptedData,
      iv: iv
    }).then(res => {
      if (!res.code) {
        $Toast({
          content: '手机号授权成功',
          type: 'success'
        });
        this.setData({
          phone: res.data.phone
        })
        // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
        if (app.globalData.userInfo) {
          app.globalData.userInfo.phone = res.data.phone
        }
      } else {
        $Toast({
          content: '手机号授权失败',
          type: 'error'
        });
      }
    })
  },

  handleNickname: function(event) {
    this.setData({
      nickname: event.detail.value
    })
  },

  handleDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },

  handleRemark: function(event) {
    this.setData({
      remark: event.detail.value
    })
  },
  handleSubmit: function() {
    if (!this.data.nickname || !this.data.phone || !this.data.date) {
      $Toast({
        content: '请完善必要信息',
        type: 'error'
      });
      return
    }
    if (this.data.phone.length == 0) {
      $Toast({
        content: '请授权手机号',
        type: 'error'
      });
      return
    }
    api.project.reservate({
      pid: this.data.id,
      nickname: this.data.nickname,
      phone: this.data.phone,
      expectation_time: this.data.date,
      remark: this.data.remark
    }).then(res => {
      $Toast({
        content: res.msg,
        type: !res.code ? 'success' : 'error'
      });
      if (!res.code) {
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 800)
      }
    })
  },

  /**
   * 保存手机号
   */
  savePhone() {
    //发送请求保存手机号
    const phone = this.data.formPhone
    api.getPhoneNumber({
      phone: phone
    }).then(res => {
      if (!res.code) {
        // 将刚拿到的手机号码放到全局数据中，否则phone数据只会是当前页面数据
        if (app.globalData.userInfo) {
          app.globalData.userInfo.phone = res.data.phone
        }
        this.setData({
          phone: res.data.phone,
          visible: false
        })

        if (res.is_relation) {
          $Toast({
            content: '温馨提示:手机号授权成功,系统已自动关联您在其他平台购买的美行者VIP会员',
            type: 'success'
          });

        } else {
          $Toast({
            content: '手机号授权成功',
            type: 'success'
          });
        }

        //在拉去一遍用户信息
        this.getUserInfo();
      } else {
        this.setData({
          'errMsg': true,
          'errMessage': '*' + res.msg
        })
      }
    })

  },

  //获取用户信息
  // 获取个人资料
  getUserInfo: function () {
    api.me.info().then(res => {
      if (!res.code) {
        console.log(res.data);
        app.globalData.userInfo = res.data
        // 渲染数据
        this.setData({
          user: res.data,
        })
      }
    })
  },

  /**
   * 关闭手机号填写弹窗
   */
  alertClose() {
    this.setData({
      visible: false
    });
  },

  /**
   * 打开手机号填写弹窗
   */
  openAlert() {
    this.setData({
      visible: true
    })
  },

  handlePhone: function (event) {
    this.setData({
      formPhone: event.detail.detail.value
    })
  },
})