import authApi from "@/api/address.api";
import { mapMutations } from "vuex";
import { mpConfig } from "@/utils/mpConfig/types";
import { saLogin, saTrackEvent } from "@/utils/sa.js";
import { onLaunchSubmit } from "@/utils/subscribe";
import adApi from "@/api/ad.api";
import { mapState } from "vuex";
import { smTrackEvent } from "@/utils/shumei";
export default {
  data() {
    return {
      loginBtnText: mpConfig.loginBtnText,
      loginData: {}
    };
  },
  created() {
    // #ifdef MP-WEIXIN
    this.setGDTVID();
    this.getLoginCode(); // 微信初始化调用一次
    // #endif
  },
  computed: {
    ...mapState({
      gdt_vid: state => state.ad.gdt_vid
    })
  },
  methods: {
    async setGDTVID() {
      const openId = uni.getStorageSync("openid");
      if (!this.gdt_vid || !openId) return;
      await adApi.saveGDTVID({
        clickId: this.gdt_vid,
        wechatOpenId: openId
      });
    },
    async getGDTVID() {
      const openId = uni.getStorageSync("openid");
      if (!openId) return;
      const [res, err] = await adApi.getGDTVID(openId);
      if (err) return;
      return res;
    },
    async uploadTencentAdData() {
      const openId = uni.getStorageSync("openid");
      const gdt_vid = await this.getGDTVID();
      // 注册上报
      if (!gdt_vid || !openId) return;
      await adApi.uploadAdData({
        clickId: gdt_vid,
        wechatOpenid: openId,
        actionType: "REGISTER"
      });
    },

    async getPhoneNumber(e) {
      this.uploadSaLoginBtnClick();
      const loginCode = await this.getLoginCode();
      if (e.detail.errMsg == "getPhoneNumber:ok") {
        this.miniAppLogin(loginCode, e.detail);
      }
    },
    /***************************************************************/
    /********************** 支付宝登录相关 ****************************/
    async getAlipayPhoneNumber() {
      this.uploadSaLoginBtnClick();
      const result = await this.onGetAuthorize();
      console.log("result===============>", result);
      const loginCode = await this.getLoginCode();
      if (result.response) {
        this.miniAppLogin(loginCode, { encryptedData: result.response });
      }
    },
    uploadSaLoginBtnClick() {
      try {
        const le_channel_code = uni.getStorageSync("vccChannel") || "";
        saTrackEvent("MINI_LoginBtnClick", {
          le_channel_code,
          le_login_type: "微信授权登录"
        });
      } catch (err) {
        console.log(err);
      }
    },
    onGetAuthorize() {
      return new Promise((resolve, reject) => {
        uni.getPhoneNumber({
          success: res => {
            resolve(JSON.parse(res.response));
          },
          fail: res => {
            console.log(res);
            reject(res);
          }
        });
      });
    },
    /********************** 支付宝登录相关 ****************************/
    /***************************************************************/
    getLoginCode() {
      return new Promise(resolve => {
        // #ifdef MP-BAIDU
        uni.getLoginCode({
          success: res => {
            resolve(res.code);
          },
          fail: err => {
            console.log("getLoginCode====================> fail", err);
          }
        });
        // #endif

        // #ifdef MP-WEIXIN || MP-ALIPAY
        uni.login({
          provider: mpConfig.provider,
          // #ifdef MP-ALIPAY
          scopes: "auth_base",
          // #endif
          success: res => {
            resolve(res.code);
          },
          fail: err => {
            console.log("login====================> fail", err);
          }
        });
        // #endif
      });
    },
    async miniAppLogin(opt, ueserPhoneData) {
      // 登录接口
      const [userinfo] = await authApi.login({ code: opt });
      this.loginData = userinfo;
      if (userinfo) {
        userinfo.openid && uni.setStorageSync("openid", userinfo.openid);
        if (userinfo.token) {
          this.saveUserAuthInfo(userinfo);
          this.$ry?.loggedin(userinfo.uuid);
          this.setLoginInfoToStore(userinfo, true);
          smTrackEvent({
            eventId: "login",
            type: "signupPlatform"
          });
        } else {
          this.registerApp({
            // #ifdef MP-ALIPAY
            cursor: userinfo.cursor,
            // #endif

            // #ifndef MP-ALIPAY
            openid: userinfo.openid,
            unionId: userinfo.unionId || "",
            iv: ueserPhoneData.iv,
            // #endif
            encryptedData: ueserPhoneData.encryptedData
          });
        }
      } else {
        const le_channel_code = uni.getStorageSync("vccChannel") || "";
        saTrackEvent("MINI_LoginEvent", {
          le_is_login_success: false,
          le_login_type: "微信授权登录",
          le_channel_code,
          le_failure_code: "",
          le_failure_message: "登录失败"
        });
      }
    },
    async registerApp(opt) {
      // 注册
      const [userinfo] = await authApi.register(opt);
      if (userinfo) {
        this.loginData = userinfo;
        userinfo.openid && uni.setStorageSync("openid", userinfo.openid); // 注册的时候不会返回openid，只会返回token
        userinfo.unionId && uni.setStorageSync("unionid", userinfo.unionId);
        this.$ry?.register(userinfo.uuid);
        this.setLoginInfoToStore(userinfo, false);
        smTrackEvent({
          eventId: "login",
          type: "signupPlatform"
        });
      }
    },
    async setLoginInfoToStore(userinfo) {
      uni.setStorageSync("token", userinfo.token);
      uni.setStorageSync("phone", userinfo.phoneNo);
      uni.setStorageSync("userAuthInfo", userinfo);
      /* #ifdef MP-ALIPAY */
      uni.setStorageSync("thirdUserId", userinfo.thirdUserId);
      /* #endif */
      saLogin(userinfo.uuid);
      this.loginType && uni.$emit("login", true);
      this.close && this.close();
      // const saEvent = isLogin ? "MINI_LoginEvent" : "MINI_RegisterEvent";
      const le_channel_code = uni.getStorageSync("vccChannel") || "";
      saTrackEvent("MINI_LoginEvent", {
        le_is_login_success: true,
        le_login_type: "微信授权登录",
        le_channel_code,
        le_failure_code: "",
        le_failure_message: ""
      });
      // #ifdef MP-WEIXIN
      await this.setGDTVID();
      await this.uploadTencentAdData();
      this.isGetUserInfo(userinfo); // 由于获取头像功能当时只是支持百人团项目，其他平台登录无需走此逻辑
      onLaunchSubmit(); // 订阅消息上报，只针对微信
      // #endif
      // #ifndef MP-WEIXIN
      this.subscribeConfirm && this.subscribeConfirm(); // 直接返回
      // #endif
    },
    isGetUserInfo(userinfo) {
      const tenantId = +uni.getStorageSync("tenantId");
      if (tenantId === 560761) {
        // 羊小咩走正常授权头像、订阅消息逻辑
        if (!userinfo.hasAvatar) {
          this.showAuthModal();
        } else {
          this.$refs["subscribe-dialog"].open();
        }
      } else {
        // 其他租户直接返回
        return uni.navigateBack();
      }
    },
    // 打开用户信息授权框
    showAuthModal() {
      this.$refs["authPopup"].open();
    },
    // 获取用户信息回调
    handleUserInfo(e) {
      const loginData = this.loginData;
      this.getAvatar({
        openid: loginData.openid,
        userId: loginData.userId,
        ...e
      });
    },
    // 如果用户信息取消则是否正常进行后面的授权，待确认
    handleUserClose() {
      this.$refs["subscribe-dialog"].open();
    },
    async getAvatar(opt) {
      try {
        // 发送头像信息成功之后走后面授权流程
        await authApi.getAvatar(opt);
        this.$refs["subscribe-dialog"].open();
      } catch (err) {
        console.log(err);
      }
    },
    ...mapMutations(["saveUserAuthInfo"])
  }
};
