<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>
          <div class="center">
            <div class="item account">
              <span
                style="color: #bbb; font-size: 19px; padding-top: 7px"
                class="icon iconfont icon-wode"
              ></span>
              <input
                type="text"
                v-model="name"
                :placeholder="L['请输入邮箱']"
                class="input"
                autocomplete="off"
              />
              <div
                data-type="userName"
                class="cancel"
                @click="clearInputVal('name')"
              >
                <span style="color: #bbb" class="iconfont icon-cuowu"></span>
              </div>
            </div>
            <div class="item password">
              <span
                style="color: #bbb; font-size: 21px; padding-top: 7px"
                class="icon iconfont icon-mima1"
              ></span>
              <input
                type="password"
                v-model="password"
                :placeholder="L['请输入密码']"
                class="input"
                autocomplete="new-password"
              />
              <div
                data-type="password"
                class="cancel"
                @click="clearInputVal('password')"
              >
                <span style="color: #bbb" class="iconfont icon-cuowu"></span>
              </div>
            </div>

            <div class="error">
              <span
                v-if="errorMsg"
                style="color: #e1251b; font-size: 14px"
                class="iconfont icon-jubao"
              ></span>
              {{ errorMsg }}
            </div>
            <el-button
              @click="login"
              :class="{ submit: true, disabled: loginDisabled }"
              :disabled="loginDisabled"
              :loading="loginLoding"
              >{{ L["登录"] }}</el-button
            >
          </div>
          <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 isLoading = ref(false);

// const L = lang_zn;
const L = getCurLanguage();
const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const keyEnter = ref(true);
const errorMsg = ref(); //错误提示
const name = ref(""); //账户
const password = ref(""); //密码
const loginType = ref(1); //登陆类型：1-账号密码登陆，2-手机验证码登陆
const defaultImg = ref("/common_top_logo.png");
const defaultBgImg = ref("/login_bg.png");
const fromurl = ref("");
const wxEnable = ref("");
const pwdCalc = ref();
const ImgBG = ref("");
const loginLoding = ref(false);

const loginDisabled = computed(() => !name.value || !password.value);
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 = () => {
  let param = {};
  param.username = name.value;
  param.password = password.value;
  param.loginType = loginType.value;

  //账号验证
  if (!param.username) {
    errorMsg.value = L["请输入账号"];
    return false;
  }

  //密码校验
  if (!param.password) {
    errorMsg.value = L["请输入密码"];
    return false;
  } else {
    pwdCalc.value = checkPwd(param.password);
    if (pwdCalc.value !== true) {
      errorMsg.value = pwdCalc.value;
      return false;
    }
  }

  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);
            if (window.history.state.back) {
              // if(window.history.state.back == '/register' || window.history.state.back == '/member/login/forget' || window.history.state.back == '/member/login/forget' || window.history.state.back == '/member/login/forget'){
              window.location.href = "/";
              // }else{
              //   window.location.href = window.history.state.back;
              // }
            } else {
              router.replace({ path: "/member/home" });
            }
          }
        }).catch(err => {
          loginLoding.value = false;
        })
    } else {
      //提示错误
      errorMsg.value = res.msg;
    }
  });
};
//清空输入框内容
const clearInputVal = (type) => {
  if (type == "name") {
    name.value = "";
  } else if (type == "password") {
    password.value = "";
  }
};
//登录方式切换
const changeLoginType = (type) => {
  loginType.value = type;
  name.value = "";
  password.value = "";
  errorMsg.value = "";
};

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

watch([name, password], () => {
  if (loginType.value == 1) {
    password.value = password.value.substring(0, 20);
    // name.value = memberEmail.value.substring(0, 20)
  } else {
    password.value = password.value.substring(0, 6);
    // name.value = memberEmail.value.substring(0, .gitignore)
  }

  if (password.value || name.value) {
    errorMsg.value = "";
  }
});

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

// onBeforeRouteLeave(() => {
//   keyEnter.value = false;
// });
</script>
<style lang="scss" scoped>
@import "@/assets/style/register.scss";
.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>
