<template>
  <div class="sld_login">
    <div class="sld_login_header">
      <div class="content">
        <nuxt-link tag="a" class="l_logo" :to="'/'">
          <img
            class="img"
            :src="
              filtersStore.getSiteLogo ? filtersStore.getSiteLogo : defaultImg
            "
            :onerror="defaultImg"
            alt
          />
        </nuxt-link>
        <div class="r_register_wrap">
          {{ L["还没注册？"] }}
          <a
            class="go_register_btn"
            href="javascript:void(0)"
            @click="goToPage('/register')"
            >{{ L["去注册"] }}</a
          >
        </div>
      </div>
    </div>
    <div class="sld_login_content">
      <img
        class="bg"
        :src="ImgBG ? ImgBG : configInfo.main_user_logon_bg + ''"
        :onerror="defaultBgImg"
        alt
      />
      <div class="login">
        <div class="login_box">
          <div class="top">
            <div class="item1">{{ L["账号登录"] }}</div>
          </div>
          <LoginEmail ref="loginEmail" v-if="appType === 'user'" :loginLoding="loginLoding" @login="login" />
          <LoginPhone ref="loginPhone" v-if="appType === 'distributor'" :loginLoding="loginLoding" @login="login" />
          <div
            :class="{
              bottom: true,
              flex_row_between_center: wxEnable == 0,
              flex_row_end_center: wxEnable != 0,
            }"
          >
            <a href="javascript:void(0)" @click="goToPage('/register')">{{
              L["立即注册"]
            }}</a>
            <router-link tag="a" :to="`/member/login/forget`">{{
              L["忘记密码"]
            }}</router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
// import { lang_zn } from "@/assets/language/zh";
import { getCurLanguage } from "@/composables/common.js";
import { useUserInfo } from "@/store/user.js";
import { useFiltersStore } from "@/store/filter.js";
const configInfo = useUserInfo();
const filtersStore = useFiltersStore();

const loginEmail = ref();
const loginPhone = ref()

const config = useRuntimeConfig();
const appType = config.public.appType;

const L = getCurLanguage();
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
// const keyEnter = ref(true);
const loginLoding = ref(false)

const defaultImg = ref("/common_top_logo.png");
const defaultBgImg = ref("/login_bg.png");
const fromurl = ref("");
const wxEnable = ref("");
const ImgBG = ref("");

useHead({
  title: "Login",
  meta: [
    {
      name: "description",
      content: "Login",
    },
    {
      name: "keywords",
      content: "Login",
    },
  ],
});

// //由于这里的回车键触发事件和商品搜索框的回车键触发事件冲突，引入keyEnter变量判断
// if (process.client) {
//   document.onkeydown = function () {
//     var key = window.event.keyCode;
//     if (key == 13 && keyEnter.value) {
//       // login();
//     }
//   };
// }

//获取背景图
const getBg = () => {
  get("v3/system/front/setting/getSettings?names=main_user_logon_bg").then(
    (res) => {
      ImgBG.value = res.data[0];
    }
  );
};
getBg();

const login = (param) => {
  loginLoding.value = true;
  post("v3/frontLogin/oauth/token", param)
    .then((res) => {
      if (res.state == 200) {
        //将用户信息存缓存，并跳转到首页
        filtersStore.setLoginStatus(true);
        filtersStore.setToken(res.data.access_token);
        filtersStore.setRefreshToken(res.data.refresh_token);
        filtersStore.setTime(new Date().getTime().toString()); //存储refresh_token更新时间
        //获取用户信息，并同步信息到pinia

        get("v3/member/front/member/getInfo").then((res) => {
          if (res.state == 200) {
            filtersStore.setMemberInfo(res.data);
            router.replace({
              path: "/",
            });
            localStorage.setItem("isLoggedIn", "true");
            setTimeout(() => {
              localStorage.removeItem("isLoggedIn");
            }, 200);
          }
        });
      } else {
        //提示错误
        const instance = appType === 'user' ? loginEmail.value : loginPhone.value;
        instance.updateErrorMsg(res.msg)
      }
    })
    .finally(() => {
      loginLoding.value = false;
    });
};

//通过replace方式跳转页面
const goToPage = (type) => {
  router.replace({
    path: type,
  });
};

onMounted(() => {
  if (route.query.redirectUrl) {
    fromurl.value =
      window.location.origin + decodeURIComponent(route.query.redirectUrl);
  } else {
    fromurl.value = window.location.origin;
  }

  if (route.query.error) {
    ElMessage.error(decodeURIComponent(route.query.error));
  }
});

</script>
<style lang="scss" scoped>
@import "@/assets/style/register.scss";
:deep(.center) {
  padding: 30px 30px 40px;

  .item {
    position: relative;
    margin-top: 15px;
    border-radius: 2px;

    &:first-child {
      margin-top: 0;
    }

    .icon {
      position: absolute;
      left: 1px;
      top: 1px;
      width: 50px;
      text-align: center;
      height: 38px;
      background: #f8f8f8;

      .input {
        border: 1px solid #e8e8e8;
        height: 40px;
        padding: 0 44px 0 60px;
        width: 326px;
      }
    }

    .input {
      border: 1px solid #e8e8e8;
      height: 40px;
      padding: 0 44px 0 60px;
      width: 326px;
    }
  }

  .cancel {
    position: absolute;
    right: 0;
    top: 1px;
    width: 44px;
    height: 38px;
    cursor: pointer;

    :before {
      position: absolute;
      top: 9px;
      left: 14px;
    }
  }

  .error {
    margin-top: 10px;
    position: relative;
    color: $colorMain;
    height: 16px;
    line-height: 16px;
  }

  .submit {
    margin-top: 35px;
    background: $colorMain;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    width: 100%;
    height: 45px;
    font-size: 18px;
    letter-spacing: 0px;

    &:hover {
      opacity: 0.9;
    }

    &.disabled {
      background-color: #909399;
    }
  }
}
</style>
