import { encode } from "js-base64";
import settingConfig from "@/settings";
import QRcode from "qrcode";

function getUrlParams(url) {
  let result = {};
  if (url) {
    let urlStr = url.split("?")[1];
    const urlSearchParams = new URLSearchParams(urlStr);
    result = Object.fromEntries(urlSearchParams.entries());
  }
  return result;
}

export default {
  name: "Login",
  props: {
    lang: [String, Function],
  },
  components: {},
  data() {
    return {
      isCounting: false,
      countdown: 0,
      buttonText: this.$t1("获取验证码"),
      smsTimer: null,
      isRememberPassword: false,
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          {
            required: true,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
          },
        ],
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      // isChangeBackground: false,
      backgroundClass: "",
      hasLogin: false,
      showView: false,
      loginForm2: {
        username: null,
        smsCode: null,
      },
      activeName: "first",
      searchParam: {},
      showContent: true,

      qrTimer1: null,
      qrTimer2: null,
      qrContent: null,
      qrCodeFlag: 0,
      qrBase64: "",
      settingConfig: settingConfig,
      qrExpired: false,
      loginConfig: {},
      imageUrl: "",
      loginMethod: "",

      accountLoagin: true,
      phoneLogin: false,
      qrLogin: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  beforeDestroy() {
    this.clearQrLoginTimer();
    this.clearSmsTimer();
  },
  created() {
    this.init();
  },
  mounted() {
    // if (this.loginForm.username === '') {
    //   this.$refs.username.focus();
    // } else if (this.loginForm.password === '') {
    //   this.$refs.password.focus();
    // }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
    window.removeEventListener("keydown", this.keyDown, false);
  },
  methods: {
    handleLoginConfig() {
      let loginConfig = this.$store.getters.loginConfig || {};
      this.loginConfig = loginConfig;
      this.initImage();
      this.initLoginMethod();
    },
    initImage() {
      //初始化登录图片
      let loginConfig = this.loginConfig;
      if (loginConfig?.attachments?.length) {
        this.imageUrl =
          loginConfig.attachments[0].domain + loginConfig.attachments[0].source;
      }
    },

    initLoginMethod() {
      let loginConfig = this.loginConfig?.login_method;
      if (loginConfig?.length) {
        this.accountLoagin = loginConfig.includes(1);
        this.phoneLogin = loginConfig.includes(2);
        this.qrLogin = loginConfig.includes(3);
        if (this.accountLoagin) {
          this.activeName = "first";
        } else if (this.phoneLogin) {
          this.activeName = "second";
        } else if (this.qrLogin) {
          this.activeName = "third";
          this.$nextTick(() => {
            this.initQR();
          });
        }
      } else {
        this.accountLoagin = true;
        this.phoneLogin = settingConfig.mobileLoginEnabled;
        this.qrLogin = settingConfig.qrLoginEnabled;
      }
    },
    initLang() {
      let lang = this.$route.query.lang;
      if (!lang && !!this.lang) {
        if (typeof this.lang === "function") {
          lang = this.lang();
        } else {
          lang = this.lang;
        }
      }
      if (lang) {
        this.$i18n.locale = lang;
        localStorage.setItem("i18n-lang", lang);
      }
    },
    init() {
      this.initLang();
      this.handleLoginConfig();
      let searchParam = getUrlParams(location.search);
      this.searchParam = searchParam;
      //小熊SSO返回判断--目前因为小熊单点返回ticket有问题要特殊处理
      let ssoParams = {};
      if (location.search) {
        ssoParams = searchParam;
      }
      // 获取URL参数
      const urlParams = this.$route.query;
      if (
        ssoParams.ticket ||
        "bear_portalsso" == urlParams.access ||
        urlParams.ticket
      ) {
        //小熊单点登录
        this.bearSsoLogin();
      } else if (searchParam.gatewayToken) {
        this.showContent = false;
        this.handleGatewayTokenLogin();
      } else if (searchParam.xtoken) {
        this.showContent = false;
        this.handleXTokenLogin();
      } else {
        //正常登陆
        this.login();
      }
    },
    keyDown(e) {
      //如果是回车则执行登录方法
      if (e.keyCode == 13 && e.target.nodeName != "INPUT") {
        let closeBtn = document.querySelector(".el-dialog__close");
        closeBtn && closeBtn.click();
        if (this.activeName == "third") return;
        this.handleLogin();
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    handleLogin() {
      let loadingObj = null;
      let reqData = {};
      if (this.activeName == "first") {
        //账号密码登录
        loadingObj = this.$baseLoading();
        let password = encode(this.loginForm.password + "");
        reqData = { username: this.loginForm.username, password: password };
      } else {
        //手机验证码登录
        let username = this.loginForm2.username;
        let smsCode = this.loginForm2.smsCode;
        if (!username || !smsCode) {
          this.$baseAlert(this.$t1("请输入手机号和验证码"));
          return;
        }
        loadingObj = this.$baseLoading();
        reqData = { username: username, smsCode: smsCode, mode: "sms" };
      }

      if (settingConfig.i18nEnabled) {
        //登录传语种到后台
        let language = this.$i18n?.locale;
        if (language && language != "zh") {
          reqData.language = language;
        }
      }

      this.$store
        .dispatch("user/login2", reqData)
        .then((res) => {
          setTimeout(function () {
            loadingObj.close();
          }, 200);
          if (res.type == "success") {
            localStorage.removeItem("currentMenuId");
            this.rememberPassword();
            /*this.$router.push({
              path: '/'
            });*/
            this.loading = false;
            window.removeEventListener("keydown", this.keyDown, false);
            this.handleRedirectUrl();
          } else {
            setTimeout(function () {
              loadingObj.close();
            }, 200);
          }
        })
        .catch((e) => {
          this.loading = false;
          setTimeout(function () {
            loadingObj.close();
          }, 200);
          console.error(e);
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    initPassword() {
      var u = localStorage.getItem("login_info");
      var login_info;
      if (u) {
        login_info = JSON.parse(u);
        var username = login_info.username;
        var password = login_info.password;
        var isRememberPassword = login_info.isRememberPassword;
        if (isRememberPassword == "true") {
          this.isRememberPassword = true;
          this.loginForm.username = username;
          this.loginForm.password = password;
        }
      }
    },
    rememberPassword() {
      if (this.isRememberPassword) {
        var username = this.loginForm.username;
        var password = this.loginForm.password;
        var login_info = {
          username: username,
          password: password,
          isRememberPassword: "true",
        };
        localStorage.setItem("login_info", JSON.stringify(login_info));
      } else {
        localStorage.removeItem("login_info");
      }
    },
    changeBackground() {
      if (
        location.host.indexOf("pcp.sc.5mall.com") >= 0 ||
        location.host.indexOf("pip.bears.com.cn") >= 0
      ) {
        this.backgroundClass = "pcp";
      } else if (location.host.indexOf("chigo.sc.5mall.com") >= 0) {
        this.backgroundClass = "chigo";
      } else {
        this.backgroundClass = "tc";
      }
    },
    login() {
      let url = window.MAIN_WEB_PREFIX + "/index.html/#/login";
      if (
        self != top &&
        (process.env.NODE_ENV == "development" || self.host == parent.host)
      ) {
        parent.location.href = url;
      } else if (
        process.env.NODE_ENV !== "development" &&
        window.MAIN_WEB_PREFIX &&
        window.MAIN_WEB_PREFIX != window.WEB_PREFIX
      ) {
        window.location.href = url;
      }
      /* let lang = this.$route.query.lang;
      if(lang=="en-US"){
        changeLocale(lang);
      }else{
        changeLocale("zh-CN");
      } */
      // window.addEventListener('storage', this.afterQRScan)

      window.removeEventListener("keydown", this.keyDown, false);
      window.addEventListener("keydown", this.keyDown, false);
      this.changeBackground();
      this.initPassword();
      this.showView = true;
    },
    bearSsoLogin() {
      //小熊SSO返回判断--目前因为小熊单点返回ticket有问题要特殊处理
      let urlParams = {};
      if (location.search) {
        urlParams = getUrlParams(location.search);
      }
      //let urlParams = this.$route.query;

      // 获取URL参数
      console.log("urlParams", urlParams);
      const loginPath = process.env.VUE_APP_BASE_API;
      console.log("loginPath--->", loginPath);

      //&& loginPath ===window.location.href
      if (urlParams.ticket) {
        console.log("进入回调方法=================");
        this.$store.dispatch("user/clearToken");
        this.$http({
          url: USER_PREFIX + "/auth/idmLogin",
          method: `post`,
          data: { ticket: urlParams.ticket },
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            let token = res.objx;
            console.log("token", token);
            this.$store.dispatch("user/addToken", { token }).then((res) => {
              localStorage.removeItem("currentMenuId");
              this.rememberPassword();
              /*this.$router.push({
                path: '/'
              });*/
              this.loading = false;
              window.removeEventListener("keydown", this.keyDown, false);
              let redirect = sessionStorage.getItem("loginRedirect");
              this.handleRedirectUrl(redirect);
            });
          },
          fail: () => {
            this.showView = true;
          },
          error: () => {
            this.showView = true;
          },
        });
      } else {
        console.log("进入单点方法");
        let redirect = this.$route.query.redirect || "";
        this.$http({
          url: USER_PREFIX + "/auth/idmLoginUrl",
          method: `post`,
          data: {},
          isLoading: true,
          modalStrictly: true,
          success: (res) => {
            sessionStorage.setItem("loginRedirect", redirect);
            location.href = res.objx;
            // location.href = res.objx+"&redirect="+redirect;
          },
          fail: () => {
            this.showView = true;
          },
          error: () => {
            this.showView = true;
          },
        });
      }
    },
    sendCode() {
      if (this.isCounting) {
        return;
      }
      let mobile = this.loginForm2.username;
      if (!mobile) {
        this.$baseAlert("请输入手机号");
        return;
      }

      this.$http({
        url: USER_PREFIX + "/auth/sendSmsCode",
        method: `post`,
        data: { mobile: mobile },
        isLoading: true,
        success: (res) => {
          this.$message({
            message: res.content,
            type: "success",
            duration: 1500,
          });
          this.isCounting = true;
          this.countdown = 60;
          this.buttonText = this.$t1("60秒后重新获取");
          this.clearSmsTimer();
          this.smsTimer = setInterval(() => {
            this.countdown--;
            this.buttonText = this.$t1("{time}秒后重新获取", {
              time: this.countdown,
            });
            if (this.countdown == 0) {
              this.clearSmsTimer();
              this.isCounting = false;
              this.buttonText = this.$t1("获取验证码");
            }
          }, 1000);
        },
      });
    },
    clearSmsTimer() {
      if (this.smsTimer) {
        clearInterval(this.smsTimer);
        this.smsTimer = null;
      }
    },
    mobileLogin() {},
    handleRedirectUrl(redirect) {
      redirect = redirect || this.$route.query.redirect;
      let path = null;
      if (redirect && redirect.startsWith("/outLinkView")) {
        path = this.addParamToUrl(redirect, "hasToken", "true");
      } else {
        path = "/";
      }
      this.getWebPrefix((webPrefix) => {
        let prefix = webPrefix ? "/" + webPrefix : "";
        let ssotoken = this.searchParam.gatewayToken;
        let xtoken = this.searchParam.xtoken;
        if (prefix && prefix !== window.WEB_PREFIX) {
          location.href = prefix + "/index.html" + path;
        } else if (!!ssotoken || !!xtoken) {
          prefix = prefix || window.WEB_PREFIX;
          location.href = prefix + "/index.html" + path;
        } else {
          this.$router.push({
            path: path,
          });
        }
      });
      /*if (redirect && redirect.startsWith("/outLinkView")) {
        let path = this.addParamToUrl(redirect, "hasToken", "true");
        this.$router.push({
          path: path
        });
      } else {
        this.$router.push({
          path: '/'
        });
      }*/
    },
    addParamToUrl(url, paramKey, paramValue) {
      var regex = new RegExp("([?&])" + paramKey + "=.*?(&|$)", "i");
      if (url.match(regex)) {
        url = url.replace(regex, "$1" + paramKey + "=" + paramValue + "$2");
      } else {
        url +=
          (url.indexOf("?") === -1 ? "?" : "&") + paramKey + "=" + paramValue;
      }
      return url;
    },
    getWebPrefix(callback) {
      this.$http({
        url: USER_PREFIX + "/auth/getWebPrefix",
        method: `post`,
        data: {},
        isLoading: true,
        success: (res) => {
          let webPrefix = res.objx;
          callback && callback(webPrefix);
        },
      });
    },
    handleGatewayTokenLogin() {
      let ssotoken = this.searchParam.gatewayToken;
      let companycode = this.searchParam.entCode;
      this.$store
        .dispatch("user/login2", { ssotoken, companycode })
        .then((res) => {
          if (res.type == "success") {
            this.$nextTick(() => {
              this.handleRedirectUrl();
            });
          }
        });
    },
    handleXTokenLogin() {
      let xtoken = this.searchParam.xtoken;
      let companycode = this.searchParam.entCode;
      this.$store
        .dispatch("user/login2", { xtoken, companycode })
        .then((res) => {
          if (res.type == "success") {
            this.handleRedirectUrl();
          }
        });
    },
    /**二维码登录begin*/
    guid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (t) {
          var e = (16 * Math.random()) | 0;
          return ("x" == t ? e : (3 & e) | 8).toString(16);
        }
      );
    },
    initQR() {
      this.clearQrLoginTimer();
      this.qrExpired = true;
      let option = { width: 300, height: 300 };
      this.qrContent = this.guid();
      this.createQR(this.qrContent, option).then((url) => {
        this.qrExpired = false;
        this.qrBase64 = url;
        this.createQrLoginTimer();
      });
    },
    // 生成二维码
    createQR(content, options) {
      return new Promise((resolve, reject) => {
        QRcode.toDataURL(content, options).then((url) => {
          resolve(url);
        });
      });
    },
    changeTab() {
      // this.initQR();
      // return
      if (this.activeName == "third") {
        this.initQR();
      } else {
        this.clearQrLoginTimer();
      }
    },
    clearQrLoginTimer() {
      if (this.qrTimer1) {
        clearTimeout(this.qrTimer1);
        this.qrTimer1 = null;
      }
      if (this.qrTimer2) {
        clearTimeout(this.qrTimer2);
        this.qrTimer2 = null;
      }
    },
    createQrLoginTimer() {
      this.checkQrLoginTimerHanlde();
      this.qrTimer2 = setTimeout(() => {
        this.qrExpired = true;
        this.clearQrLoginTimer();
      }, 60000);
    },
    checkQrLoginTimerHanlde() {
      this.qrTimer1 = setTimeout(() => {
        this.checkQrLoginStatusHanlde();
      }, 3000);
    },
    checkQrLoginStatusHanlde() {
      if (this.qrExpired) {
        return;
      }
      this.$http({
        url: USER_PREFIX + "/auth/login",
        method: `post`,
        data: { as: this.qrContent },
        // isLoading: true,
        failMsg: false,
        success: (res) => {
          let token = res.objx;
          if (token) {
            this.$message({
              message: this.$t1("登录成功"),
              type: "success",
            });
            this.clearQrLoginTimer();
            this.$store.dispatch("user/addToken", { token }).then((res) => {
              localStorage.removeItem("currentMenuId");
              this.rememberPassword();
              this.loading = false;
              window.removeEventListener("keydown", this.keyDown, false);
              this.handleRedirectUrl();
            });
          } else {
            this.checkQrLoginTimerHanlde();
          }
        },
      });
    },
    /**二维码登录end*/
  },
};
