// pages/login/index.js
import HTTP from "../../../requestFn/Api"
const app = getApp()
var QQMapWX = require('../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'ZZFBZ-RK6L6-FPZS5-E3MBZ-63LS2-7WBJE' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: "",
    phone_iv: "",
    phone_encrypt: "",
    isAgree: false,
    notips: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const {
      windowHeight,
      windowWidth
    } = app.globalData.systemInfo;
    this.setData({
      windowHeight,
      windowWidth
    });
  },

  //获取手机号
  getPhoneNumber(e) {
    let that = this;
    let phone_encrypt = e.detail.encryptedData;
    let phone_iv = e.detail.iv;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      that.login(phone_iv, phone_encrypt);
    }
  },
  login(phone_iv, phone_encrypt) {
    const that = this;
    wx.checkSession({
      success: (res) => {
        const {
          user_encrypt,
          user_iv,
          code
        } = app.globalData;
        HTTP.Login({
          phone_iv,
          phone_encrypt,
          code,
          user_encrypt,
          user_iv
        }).then(res => {
          if (res.token) {
            const {
              openim_id,
              token
            } = res;
            that.setData({
              openim_id,
            })
            app.globalData.openim_id = openim_id;
            wx.setStorageSync("userInfo", res)
            wx.setStorageSync("token", token)
            wx.setStorageSync("openim_id", openim_id)
            that.checkLocation();
          }
        })
      },
      fail: (res) => {
        app.getWxCode();
      },
      complete(res) {

      }
    })
  },
  locationScope() {
    const that = this;
    wx.authorize({
      scope: 'scope.userFuzzyLocation',
      success(res) {
        if (res.errMsg == "authorize:ok") {
          that.getLocation();
        }
      },
      fail(e) {
        that.goHome();
      }
    })
  },
  getLocation() {
    const that = this;
    wx.getFuzzyLocation({
      success(res) {
        const {
          latitude,
          longitude
        } = res;
        app.globalData.longitude = longitude;
        app.globalData.latitude = latitude;
        that.setData({
          longitude,
          latitude
        })
        that.getUserLocation();
      },
    })
  },
  getUserLocation() {
    let vm = this
    qqmapsdk.reverseGeocoder({ //逆地址解析（经纬度 ==> 坐标位置）
      location: {
        latitude: vm.data.latitude,
        longitude: vm.data.longitude
      },
      success(res) {
        var {
          result: {
            ad_info: {
              city
            }
          }
        } = res;
        app.globalData.city_name = city;
        vm.setData({
          city_name: city
        })
        vm.GetCityCode();
      }
    })
  },
  async GetCityCode() {
    const {
      city_name
    } = this.data;
    const data = await HTTP.GetCityCode({
      city_name
    });
    app.globalData.city_code = data.code;
    this.goHome();
  },
  checkLocation() {
    const that = this;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userFuzzyLocation'] === true) {
          that.getLocation();
        } else if (res.authSetting['scope.userFuzzyLocation'] === undefined) {
          that.locationScope();
        } else if (res.authSetting['scope.userFuzzyLocation'] !== undefined && res.authSetting['scope.userFuzzyLocation'] !== true) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权，否则无法使用相关功能！',
            success: res => {
              //如果点击取消则显示授权失败
              if (res.cancel) {
                wx.showToast({
                  title: '您已拒绝授权!',
                  icon: 'none'
                })
                that.goHome();
              }
              //如果点击确定会打开授权页请求二次授权
              else if (res.confirm) {
                wx.openSetting({
                  success: dataAu => {
                    if (dataAu.authSetting['scope.userFuzzyLocation'] === true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'none'
                      })
                      //再次授权，调用getLocationt的API
                      that.locationScope()
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none'
                      })
                      that.goHome();
                    }
                  }
                })
              }
            }
          })
        }
      },
    })
  },
  goHome() {
    const that = this;
    wx.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 1000,
      success(e) {
        that.LoginIM();
      }
    })
  },
  async LoginIM() {
    const {
      openim_id,
    } = this.data;
    const data = await HTTP.OpenimLogin({
      openim_id
    });
    const {
      data: {
        token,
      }
    } = data;
    app.globalData.openIMToken = token;
    wx.setStorageSync("openIMToken", token)
    app.login();
    setTimeout(() => {
      wx.switchTab({
        url: '/page/tabBar/home/index',
      })
    }, 1000)
  },
  noagree() {
    const {
      isAgree
    } = this.data;
    if (!isAgree) {
      this.setData({
        notips: true
      });
      setTimeout(() => {
        this.setData({
          notips: false
        });
      }, 1000)
    }
  },
  checkboxChange(e) {
    if (e.detail.value) {
      this.setData({
        isAgree: true
      })
    }
  },
  readTerms() {
    wx,
    wx.navigateTo({
      url: '../pages/protocol/protocol',
    })
  }
})