<template>
  <div class="login-container">
    <!-- 系统头部 -->
    <s-header
      :name="
        sys
          ? sys.title
          : sysTitle == 'AETI GLOBAL'
          ? sysTitle
          : $t('public.sysName')
      "
      :noback="true"
    />

    <!-- 主要内容区域 -->
    <div class="login-content">
      <!-- Logo区域 -->
      <div class="logo-section">
        <div class="logo-container">
          <img :src="logoName" alt="System Logo" class="system-logo" />
        </div>
      </div>

      <!-- 登录表单 -->
      <div class="form-container">
        <van-form @submit="onSubmit" class="login-form">
          <!-- 用户名输入 -->
          <van-field
            v-model="userName"
            name="userName"
            :placeholder="$t('login.userNameInput')"
            :rules="[{ required: true, message: $t('login.userNameInput') }]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="user-o" size="22" class="field-icon" />
            </template>
          </van-field>

          <!-- 密码输入 -->
          <van-field
            v-model="userPwd"
            name="userPwd"
            type="password"
            :placeholder="$t('login.passWordInput')"
            :rules="[{ required: true, message: $t('login.passWordInput') }]"
            class="form-field"
          >
            <template #left-icon>
              <van-icon name="lock" size="22" class="field-icon" />
            </template>
          </van-field>

          <!-- 记住密码和忘记密码 -->
          <div class="password-options">
            <div class="remember-me">
              <van-checkbox v-model="checked" shape="square" icon-size="20">
                {{ $t("login.checkedPassWord") }}
              </van-checkbox>
            </div>

            <div class="forgot-password" @click="forgetPassword">
              <span>{{ $t("login.forgetPassWord") }}</span>
              <van-icon name="arrow" size="16" />
            </div>
          </div>

          <!-- 登录按钮 -->
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            class="login-button"
          >
            {{ $t("login.loginButton") }}
          </van-button>

          <!-- 微信登录 -->
          <div v-if="isInWeChat" class="wechat-login" @click="wxLoginHandler">
            <van-button round block class="wechat-button">
              <div class="wechat-container">
                <van-icon name="wechat" size="28" class="wechat-icon" />
                <span>{{ $t("login.loginWithWechat") }}</span>
              </div>
            </van-button>
          </div>

          <!-- 注册选项 -->
          <div class="register-option">
            <span class="register-link" @click="registerClick">{{
              $t("login.regusterButton")
            }}</span>
          </div>
        </van-form>
      </div>
    </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 { loginSys, 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";
import defaultLogo from "../assets/login/logo.png";
import aetiLogo from "../assets/login/aetiLogo.png";

export default {
  setup() {
    let languageName = ref(getLocal("curLang"));
    const { t } = useI18n();
    const checked = ref(false); // 是否记住密码状态
    const userName = ref("");
    const userPwd = ref("");
    const router = useRouter();
    const route = useRoute();
    const sys = ref(null);
    const currentLan = ref(""); // 当前语言
    const logoName = ref(defaultLogo); // Logo图片名称
    const sysTitle = ref(""); // 页头标题

    // 页面初始化
    onMounted(() => {
      // 加载样式
      styleUrl("login");
      // 如果没有语言缓存
      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;
      }
      getDomainFunc();
    });

    const getDomainFunc = async () => {
      const currentDomain = window.location.href;
      // console.log("href >>>", currentDomain);
      // console.log("hostname >>>", window.location.hostname);
      switch (true) {
        case currentDomain.includes("/aeti/"): // aeti是美国孙总portalmcc.com.cn
          logoName.value = aetiLogo;
          sysTitle.value = "AETI GLOBAL";
          break;
        default:
          logoName.value = defaultLogo;
          sysTitle.value = t("public.sysName");
      }
    };

    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;
        console.log("sys.value >>>", sys.value);
      }
    };

    // 登录
    const onSubmit = async (values) => {
      const { data } = await loginSys({
        username: values.userName,
        password: md5(values.userPwd),
        hostName: "Sunzee",
      });
      console.log(checked.value);
      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);
          }
        }
        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 wxLoginHandler = async () => {
      state.isLoading = true;
      try {
        // 用户静默授权，获取 用户信息
        const { data } = await getOpenid({ hostName: "Sunzee" });
        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,
      isInWeChat,
      state,
      wxLoginHandler,
      getOpenid,
      currentLan,
      logoName,
      sysTitle,
    };
  },
  components: {
    sHeader,
    [Button.name]: Button,
    [Dialog.name]: Dialog,
  },
};
</script>

<style lang="less" scoped>
@theme-color: #4d6add;

.login-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.login-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 30px;
  // justify-content: center;
  background: #f5f6fa;
  height: calc(100% - 45px);
  overflow: auto;
  overflow-x: hidden;
}

.logo-section {
  margin-bottom: 20px;

  .logo-container {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
    box-shadow: 0 4px 20px rgba(2, 77, 163, 0.25);
    border: 2px solid rgba(2, 77, 163, 0.1);
    padding: 10px;

    .system-logo {
      width: 90%;
    }
  }
}

.form-container {
  width: 100%;
  max-width: 400px;

  .login-form {
    margin: 15px;
    background-color: white;
    border-radius: 20px;
    padding: 20px;
    box-shadow: 0 8px 30px rgba(2, 77, 163, 0.15);
  }

  .form-field {
    margin-bottom: 22px;
    padding: 16px 15px;
    background-color: #f5f9ff;
    border-radius: 12px;

    :deep(.van-field__control) {
      padding-left: 10px;
      font-size: 16px;
    }

    .field-icon {
      color: @theme-color;
      margin-right: 8px;
    }

    :deep(.van-field__error-message) {
      margin-left: 10px;
    }
  }
}

.password-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -8px;
  margin-bottom: 20px;

  .remember-me {
    :deep(.van-checkbox__label) {
      color: #666;
      font-size: 14px;
    }

    :deep(.van-checkbox__icon--checked .van-icon) {
      background-color: @theme-color;
      border-color: @theme-color;
    }
  }

  .forgot-password {
    display: flex;
    align-items: center;
    color: @theme-color;
    font-size: 14px;
    cursor: pointer;

    span {
      margin-right: 4px;
    }

    &:hover {
      text-decoration: underline;
    }
  }
}

.login-button {
  height: 50px;
  font-size: 18px;
  font-weight: 500;
  color: white;
  background: linear-gradient(135deg, @theme-color, #0f6fee);
  border: none;
  margin-top: 15px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(2, 77, 163, 0.3);

  &:active {
    opacity: 0.95;
    transform: translateY(1px);
  }
}

.wechat-login {
  margin: 20px 0;

  .wechat-button {
    height: 50px;
    background-color: #07c160;
    border: none;
    color: white;
    font-weight: 500;

    &:active {
      background-color: #06ae56;
    }
  }

  .wechat-container {
    display: flex;
    align-items: center;
    justify-content: center;

    .wechat-icon {
      margin-right: 10px;
      color: white;
    }
  }
}

.register-option {
  text-align: center;
  margin-top: 25px;
  color: #666;
  font-size: 15px;

  .register-link {
    color: @theme-color;
    font-weight: 500;
    margin-left: 8px;
    cursor: pointer;

    &:hover {
      text-decoration: underline;
    }
  }
}

.footer-container {
  text-align: center;
  padding: 15px 0;

  .app-version {
    font-size: 13px;
    color: #888;
    margin-bottom: 5px;
  }

  .copyright {
    font-size: 12px;
    color: #999;
  }
}

@media (max-width: 480px) {

  .logo-section .logo-container {
    width: 150px;
    height: 150px;
  }

  .login-button,
  .wechat-button {
    height: 46px;
    font-size: 16px;
  }

  .form-field {
    padding: 12px 15px;
  }
}
</style>
