<template>
  <!-- 登录 -->
  <div class="login">
    <s-header :name="sys ? sys.title : $t('public.sysName')" :noback="true"></s-header>
    <div class="loginLogoBox l-re">
      <div class="loginLogo"></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="userPhone" name="userPhone" label="" placeholder="请输入手机号"
          :rules="[{ required: true, message: '请输入手机号' }]" />
        <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 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, Dialog, Button } from "vant";
// import { login, getSys } from "@/service/login";
import { login } from "@/service/login";
import { setLocal, styleUrl } from "@/common/js/utils";
import sHeader from "@/components/SimpleHeader";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

export default {
  setup() {
    const { t } = useI18n();
    const checked = ref(false); // 是否记住密码状态
    const userPhone = ref('');
    const userPwd = ref("");
    const router = useRouter();
    const route = useRoute();
    const sys = ref(null);
    // 页面初始化
    onMounted(() => {
      // 加载样式
      styleUrl('login');
      if (route.query.relation_admin_id) {
        // getSysFun();
      }
      const savedCredentials = localStorage.getItem('savedCredentials');
      if (savedCredentials) {
        checked.value = true;
        const { savedUserPhone, savedPassword } = JSON.parse(savedCredentials);
        userPhone.value = savedUserPhone;
        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 showPopover = ref(false);

    // 登录
    const onSubmit = async (values) => {
      let loginParam = {
        phone: values.userPhone,
        password: md5(values.userPwd),
      }
      const { data } = await login(loginParam);
      
      console.log("记住密码?", checked.value);
      console.log("data.code", data.code);
      if (data.code === "00000") {
        setLocal("loginUser", JSON.stringify(data.data));
        if (checked.value) {
          const savedCredentials = JSON.stringify({ savedUserPhone: values.userPhone, savedPassword: values.userPwd });
          localStorage.setItem('savedCredentials', savedCredentials);
        } else {
          const savedCredentials = localStorage.getItem('savedCredentials');
          if (savedCredentials) {
            localStorage.removeItem('savedCredentials', savedCredentials);
          }
        }
        showSuccessToast(t('login.loginSucess'));
        localStorage.setItem('firstLogin', true);

        // 需要刷新页面，否则 axios.js 文件里的 token 不会被重置
        window.location.href = '/shenze/';
        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 isInWeChat = computed(() => {
      const ua = window.navigator.userAgent.toLowerCase();
      return new RegExp('micromessenger').test(ua);
    });


    return {
      checked,
      userPhone,
      userPwd,
      onSubmit,
      registerClick,
      forgetPassword,
      sys,
      isInWeChat,
      state,
      showPopover,
    };
  },
  components: {
    sHeader,
    [Button.name]: Button,
    [Dialog.name]: Dialog
  },
};
</script>

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