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

Page({
  data: {
    user: null,
    show_bind: 0,
    imghots: os.imghost,
    store_logo: '',
    first_leader: '',   //-- 邀请人 --
    config2: null,
    sub: 0,
    phone: '',
    id: "",
    openuserid: '',
    skip_verify: 1,
    error_arr: {
      '81012': '缺失可见范围',
      '81013': 'UserID、部门ID、标签ID全部非法或无权限',
      '40031': '不合法的UserID列表',
      '0032': '不合法的UserID列表长度',
      '40058': '不合法的参数',
      '40063': '参数为空',
      '40094': '不合法的URL',
      '40096': '不合法的外部联系人userid',
      '40099': '外部联系人的数量已达上限',
      '40100': '此用户的外部联系人已经在转移流程中',
      '40125': '无效的openuserid参数',
      '41001': '缺少access_token参数',
      '41009': '缺少userid参数',
      '41010': '缺少url参数',
      '41035': '缺少外部联系人userid参数',
      "41037": '缺少「联系我」type参数',
      "41038": '缺少「联系我」scene参数',
      "41039": '无效的「联系我」type参数',
      "41040": '无效的「联系我」scene参数',
      "41041": '「联系我」使用人数超过限制',
      "41042": '无效的「联系我」style参数',
      "41043": '缺少「联系我」config_id参数',
      "41044": '无效的「联系我」config_id参数',
      "41045": 'API添加「联系我」达到数量上限',
      "42001": 'access_token已过期',
      '43009': '企业未验证主体',
      '45009': '接口调用超过限制',
      '45022': '应用name参数长度不符合系统限制',
      '45024': '帐号数量超过上限',
      '45034': 'url必须有协议头',
      '46004': '指定的用户不存在',
      '48001': 'API功能未授权',
      '48002': 'API接口无权限调用',
      '48003': '不合法的suite_id',
      '48004': '授权关系无效',
      '48005': 'API接口已废弃',
      '48006': '接口权限被收回',
      '60102': 'UserID已存在',
      '670010': '负责人数量超出限制',
      '81014': '标签添加成员，单次添加user或party过多',
      '82001': '	指定的成员/部门/标签全部为空',
      '84072': '应用未配置客服',
      '84073': '客服userid不在应用配置的客服列表中',
      '84074': '没有外部联系人权限',
      '84075': '不合法或过期的authcode',
      '84076': '缺失authcode',
      '84083': '非服务人员',
      '84084': '非跟进用户',
      '84085': '应用已下架',
      '84144': '确认者的gid不在当前服务商的通讯录中',
      '84145': '确认者gid所在的企业数不能超过5个',
      '84146': '确认者gid最多只能在3个企业下确认合同',
      '86001': '参数 chatid 不合法',
      '86003': '参数 chatid 不存在',
      '86004': '参数 群名不合法',
      '86005': '参数 群主不合法',
      '86006': '群成员数过多或过少',
      '86007': '不合法的群成员',
    },
  },
  onLoad:async function (tt) {
    // tt.scene="0_0_16"
    if (tt && tt.scene) {
      var first_leader_str = decodeURIComponent(tt.scene);
      var f_arr = first_leader_str.split("_");
      // first_leader = f_arr[0] && parseFloat(f_arr[0]) > 0 ? f_arr[0] : null;
      //注册门店
      // if (f_arr[1] && parseFloat(f_arr[1]) > 0) {
      // 	getApp().globalData.store_number = f_arr[1];
      // }
      //企业微信群id
      if (f_arr && f_arr[2] && parseFloat(f_arr[2]) > 0) {
        this.setData({
          id: f_arr[2]
        })
        await  this.getopenuserid(f_arr[2])
        //判断是否有注册，如果没有注册必须先注册
        let userinfo = wx.getStorageSync('userinfo');
        if (!userinfo) {
          wx.setStorageSync('qyzsdg', tt.scene)
          wx.navigateTo({
            url: '/packageE/pages/togoin/togoin',
          })
        }else{
          if (userinfo && userinfo.mobile) {
            wx.removeStorageSync('qyzsdg')
            this.setData({
              phone:userinfo.mobile
            })     
           
          }else{

            wx.removeStorageSync('userinfo')
            wx.setStorageSync('qyzsdg', tt.scene)
            wx.navigateTo({
              url: '/packageE/pages/togoin/togoin',
            })
          }
        }

        // getApp().globalData.groupchat_id = f_arr[2];
      }

    }
    // if (wx.getUserProfile) {
    //   this.setData({
    //     canIUseGetUserProfile: true
    //   })
    // }
    // getApp().globalData.isLoad_ad = 1;
    //--判断是否有接受到邀请人的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
    //   }
    // }, 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 });
    //   }
    // })
  },
  onShow:function(){
    let userinfo = wx.getStorageSync('userinfo');
    if (userinfo && userinfo.mobile) {
      this.setData({
        phone:userinfo.mobile
      })
      // wx.removeStorageSync('qyzsdg')
    }
    // if (this.data.id) {
    //   this.getopenuserid(this.data.id)
    // }
  },
  getopenuserid(id) {
    let url = `/api/weshop/qyWeChat/qywxStaffcode/get/${id}`
    getApp().request.promiseGet(url, { data: {} }).then(async res => {
      console.log(res);
      if (res.data.code == 0) {
        // let resdata=JSON.parse(res.data.data);
        let openuserid = res.data.data.openuserid;
        let skip_verify = res.data.data.skip_verify;
        let guide_id =res.data.data.guide_id
        getApp().globalData.guide_id=guide_id

        						//调用接口判断是不是会员
        await getApp().request.promiseGet("/api/weshop/shoppingGuide/getId/" + oo.stoid + "/" + guide_id, {}).then(
          res => {
            // console.error(res);
            if (res.data.code == 0) {
              getApp().globalData.first_leader = res.data.data.bind_user_id;
              // goods.guide_sn = res.data.data.salesman_no;
            }
          }
        )
        this.setData({
          openuserid,
          skip_verify
        })
        if (this.data.phone) {
          
          this.befgetqy()
        }
        // if (this.data.phone) {
        //   this.getqy()
        // }
      }
    })
  },
  async getqy() {
    // wx.showLoading({
    //   title: '加载中',
    //   mask:true
    // })
    let openuserid = this.data.openuserid
    let skip_verify = this.data.skip_verify ? true : false
    let res = await getApp().request.promisePost(`/apib/weshop/admin/qyWeChat/qyWeChatCorpInfo/postAdminQyApi?accdb=${this.data.store.erpid}&url=externalcontact/add_contact_way&qyid=4`, {
      data: {
        // accdb: getApp().globalData.config.erpid,
        // ApiName: 'api.pos.shop.advancesum.seek',
        // url:'externalcontact/add_contact_way',
        user: openuserid,
        type: 1,
        scene: 2,
        style: 1,
        state: '手店_' + this.data.phone,
        skip_verify
        // is_temp:true,
        // store_id: getApp().globalData.setting.stoid,
        // usercode: "admin",
        // vipid: this.data.userinfo.erpvipid,
        // oddsum: "0",
        // advancesum: cartList.order_amount,
        // storageid: storageid,
        // listform
      },
      is_json: 1
    })
    wx.hideLoading()
    if (res.data && res.data.errcode == 0) {
      this.setData({
        qr_code: res.data.qr_code
      })
      this.saveqy(res.data.config_id, res.data.qr_code)
    } else {
      let errcode = res.data.errcode
      let msg = errcode
      if (this.data.error_arr[errcode]) {
        msg += this.data.error_arr[errcode]
      }
      wx.showModal({
        title: '提示',
        content: '获取失败,错误码:' + msg,
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
    console.log('获取企业二维码');
    console.log(res);
  },

  //绑定手机号
  getphone: function (e) {
    //接下来写业务代码登录
    console.log(e);
    e = e.detail;
    if (e.code == undefined) {
      this.setData({ show_bind: 0 })
      return app.my_warnning("登录需要授权手机号码！", 0, this);
      return false;
    }
    let that =this;
    let req_data = {
      js_code:e.code,
      store_id:getApp().globalData.setting.stoid,
    }
    getApp().request.promiseGet('/api/weshop/users/getCodeMobile',{data:req_data}).then(res=>{

       if (res.data.code==0) {
          this.setData({
            phone:res.data.data
          })
          this.befgetqy()
        }else {
          return app.my_warnning("授权登入失败,请稍后再试!", 0, that);
        }
      },
    );
  
    // app.request.get("/api/weshop/manager/managerConfig/get", {
    //   data: {
    //     storeId: getApp().globalData.setting.stoid
    //   },
    //   success: function (res2) {
    //     if (res2.data.code == 0) {
    //       var sessionKey = getApp().globalData.sessionKey;
    //       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,
    //         }
    //       }

    //       debugger
    //       //-- 获取一下手机 --/api/weshop/users/getCodeMobile?store_id=1&js_code=b8451556dd98b2eebec5aa6775625bce192a68fc1a4b15b0c6bf3ed046f90da4
    //       getApp().request.promiseGet("/api/weshop/users/getmobile", { data: req_data }).then(res => {
    //         debugger
    //         if (res.data.code == 0) {
    //           let resdata = res.data.data;
    //           that.setData({
    //             phone: resdata
    //           })
    //           that.befgetqy()
    //         }
    //       })
    //       // var sessionKey = getApp().globalData.sessionKey;
    //       // var openid = getApp().globalData.openid;
    //       // var r = getApp().globalData.getu;
    //       // this.save_the_data(r, e, sessionKey, openid)


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

  },

  charuser(){
    wx.navigateTo({
      url: '/packageE/pages/togoin/togoin',
    })
    // wx.showModal({
    //   title: '提示',
    //   content: '当前暂未登录，是否授权登录',
    //   complete: (res) => {
    //     if (res.confirm) {
    //       wx.navigateTo({
    //         url: '/packageE/pages/togoin/togoin',
    //       })
    //     }
    //   }
    // })
  },

  async befgetqy() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let openuserid = this.data.openuserid
    let res = await getApp().request.promiseGet(`/api/weshop/qyWeChat/qywxConfigList/getMobileInfo/${getApp().globalData.setting.stoid}/${openuserid}/${this.data.phone}`, { data: {} })
    console.log('获取数据库表');
    console.log(res);
    if (res.data && res.data.code == 0) {
      this.setData({
        qr_code: res.data.data.qrcode
      })
      wx.hideLoading()
    } else {
      this.getqy()
    }

  },
  async saveqy(config_id, qrcode) {
    let openuserid = this.data.openuserid
    let mobile = this.data.phone
    let addtime = ((Date.now()) / 1000).toFixed(0)
    let req_data = {
      store_id: getApp().globalData.setting.stoid,
      openuserid,
      config_id,
      qrcode,
      mobile,
      addtime
    }
    let res = await getApp().request.promisePost(`/api/weshop/qyWeChat/qywxConfigList/save`, {
      data: req_data,
      // is_json: 1
    })
    // wx.hideLoading()
  },

  //-- 会员授权 --
  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;
                    }
                  })


                  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;
    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) {

      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;
          wx.redirectTo({
            url: "/packageA/pages/profile/profile?is_back=1"
          })
        }
      })

    } else {
      if (th.data.is_lable_set) {
        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;
            wx.redirectTo({
              url: "/packageE/pages/user/labels/labels?pageType=1"
            })
          }
        })
      } else {
        this.setData({ sub: 1 });
        wx.showLoading({
          title: '处理中.',
          mask: true
        })
        this.zu_ce(dd); //调用注册的函数
      }
    }

  },

  zu_ce: function (dd) {
    var th = this;
    app.request.get("/api/weshop/users/thirdLogin", {
      data: dd,
      success: function (e) {
        if (e.data.code == 0) {
          app.globalData.user_id = e.data.data.user_id;
        }
        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;
          }
        })

      },
      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;
                  }
                })


                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 isAgree = null;
    if (e.detail.value[0]) {
      isAgree = true;
    } else {
      isAgree = false;
    };
    // this.data.isAgree = isAgree;
    this.setData({
      isAgree,
    });
  },


  //通过路径跳转到其他页面
  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();
      }
    })

  },


})
