<template>
  <!-- 登录 -->
  <div class="login">
    <s-header
        :name="sys ? sys.title : $t('public.sysName')"
    ></s-header>
    <div class="loginLogoBox l-re">
      <div class="loginLogo"></div>
      <div class="l-ab pointer languageCon" @click="languageClk">
        <div class="c-text-b">
          {{ compLang }}
        </div>
      </div>
    </div>
    <div class="loginTitleBox l-flex-center">
      <span class="loginTitle">{{ $t("login.title") }}</span>
    </div>
    <div class="loginFormBox">
      <van-form @submit="onSubmit">
        <van-field
            v-model="userName"
            name="userName"
            label=""
            :placeholder="$t('login.userNameInput')"
            :rules="[{ required: true, message: $t('login.userNameInput') }]"
        />
        <van-field
            v-model="userPwd"
            type="password"
            name="userPwd"
            label=""
            :placeholder="$t('login.passWordInput')"
            :rules="[{ required: true, message: $t('login.passWordInput') }]"
        />
        <div class="checkedPasswordBox">
          <van-checkbox icon-size="18px" class="checkedPassWord" v-model="checked">
            {{ $t("login.checkedPassWord") }}
          </van-checkbox>
          <span class="forgetPassWord" @click="forgetPassword">{{
              $t("login.forgetPassWord")
            }}</span>
        </div>
        <br>
        <br>
        <!-- 微信登录 -->
        <!-- <div v-if="isInWeChat" class="loginWithWechatClass">
          <van-button class="wechat-btn" type="primary" size="large" @click="wxLoginHandler">
            <van-icon name="wechat" color="#1bd66c" size="40" class="wechat-icon"/>
          </van-button>
        </div> -->

        <div class="buttonBox">
          <van-button
              round
              type="primary"
              class="register"
              @click="registerClick"
          >{{ $t("login.regusterButton") }}
          </van-button>
          <van-button round type="primary" native-type="submit">{{
              $t("login.loginButton")
            }}
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import md5 from "js-md5";
import {onMounted, ref, computed, reactive} from "vue";
import { showSuccessToast, showFailToast, showDialog, Dialog, Button } from "vant";
import {login, getSys, getOpenid} from "../service/login";
import {setLocal, getLocal, navigatorLanguage, styleUrl} from "../common/js/utils";
import sHeader from "../components/SimpleHeader";
import {useRoute, useRouter} from "vue-router";
import {useI18n} from "vue-i18n";
// vant 组件的中英文切换
import {Locale} from "vant";
// 引入英文语言包
import enUS from "vant/es/locale/lang/en-US";
// 引入简体中文语言包
import zhCN from "vant/es/locale/lang/zh-CN";

export default {
  setup() {
    let languageName = ref(getLocal("curLang"));
    const {locale, t} = useI18n();
    // 语言点击
    const languageClk = () => {
      if (languageName.value === "zh") {
        locale.value = "en";
        languageName.value = "en";
        setLocal("curLang", "en");
        // 切换vant语言包
        Locale.use("en-US", enUS);
      } else {
        locale.value = "zh";
        languageName.value = "zh";
        setLocal("curLang", "zh");
        // 切换vant语言包
        Locale.use("zh-CN", zhCN);
      }
    };
    const compLang = computed(() => {
      if (languageName.value === "en") {
        return "中文";
      } else {
        return "English";
      }
    });
    const checked = ref(false); // 是否记住密码状态
    const userName = ref("");
    const userPwd = ref("");
    const router = useRouter();
    const route = useRoute();
    const sys = ref(null);
    // 页面初始化
    onMounted(() => {
      // 加载样式
      styleUrl('login');
      // localStorage.clear();
      // 如果没有语言缓存
      if (!getLocal("curLang")) {
        //  根据浏览器语言重新缓存到localstorage
        setLocal("curLang", navigatorLanguage());
        languageName.value = getLocal("curLang");
      }
      if (route.query.relation_admin_id) {
        getSysFun();
      }
      const savedCredentials = localStorage.getItem('savedCredentials');
      if (savedCredentials) {
        checked.value = true;
        const { savedUsername, savedPassword } = JSON.parse(savedCredentials);
        userName.value = savedUsername;
        userPwd.value = savedPassword;
      }
    });
    const getSysFun = async () => {
      const {data} = await getSys({
        relationAdminId: route.query.relation_admin_id,
      });
      if (data.code === "00000") {
        data.data.relationAdminId = route.query.relation_admin_id;
        setLocal("loginSys", JSON.stringify(data.data));
        sys.value = data.data;
      }
    };
    // 登录
    const onSubmit = async (values) => {
      const {data} = await login({
        username: values.userName,
        password: md5(values.userPwd),
        hostName: 'Sevencloud',
      });
      if (data.code === "00000") {
        setLocal("loginUser", JSON.stringify(data.data));
        if (checked.value) {
          const savedCredentials = JSON.stringify({ savedUsername: values.userName, savedPassword: values.userPwd });
          localStorage.setItem('savedCredentials', savedCredentials);
        } else {
          const savedCredentials = localStorage.getItem('savedCredentials');
          if (savedCredentials) {
            localStorage.removeItem('savedCredentials', savedCredentials);
          }
        }
        // console.log('loginUser JSON：', JSON.stringify(data.data));
        showSuccessToast(t('login.loginSucess'));
        // 需要刷新页面，否则 axios.js 文件里的 token 不会被重置
        // window.location.href = '/';
        window.location.href = '/sc/';
        setTimeout(() => {
          router.push("/home");
        }, 200);
      } else {
        showFailToast(data.message);
      }
    };
    // 跳转注册页面
    const registerClick = async () => {
      await router.push("/register");
    };
    // 跳转忘记密码页面
    const forgetPassword = async () => {
      await router.push("/forgetpassword");
    };

    const state = reactive({
      isLoading: false
    })
    // 微信登录
    const wxLoginHandler = async () => {
      state.isLoading = true;
      try {
        // 用户静默授权，获取 用户信息
        const {data} = await getOpenid();
        console.log("微信登录:", data)
        if (data.code === "00000") {
          window.location.href = data.data;
        } else {
          showFailToast('微信登录失败：' + data.message);
        }
      } catch (error) {
        handleError(error.message || '微信登录失败，请重试');
      } finally {
        state.isLoading = false;
      }
    }

    const isInWeChat = computed(() => {
      const ua = window.navigator.userAgent.toLowerCase();
      return new RegExp('micromessenger').test(ua);
    });

    const handleError = (errMsg) => {
      showDialog({
        title: '错误提示',
        message: errMsg
      })
    }

    return {
      checked,
      userName,
      userPwd,
      onSubmit,
      registerClick,
      forgetPassword,
      sys,
      compLang,
      languageClk,
      isInWeChat,
      state,
      wxLoginHandler,
      getOpenid,

    };
  },
  components: {
    sHeader,
    [Button.name]: Button,
    [Dialog.name]: Dialog
  },
};
</script>

<style lang="less" scoped>
@import "../common/style/mixin";
</style>
