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: '../../assets/images/logo.png',
    phone: '',
    pwd: '',
    status: '',
    showpass: "hidepass",
    focus: false,
    password: true,
    ifShowShop: false,
    merchantList: []
  },
  onLoad() {
    Common.getMallIcon()
      .then(data => {
        // debugge
        console.log(data, 777)
        this.setData({
          logo: data.data && data.data.mallImgUrl ? data.data.mallImgUrl : '../../assets/images/logo.png',
        })
      })
  },
  onShow() {
    var that = this;
    var phone = tt.getStorageSync("phone");
    var pwd = tt.getStorageSync("pwd");
    that.ttLogin();
    if (phone) {
      that.setData({
        phone: phone
      });
    }
    if (pwd) {
      that.setData({
        pwd: pwd
      });
    }

    // 进入页面后清空bUserId
    HttpBasics.setBUserId('');
    tt.setStorageSync("bUserId", '');
    app.globalData.bUserId = '';
    tt.setStorage({
      key: 'bUserId',
      data: '',
    })
  },
  //显示具体的密码
  showpassword: function () {
    console.log(this.data.password);
    let that = this;
    if (that.data.password) {
      that.setData({
        password: false,
        focus: true
      })
    } else {
      that.setData({
        password: true,
        focus: true
      })
    }
  },
  ttLogin(flag) {
    let that = this;
    tt.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') {
                tt.navigateTo({
                  url: `/pages/datatower/datatower?superopenId=${app.globalData.superopenId}&phone=${app.globalData.phone}`,
                })
              }

            } else {
              if (flag == 'fromgetPhoneNumber') {
                tt.showToast({
                  title: res.data.message,
                  icon: "none",
                  duration: 2000
                })
              }
            }
          }).catch(error => {
            console.log(error, "error");
            that.setData({
              error: error.message
            })
          })
      }
    })
  },
  showpass: function () {
    let that = this;
  },
  forgetPwd: function () {
    tt.navigateTo({
      url: '/pages/index/forgetpwd/forgetpwd',
    })
  },
  getLoginInfo(e) {
    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 => {
            const logined = res.data.logined
            const merchantList = res.data.merchantList
            // 当logined为true时，正常进入商户
            if (logined) {
              if (res.code == 200) {
                HttpBasics.setBUserId(res.data.bUserId);
                tt.setStorageSync("phone", phone);
                tt.setStorageSync("pwd", pwd);
                tt.setStorageSync("bUserId", res.data.bUserId);
                app.globalData.bUserId = res.data.bUserId;
                tt.setStorage({
                  key: 'bUserId',
                  data: res.data.bUserId,
                })
                tt.login({
                  success: function (res) {
                    Common.getOpenId(res.code, app.globalData.bUserId)
                      .then(res => {
                        console.log(res, 888)
                        app.globalData.openId = res.data.data.openId;
                        app.globalData.token = res.data.data.token;
                        HttpBasics.setToken(res.data.data.token);
                        tt.setStorageSync("openId", res.data.data.openId);
                        tt.setStorageSync("session_key", res.data.data.session_key);
                        tt.showToast({
                          image: './../../assets/images/success.png',
                          title: '登录成功',
                        })
                        tt.switchTab({
                          url: '/pages/main/main',
                          success(res) {
                            console.log(`${res}`);
                          },
                          fail(err) {
                            console.log(err, `switchTab调用失败`);
                          },
                        })
                      })
                  }
                })
              } else {
                tt.showToast({
                  image: './../../assets/images/fail.png',
                  title: res.message,
                  icon: "none"
                })
              }
              // 当logined为false时，选择商户
            } else {
              tt.setStorageSync("phone", phone);
              tt.setStorageSync("pwd", pwd);
              this.setData({
                ifShowShop: true,
                merchantList: merchantList
              })
            }
          })
      } else {
        tt.showToast({
          image: './../../assets/images/fail.png',
          title: '密码不能为空',
          icon: "none",
        })
      }
    } else if (phone == "") {
      tt.showToast({
        image: './../../assets/images/fail.png',
        title: '请输入手机号',
        icon: "none"
      })
    } else {
      tt.showToast({
        image: './../../assets/images/fail.png',
        title: '手机号有误',
        icon: "none"
      })
    }
  },
  /**
   * 获得超级管理员手机号
   */
  getPhoneNumber: function (e) {
    this.ttLogin("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.phone = res.data.data.phone;
              tt.navigateTo({
                url: `/pages/datatower/datatower?superopenId=${app.globalData.superopenId}&phone=${app.globalData.phone}`,
              })
            }
          })
      }
    }
  },
  goShop(e) {
    const id = e.currentTarget.dataset.id
    HttpBasics.setBUserId(id);
    tt.setStorageSync("bUserId", id);
    app.globalData.bUserId = id;
    tt.setStorage({
      key: 'bUserId',
      data: id,
    })
    tt.login({
      success: function (res) {
        Common.getOpenId(res.code, app.globalData.bUserId)
          .then(res => {
            console.log(res, 888)
            app.globalData.openId = res.data.data.openId;
            app.globalData.token = res.data.data.token;
            HttpBasics.setToken(res.data.data.token);
            tt.setStorageSync("openId", res.data.data.openId);
            tt.setStorageSync("session_key", res.data.data.session_key);
            tt.showToast({
              image: './../../assets/images/success.png',
              title: '登录成功',
            })
            tt.switchTab({
              url: '/pages/main/main',
              success(res) {
                console.log(`${res}`);
              },
              fail(err) {
                console.log(err, `switchTab调用失败`);
              },
            })
          })
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    let _this = this;
    return {
      title: '数据塔台',
      path: '/pages/main/main',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
})