const config = require('../../config/config.js')
const app = getApp()
const Common = require('../../common/common.js')
const Http = require('../../utils/http.js')
const HttpBasics = require('../../utils/HttpBasics.js')

Page({
  data: {
    logo: '../../static/images/logo.png',
    phone: '',
    pwd: '',
    status: '',
    showpass: "hidepass",
    focus: false,
    password: 'password',
    showPrivacy: false
  },
  onLoad() {
    Common.getMallIcon()
      .then(data => {
        // debugge
        this.setData({
          logo: data.data && data.data.mallImgUrl ? data.data.mallImgUrl : '../../static/images/logo.png'
        })
      })
    this.getPrivacySetting()
  },
  onShow() {
    var that = this;
    var phone = wx.getStorageSync("phone");
    var pwd = wx.getStorageSync("pwd");
    that.wxLogin();
    if (phone) {
      that.setData({
        phone: phone
      });
    }
    if (pwd) {
      that.setData({
        pwd: pwd
      });
    }
  },
  //显示具体的密码
  showpassword: function () {
    console.log(this.data.password);
    let that = this;
    if (that.data.password == 'password') {
      that.setData({
        password: 'text',
        focus: true
      })
    } else {
      that.setData({
        password: 'password',
        focus: true
      })
    }
  },
  wxLogin(flag) {
    let that = this;
    wx.login({
      success: res => {
        Common.getSuperOpenId(res.code)
          .then(res => {
            console.log(res)
            if (res.data && res.data.data && res.data.data.openId) {
              app.globalData.superopenId = res.data.data.openId;
            }
            if (res.data && res.data.data && res.data.data.session_key) {
              app.globalData.session_key = res.data.data.session_key;
            }
            if (res.data.code == 200) {
              app.globalData.phone = res.data.data.phone;
              that.setData({
                // ifAlBoss: true,
                status: "use"
              })
              if (flag == 'fromgetPhoneNumber') {
                wx.navigateTo({
                  url: `/pages/datatower/datatower?superopenId=${app.globalData.superopenId}&phone=${app.globalData.phone}`,
                })
              }

            } else {
              if (flag == 'fromgetPhoneNumber') {
                wx.showToast({
                  title: res.data.message,
                  icon: "none",
                  duration: 2000
                })
              }
            }
          })
          .catch(error => {
            that.setData({
              error: error.message
            })
          })
      }
    })
  },
  showpass: function () {
    let that = this;
  },

  phoneInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  pwdInput(e) {
    this.setData({
      pwd: e.detail.value
    })
  },

  forgetPwd() {
    wx.navigateTo({
      url: '/pages/index/forgetpwd/forgetpwd',
    })
  },

  reStore() {
    const phone = this.data.phone
    const pwd = this.data.pwd
    if (!phone || !pwd) {
      wx.showToast({
        title: '请输手机号或密码！',
        icon: 'none'
      })
      return
    }
    const data = {
      detail: {
        value: {
          phone: phone,
          pwd: pwd
        }
      }
    }
    this.getLoginInfo(data, true)
  },

  getLoginInfo(e, flag) {
    var phoneReg = /^1[0|1|2|3|4|5|6|7|8|9]\d{9}$/;
    let {
      phone,
      pwd
    } = e.detail.value;
    if (phoneReg.test(phone)) {
      if (pwd != '') {
        Common.userLogin(phone, pwd, app.globalData.latitude, app.globalData.longitude)
          .then(res => {
            console.log(res, 'login');
            if (res.code == 200) {
              // console.log(res,7777777)
              HttpBasics.setBUserId(res.data.bUserId);
              wx.setStorageSync("phone", phone);
              wx.setStorageSync("pwd", pwd);
              wx.setStorageSync("bUserId", res.data.bUserId);
              app.globalData.bUserId = res.data.bUserId;
              wx.setStorage({
                key: 'bUserId',
                data: res.data.bUserId,
              })
              wx.login({
                success: function (res) {
                  Common.getOpenId(res.code, app.globalData.bUserId, !flag)
                    .then(res => {
                      console.log(res, 'openId');
                      app.globalData.openId = res.data.data.openId;
                      app.globalData.token = res.data.data.token;
                      HttpBasics.setToken(res.data.data.token);
                      wx.setStorageSync("openId", res.data.data.openId);
                      wx.setStorageSync("session_key", res.data.data.session_key);
                      wx.showToast({
                        image: './../../static/images/success.png',
                        title: '登录成功',
                      })
                      if (!flag) {
                        wx.switchTab({
                          url: '/pages/main/main',
                        })
                      } else {
                        wx.navigateTo({
                          url: `/pages/getuserinfo/index?path=login`,
                        })
                      }
                    })
                    .catch(err => {
                      console.log(err, 'err');
                      wx.showToast({
                        title: err.data.message,
                        icon: 'none',
                      })
                    })
                }
              })
            } else {
              wx.showToast({
                image: './../../static/images/fail.png',
                title: res.message,
              })
            }
          })
      } else {
        wx.showToast({
          image: './../../static/images/fail.png',
          title: '密码不能为空',
        })
      }
    } else {
      wx.showToast({
        image: './../../static/images/fail.png',
        title: '手机号有误',
      })
    }
  },
  /**
   * 获得超级管理员手机号
   */
  getPhoneNumber: function (e) {
    console.log(e)
    // this.wxLogin("fromgetPhoneNumber");
    if (app.globalData.superopenId && app.globalData.session_key) {
      let { encryptedData, iv } = { encryptedData: e.detail.encryptedData, iv: e.detail.iv };
      if (encryptedData && iv) {
        Common.getUserPhone(encryptedData, iv, app.globalData.superopenId, app.globalData.session_key)
          .then(res => {
            if (res.data.code == 200 && res.data.data.admin == 1) {
              app.globalData.token = res.data.data.token
              app.globalData.phone = res.data.data.phone;
              wx.navigateTo({
                url: `/pages/datatower/datatower?superopenId=${app.globalData.superopenId}&phone=${app.globalData.phone}`,
              })
            } else {
              wx.showToast({
                title: res.data.message,
                icon: "none",
                duration: 2000
              })
            }
          }).catch(error => {
            console.log(error)
            wx.showToast({
              title: error.message,
              icon: "none",
              duration: 2000
            })
          })
      }
    }
  },

  clickPrivacy(e) {

  },

  closePrivacy() {
    wx.exitMiniProgram()
  },

  getPrivacySetting() {
    const canIUsePrivacy = wx.canIUse('getPrivacySetting')
    console.log(canIUsePrivacy, 'canIUse getPrivacySetting')
    if (canIUsePrivacy) {
      wx.getPrivacySetting({
        success: res => {
          console.log(res, 'getPrivacySetting') // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
          if (res.needAuthorization) {
            // 需要弹出隐私协议
            this.setData({
              showPrivacy: true
            })
          } else {
            // this.setData({
            //   showPrivacy: true
            // })
            // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
            // wx.getUserProfile()
            // wx.chooseMedia()
            // wx.getClipboardData()
            // wx.startRecord()
            // this.setData({
            //   showPrivacy: true
            // })
          }
        },
        fail: () => { },
        complete: () => { }
      })
    }
  },

  handleAgreePrivacyAuthorization() {
    console.log('Privacy Agreed!');
    this.setData({
      showPrivacy: false
    })
    // 用户同意隐私协议事件回调
    // 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
    // wx.getUserProfile()
    // wx.chooseMedia()
    // wx.getClipboardData()
    // wx.startRecord()
  },

  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {
        // this.setData({
        //   showPrivacy: false
        // })
      }, // 打开成功
      fail: () => { }, // 打开失败
      complete: () => { }
    })
  },

  /**
  * 用户点击右上角分享
  */
  onShareAppMessage: function (res) {
    let _this = this;
    return {
      title: '商管操作台',
      path: 'pages/index/index',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
})