var t = require("../../../utils/common.js");
const app = getApp();
var os = app.globalData.setting;
var regeneratorRuntime = require('../../../utils/runtime.js');

Page({
  data: {
    user: null,
    show_bind: 0,
    imghots: os.imghost,
    store_logo: '',
    first_leader: '',   //-- 邀请人 --
    config2: null,
    sub: 0,
    is_reg:1,
    openid:''
  },
  onLoad: function (options) {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    getApp().globalData.isLoad_ad = 1;

    if(options.openid){
        this.data.openid=options.openid;
        getApp().globalData.h5_openid=options.openid;

        console.log("options.openid")
        console.log(options.openid)
    }

    // if(options.is_reg){
    //   this.data.is_reg=1;
    // }

    //-- 看一下隐私政策要不要显示 --
    var privacy_pop = this.selectComponent("#privacy_pop"); //组件的id
    if (privacy_pop) {
      privacy_pop.check_pri_show();
    }

    //--判断是否有接受到邀请人的ID--
    if (options.first_leader) {
      this.setData({ first_leader: options.first_leader });
    } else if (getApp().globalData.first_leader) {
      this.setData({ first_leader: getApp().globalData.first_leader });
    }
    var th = this;
    app.getConfig(function (e) {
      var logo = th.data.imghots + e.store_logo;
      th.setData({ store: e, store_logo: logo });
    })


    //判断注册的条件
    app.getConfig2(function (e) {
      if (e.reg_type == 1) {
        var arr = JSON.parse(e.reg_info);
        if (arr['name_state'] == 1) th.data.name_need_go = 1;
        if (arr['birthday_state'] == 1) th.data.birth_need_go = 1;
        if (arr['idcard_state'] == 1) th.data.idcard_need_go = 1;
        if (arr['address_state'] == 1) th.data.address_need_go = 1;
        if (arr['pick_state'] == 1) th.data.pick_need_go = 1;
        if (arr['sex_state'] == 1) th.data.sex_need_go = 1;
        if (arr['introducer_state'] == 1) th.data.introducer_need_go = 1;
      }
      var json_d = JSON.parse(e.switch_list);
      if (json_d.user_label_set == 1) {
        th.data.is_lable_set = 1
        // self.setData({is_lable_set: 1})
        // if (json_d.is_bq_must==1) {
        //   self.setData({is_bq_must: 1})
        // }
      }
    }, 1)

    getApp().promiseGet("/api/wx/weappSendlist/page", {
      data: {
        store_id: os.stoid,
        typeid: "1007"
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data.pageData.length > 0) {
        var template_id = res.data.data.pageData[0].template_id;
        th.setData({ template_id: template_id });
      }
    })

    setTimeout(()=>{
        if(getApp().globalData.user_id){
            getApp().goto('/pages/user/index/index');
        }else{
            if(!this.data.openid){
              //getApp().goto('/packageH/pages/getopenid/index');
            }
        }

    },800)



  },


  //绑定手机号
  getphone: function (e) {
    //接下来写业务代码登录
    e = e.detail;
    if (e.encryptedData == undefined) {
      this.setData({ show_bind: 0 })
      return app.my_warnning("登录需要授权手机号码！", 0, this);
      return false;
    }
    if(this.data.sub) return false;
    this.setData({ sub: 1 });
    var sessionKey = getApp().globalData.sessionKey;
    var openid = getApp().globalData.openid;
    var r = getApp().globalData.getu;
    this.save_the_data(r, e, sessionKey, openid)
  },

     //订阅消息提醒
     newsendsm: function (ee) {
      if (!this.data.isAgree) {
        wx.showToast({
          title: '请您先阅读和勾选指定的内容',
          icon: 'none',
        });
        return false;
      }
      let th = this;
      var template_id = this.data.template_id;
      // //授权订阅
      wx.requestSubscribeMessage({
        tmplIds: [template_id],
        success(res) {
          th.bindGetUserInfo(ee);
        },
        fail(res) {
          th.bindGetUserInfo(ee);
        }
      })
    },
     //订阅消息提醒
     oldsendsm: function (ee) {
      if (!this.data.isAgree) {
        wx.showToast({
          title: '请您先阅读和勾选指定的内容',
          icon: 'none',
        });
        return false;
      }
      let th = this;
      var template_id = this.data.template_id;
      // //授权订阅
      wx.requestSubscribeMessage({
        tmplIds: [template_id],
        success(res) {
          th.bindUserInfo(ee);
        },
        fail(res) {
          th.bindUserInfo(ee);
        }
      })
    },

  //-- 会员授权 --
  bindGetUserInfo: function (ee) {
    if (!this.data.isAgree) {
      wx.showToast({
        title: '请您先阅读和勾选指定的内容',
        icon: 'none',
      });
      return false;
    }
    var that = this;
    //-- 点击授权 --
    that.getUserProfile(function (res) {
      var user = res;
      //--拿下code--
      wx.login({
        success: function (o) {
          var dd = {
            js_code: o.code,
            store_id: os.stoid,
            nickname: app.clear_word(app.globalData.getu.nickName),
            head_pic: app.clear_word(app.globalData.getu.avatarUrl)
          };
          //-- 导购会员ID --
          if (getApp().globalData.guide_id) {
            dd.guide_id = getApp().globalData.guide_id;
          }

          getApp().request.get("/api/weshop/users/openidandkey", {
            data: dd,
            success: function (e) {
              if (e.data.code == 0) {
                that.setData({ user: user })
                //如果有会员的话,没有sessionKey
                if (!e.data.data.sessionKey) {
                  // getApp().showWarning("登录成功");
                  wx.showToast({
                    title: '登录成功',
                    icon: 'success',
                    duration: 2000
                  });
                  getApp().globalData.userInfo = e.data.data;
                  getApp().globalData.user_id = e.data.data.user_id;
                  getApp().globalData.openid = e.data.data.weapp_openid;
                  //把会员的信息存在内存
                  wx.setStorageSync("userinfo", e.data.data);

                  //调用接口判断是不是会员
                  app.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + e.data.data.user_id, {}).then(res => {
                    if (res.data.code == 0) {
                      getApp().globalData.guide_id = res.data.data.id;
                      getApp().globalData.guide_pick_id = res.data.data.pickup_id
                    }
                  })


                  setTimeout(function () {
                    getApp().globalData.login_back = 1;
                    wx.navigateBack({ delta: 1 })  //返回上一页
                  }, 1000)
                } else {
                  getApp().globalData.sessionKey = e.data.data.sessionKey;
                  getApp().globalData.openid = e.data.data.openid;
                  that.setData({ show_bind: 1 });
                }
              } else {
                getApp().confirmBox(e.data.msg);
              }
            }
          });
        }
      })

    })
  },

  //-- 调整后的获取会员信息 --
  getUserProfile: function (func) {
    var that = this;
    wx.getUserProfile({
      desc: '获取用户相关信息',
      success: res => {
        console.log("getUserProfile", res);
        //此处授权得到userInfo
        getApp().globalData.getu = res.userInfo;
        func(res.userInfo);
      }
    });
  },

  //暂不登录，返回上一页
  cancle_bind: function () {
    wx.navigateBack({ delta: 1 })
  },

  close_pop: function () {
    this.setData({ show_bind: 0 })
  },
  show_bind_mobile: function () {
    let th = this;
    th.sendsm(function () {
      th.setData({ show_bind: 1 })
    })
  },


  save_the_data: async function (r, e, sessionKey, openid) {
    var app = getApp(), a = app, th = this;

    app.request.get("/api/weshop/manager/managerConfig/get", {
      data: {
        storeId: getApp().globalData.setting.stoid
      },
      success: function (res2) {
        if (res2.data.code == 0) {
          if (res2.data.data.is_newphone == 1) {
            var dd = {
              oauth: "miniapp",
              nickname: a.clear_word(r.nickName),
              head_pic: r.avatarUrl,
              sex: r.gender,
              terminal: "miniapp",
              sessionKey: sessionKey,
              openid: openid,
              code: e.code,
              isNewPhone: 1,
              store_id: getApp().globalData.setting.stoid,
            };
          } else {
            var dd = {
              oauth: "miniapp",
              nickname: a.clear_word(r.nickName),
              head_pic: r.avatarUrl,
              sex: r.gender,
              terminal: "miniapp",
              sessionKey: sessionKey,
              openid: openid,
              encryptedData: e.encryptedData,
              iv: e.iv,
              store_id: getApp().globalData.setting.stoid,
            };
          }


          //--如果有邀请人的时候--
          if (th.data.first_leader) {
            dd.first_leader = th.data.first_leader;
          }
          //-- 导购会员ID --
          if (getApp().globalData.guide_id) {
            dd.guide_id = getApp().globalData.guide_id;
          }

          //门店的扫描识别码
          if (getApp().globalData.store_number) {
            dd.SunCode = encodeURIComponent(getApp().globalData.store_number.trim());
          }

          console.log("-----会员注册的信息-------");
          console.log(dd);


          var need_go = 0;
          //如果有需要完善的信息没有完善，就需要跳转
          if (th.data.name_need_go) { need_go = 1; }
          if (th.data.birth_need_go) { need_go = 1; }
          if (th.data.idcard_need_go) { need_go = 1; }
          if (th.data.address_need_go) { need_go = 1; }
          if (th.data.pick_need_go) { need_go = 1; }
          if (th.data.sex_need_go) { need_go = 1; }
          if (th.data.introducer_need_go) { need_go = 1; }

          if (need_go) {

            if (res2.data.data.is_newphone == 1) {
              var req_data = {
                sessionKey: sessionKey,
                code: e.code,
                isNewPhone: 1,
                store_id: getApp().globalData.setting.stoid,
              }
            }else{
              var req_data = {
                sessionKey: sessionKey,
                encryptedData: e.encryptedData,
                iv: e.iv,
                store_id: getApp().globalData.setting.stoid,
              }
            }
            //-- 获取一下手机 --
            getApp().request.promiseGet("/api/weshop/users/getmobile", { data: req_data }).then(res => {
              if (res.data.code == 0) {
                dd.mobile = res.data.data;
                getApp().globalData.zc_dd = dd;

                var g_url="/packageA/pages/profile/profile?is_back=1";
                if(th.data.is_reg){
                    g_url+="&is_reg=1";
                }
                wx.redirectTo({
                  url:g_url
                })
              }
            })

          } else {
            if (th.data.is_lable_set) {
              if (res2.data.data.is_newphone == 1) {
                var req_data = {
                  sessionKey: sessionKey,
                  code: e.code,
                  isNewPhone: 1,
                  store_id: getApp().globalData.setting.stoid,
                }
              }else{
                var req_data = {
                  sessionKey: sessionKey,
                  encryptedData: e.encryptedData,
                  iv: e.iv,
                  store_id: getApp().globalData.setting.stoid,
                }
              }

              //-- 获取一下手机 --
              getApp().request.promiseGet("/api/weshop/users/getmobile", { data: req_data }).then(res => {
                if (res.data.code == 0) {
                  dd.mobile = res.data.data;
                  getApp().globalData.zc_dd = dd;

                   var g_url="/packageE/pages/user/labels/labels?pageType=1";
                   if(th.data.is_reg){
                     g_url+="&is_reg=1";
                   }

                   wx.redirectTo({ url: g_url })
                }
              })
            } else {
              th.setData({ sub: 0 });
              wx.showLoading({
                title: '处理中.',
                mask: true
              })
              th.zu_ce(dd); //调用注册的函数
            }
          }


        } else {
          th.setData({ sub: 0 });
          return app.my_warnning("授权登入失败,请稍后再试!", 0, that);
        }
      },
      failStatus: function (t) {
        th.setData({ sub: 0 });
        return app.my_warnning("授权登入失败,请稍后再试!", 0, that);
      },
      fail: function (t) {
        th.setData({ sub: 0 });
        return i.clearAuth(), i.alertLoginErrorAndGoHome(), !1;
      }
    });
  },

  
  
  zu_ce: function (dd) {


    if(this.data.sub) return false;
    this.setData({ sub: 1 });

    if(getApp().globalData.h5_openid){
      dd.wxopenid=getApp().globalData.h5_openid;
    }

    var th = this;
    app.request.get("/api/weshop/users/thirdLogin", {
      data: dd,
      success: function (e) {

        wx.hideLoading();
        th.setData({ sub: 0 });
        

        if (e.data.code == 0) {
          app.globalData.user_id = e.data.data.user_id;
          app.globalData.userInfo = e.data.data;
        }
        else if(e.data.code==-3){
          wx.showModal({
            title: e.data.msg,
            success: function (e) {
              if(e.confirm){
                dd.isreplacemobile=1;
                th.zu_ce(dd);
              }
            }
          });
          return false;
        }
        else {
          return app.my_warnning("授权登入失败！" + e.data.msg,0,th);
        }
        getApp().globalData.login_back = 1;
        wx.setStorageSync("userinfo", e.data.data);
        wx.setStorageSync("isAuth", !0), app.globalData.userInfo = e.data.data, app.globalData.userInfo.head_pic = t.getFullUrl(app.globalData.userInfo.head_pic);

        //调用接口判断是不是会员
        app.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + e.data.data.user_id, {}).then(res => {
          if (res.data.code == 0) {
            getApp().globalData.guide_id = res.data.data.id;
            getApp().globalData.guide_pick_id = res.data.data.pickup_id
          }
        })

        //-- 看情况,是跳转等级卡，还是跳转到新人有礼 --
        getApp().go_to_page(th.data.is_reg,function (){
          wx.navigateBack({ delta: 1 })
        })


      },
      failStatus: function (t) {
        th.setData({ sub: 0 });
        return app.my_warnning("授权登入失败,请稍后再试!", 0, th);
      },
      fail: function (t) {
        th.setData({ sub: 0 });
        return i.clearAuth(), i.alertLoginErrorAndGoHome(), !1;
      }
    });
  },

  bind_bnerr: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errObj = {};
    _errObj[_errImg] = this.data.imghots + "/miniapp/images/logo.png";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ;
  },

  //-- 会员授权 --
  bindUserInfo: function (ee) {
    var that = this;
    var user = ee.detail.userInfo;
    //此处授权得到userInfo
    getApp().globalData.getu = user;

    //--拿下code--
    wx.login({
      success: function (o) {
        var dd = {
          js_code: o.code,
          store_id: os.stoid,
          nickname: app.clear_word(app.globalData.getu.nickName),
          head_pic: app.clear_word(app.globalData.getu.avatarUrl)
        };
        //-- 导购会员ID --
        if (getApp().globalData.guide_id) {
          dd.guide_id = getApp().globalData.guide_id;
        }

        getApp().request.get("/api/weshop/users/openidandkey", {
          data: dd,
          success: function (e) {
            if (e.data.code == 0) {
              that.setData({ user: user })
              //如果有会员的话,没有sessionKey
              if (!e.data.data.sessionKey) {
                // getApp().showWarning("登录成功");
                wx.showToast({
                  title: '登录成功',
                  icon: 'success',
                  duration: 2000
                });

                getApp().globalData.userInfo = e.data.data;
                getApp().globalData.user_id = e.data.data.user_id;
                getApp().globalData.openid = e.data.data.weapp_openid;
                //把会员的信息存在内存
                wx.setStorageSync("userinfo", e.data.data);

                //调用接口判断是不是会员
                app.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + e.data.data.user_id, {}).then(res => {
                  if (res.data.code == 0) {
                    getApp().globalData.guide_id = res.data.data.id;
                    getApp().globalData.guide_pick_id = res.data.data.pickup_id
                  }
                })


                setTimeout(function () {
                  getApp().globalData.login_back = 1;
                  wx.navigateBack({ delta: 1 })  //返回上一页
                }, 1000)
              } else {
                getApp().globalData.sessionKey = e.data.data.sessionKey;
                getApp().globalData.openid = e.data.data.openid;
                that.setData({ show_bind: 1 });
              }
            } else {
              getApp().confirmBox(e.data.msg);
            }
          }
        });
      }
    })


  },


  close_pop_back: function () {
    this.close_pop();
    wx.navigateBack({ delta: 1 })
  },


  // 是否同意协议
  isAgree(e) {
    let template_id = this.data.template_id;
    let that = this
    let userinfo=getApp().globalData.userInfo;

    if (userinfo) {      
      let isAgree = null;
      if (e.detail.value[0]) {
        isAgree = true;
      } else {
        isAgree = false;
      };
      // this.data.isAgree = isAgree;
      this.setData({
        isAgree,
      });
    }else{
      // //授权订阅
      wx.requestSubscribeMessage({
        tmplIds: [template_id],
        success(res) {
          let isAgree = null;
          if (e.detail.value[0]) {
            isAgree = true;
          } else {
            isAgree = false;
          };
          // this.data.isAgree = isAgree;
          that.setData({
            isAgree,
          });
        },
        fail(res) {
          let isAgree = null;
          if (e.detail.value[0]) {
            isAgree = true;
          } else {
            isAgree = false;
          };
          // this.data.isAgree = isAgree;
          that.setData({
            isAgree,
          });
        }
      })
    }
  },

  //弹出框的同意的优化
  agree_pri:function (){
    // this.setData({
    //   isAgree:1,
    // });
  },
  //通过路径跳转到其他页面
  goto: function (e) {
    console.log('xxxx', e);
    var url = e.currentTarget.dataset.url;
    getApp().goto(url);
  },

  //订阅消息提醒
  sendsm: function (func) {
    var template_id = this.data.template_id;
    // //授权订阅
    wx.requestSubscribeMessage({
      tmplIds: [template_id],
      success(res) {
        func();
      },
      fail(res) {
        func();
      }
    })

  },


})
