<template>
  <div class="login">
    <main class="login-layout">
      <section class="login-hero" aria-hidden="true">
        <div class="brand-panel">
          <img :src="logo" class="brand-logo" alt="" />
          <div>
            <div class="brand-title">{{ title }}</div>
          </div>
        </div>
      </section>

      <section class="login-card" :aria-label="proxy.$t('login.login')">
        <div class="login-card__header">
          <div class="login-brand">
            <img :src="logo" class="login-brand__logo" alt="" />
            <div>
              <h3 class="title">{{ title }}</h3>
            </div>
          </div>
          <lang-select />
        </div>

        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
          <el-form-item v-if="tenantEnabled" prop="tenantId">
            <el-select v-model="loginForm.tenantId" filterable :placeholder="proxy.$t('login.selectPlaceholder')" style="width: 100%">
              <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
              <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
            </el-select>
          </el-form-item>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" :placeholder="proxy.$t('login.username')">
              <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              auto-complete="off"
              :placeholder="proxy.$t('login.password')"
              @keyup.enter="handleLogin"
            >
              <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="captchaEnabled" prop="code" class="captcha-item">
            <div class="captcha-row">
              <el-input v-model="loginForm.code" size="large" auto-complete="off" :placeholder="proxy.$t('login.code')" @keyup.enter="handleLogin">
                <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
              </el-input>
              <button class="login-code" type="button" :title="proxy.$t('login.code')" @click="getCode">
                <img :src="codeUrl" class="login-code-img" alt="" />
              </button>
            </div>
          </el-form-item>

          <div class="login-options">
            <el-checkbox v-model="loginForm.rememberMe">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
            <router-link v-if="register" class="link-type register-link" :to="'/register'">{{ proxy.$t('login.switchRegisterPage') }}</router-link>
          </div>

          <el-button :loading="loading" size="large" type="primary" class="login-submit" @click.prevent="handleLogin">
            <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
            <span v-else>{{ proxy.$t('login.logging') }}</span>
          </el-button>
        </el-form>
      </section>
    </main>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2026 橙空科技 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { useI18n } from 'vue-i18n';
import logo from '@/assets/logo/irrigation-logo.svg';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    // 刷新验证码时清空输入框
    loginForm.value.code = '';
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.login {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100%;
  padding: 48px 32px 64px;
  overflow-x: hidden;
  overflow-y: auto;
  background-image: url('../assets/images/login-background-simple.svg');
  background-size: cover;
  background-position: center;
}

.login::before {
  position: absolute;
  inset: 0;
  content: '';
  background:
    linear-gradient(110deg, rgba(255, 255, 255, 0.2) 0%, rgba(255, 255, 255, 0.48) 52%, rgba(255, 255, 255, 0.84) 100%),
    radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.38), transparent 28%);
}

.login-layout {
  position: relative;
  z-index: 1;
  display: grid;
  grid-template-columns: minmax(0, 1fr) 430px;
  gap: clamp(40px, 7vw, 96px);
  align-items: center;
  width: min(1120px, 100%);
}

.login-hero {
  min-height: 480px;
  display: flex;
  align-items: flex-end;
}

.brand-panel {
  display: flex;
  align-items: center;
  gap: 18px;
  color: #ffffff;
  text-shadow: 0 8px 28px rgba(15, 23, 42, 0.32);
}

.brand-logo {
  width: 76px;
  height: 76px;
  border-radius: 18px;
  box-shadow: 0 16px 40px rgba(15, 23, 42, 0.2);
}

.brand-title {
  max-width: 520px;
  font-size: 36px;
  font-weight: 700;
  line-height: 1.2;
  overflow-wrap: anywhere;
}

.login-card {
  width: 100%;
  box-sizing: border-box;
  border-radius: var(--app-radius-lg);
  padding: 34px 34px 28px;
  background: rgba(255, 255, 255, 0.94);
  border: 1px solid rgba(255, 255, 255, 0.62);
  box-shadow: 0 24px 70px rgba(15, 23, 42, 0.18);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
}

.login-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 30px;

  .title {
    margin: 0;
    color: var(--el-text-color-primary);
    font-size: 20px;
    font-weight: 600;
    line-height: 1.3;
    letter-spacing: 0;
    overflow-wrap: anywhere;
  }

  :deep(.lang-select--style) {
    line-height: 0;
    color: var(--el-text-color-secondary);
  }
}

.login-brand {
  display: flex;
  align-items: center;
  min-width: 0;
  gap: 12px;
}

.login-brand__logo {
  width: 42px;
  height: 42px;
  flex: none;
  border-radius: 10px;
}

.login-form {
  width: 100%;

  .el-input {
    height: 44px;

    input {
      height: 44px;
    }
  }

  .input-icon {
    height: 43px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-form :deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.08);
}

.login-form :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}

.captcha-item {
  margin-bottom: 18px;
}

.captcha-row {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 126px;
  gap: 12px;
  width: 100%;
}

.login-options {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  min-height: 32px;
  margin: 0 0 22px;
}

.register-link {
  flex: none;
}

.login-submit {
  width: 100%;
  height: 44px;
}

.login-form :deep(.el-button--primary) {
  border-radius: var(--app-radius-md);
  box-shadow: 0 8px 20px rgba(59, 130, 246, 0.25);
}

.login-code {
  width: 100%;
  height: 44px;
  padding: 0;
  border-radius: var(--app-radius-sm);
  overflow: hidden;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid var(--el-border-color-light);
  cursor: pointer;

  img {
    vertical-align: middle;
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  text-align: center;
  color: rgba(255, 255, 255, 0.75);
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 44px;
  padding-left: 0;
}

:global(html.dark) {
  .login::before {
    background:
      linear-gradient(110deg, rgba(2, 6, 23, 0.04) 0%, rgba(2, 6, 23, 0.46) 52%, rgba(2, 6, 23, 0.78) 100%),
      radial-gradient(circle at 20% 20%, rgba(59, 130, 246, 0.22), transparent 30%);
  }

  .login-card {
    background: rgba(17, 24, 39, 0.9);
    border-color: rgba(148, 163, 184, 0.2);
  }

  .login-form :deep(.el-input__wrapper) {
    background-color: rgba(17, 24, 39, 0.7);
  }

  .el-login-footer {
    color: rgba(226, 232, 240, 0.65);
  }
}

@media (max-width: 920px) {
  .login {
    padding: 32px 18px 64px;
  }

  .login-layout {
    grid-template-columns: minmax(0, 430px);
    justify-content: center;
  }

  .login-hero {
    display: none;
  }
}

@media (max-width: 480px) {
  .login-card {
    padding: 28px 22px 24px;
  }

  .login-card__header {
    margin-bottom: 24px;
  }

  .captcha-row {
    grid-template-columns: minmax(0, 1fr) 112px;
    gap: 10px;
  }

  .login-options {
    align-items: flex-start;
    flex-direction: column;
    gap: 8px;
  }

  .el-login-footer {
    padding: 0 12px;
    line-height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
