<template>
  <div class="login" v-loading="pageLoading" element-loading-background="rgba(255,255,255,0.9)">
    <template v-if="!pageLoading">
      <div class="login-container">
        <div class="login-left">
          <div class="brand-area">
            <div class="brand-logo">
              <svg-icon icon-class="system" class="logo-icon" />
            </div>
            <h1 class="brand-title">{{ title }}</h1>
            <p class="brand-desc">华晟ERP订单管理系统</p>
          </div>
        </div>
        <div class="login-right">
          <div class="login-card">
            <h2 class="card-title">欢迎登录</h2>
            <p class="card-sub">请输入您的账号信息</p>
            <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%" size="large">
                  <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="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="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="input-icon" /></template>
                </el-input>
              </el-form-item>
              <el-form-item v-if="captchaEnabled" prop="code">
                <el-input v-model="loginForm.code" size="large" auto-complete="off"
                  :placeholder="proxy.$t('login.code')" style="width: 63%" @keyup.enter="handleLogin">
                  <template #prefix><svg-icon icon-class="validCode" class="input-icon" /></template>
                </el-input>
                <div class="login-code">
                  <img :src="codeUrl" class="login-code-img" @click="getCode" />
                </div>
              </el-form-item>
              <div class="form-options">
                <el-checkbox v-model="loginForm.rememberMe">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
              </div>
              <el-form-item style="width: 100%; margin-bottom: 0">
                <el-button :loading="loading" size="large" type="primary" class="login-btn"
                  @click.prevent="handleLogin">
                  <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
                  <span v-else>{{ proxy.$t('login.logging') }}</span>
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="login-footer">
        <span>Copyright © 2026 华晟ERP订单管理系统</span>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authRouterUrl } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

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: '',
  password: '',
  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 pageLoading = ref(true);
// 验证码开关
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;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authRouterUrl(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(async () => {
  pageLoading.value = true;
  await Promise.all([
    getCode(),
    initTenantList(),
    getLoginData()
  ]);
  pageLoading.value = false;
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e9f0 50%, #dce3eb 100%);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -20%;
    width: 600px;
    height: 600px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(26, 115, 232, 0.06) 0%, rgba(26, 115, 232, 0.02) 100%);
    pointer-events: none;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -30%;
    left: -10%;
    width: 400px;
    height: 400px;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(66, 133, 244, 0.05) 0%, rgba(66, 133, 244, 0.02) 100%);
    pointer-events: none;
  }
}

.login-container {
  display: flex;
  width: 960px;
  min-height: 520px;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.08), 0 2px 8px rgba(0, 0, 0, 0.04);
  overflow: hidden;
  z-index: 1;
}

.login-left {
  flex: 0 0 420px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #1a73e8 0%, #4285f4 50%, #5b9cf6 100%);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: -60px;
    right: -60px;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.06);
    pointer-events: none;
  }

  &::after {
    content: '';
    position: absolute;
    bottom: -40px;
    left: -40px;
    width: 160px;
    height: 160px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.04);
    pointer-events: none;
  }
}

.brand-area {
  text-align: center;
  color: #fff;
  z-index: 1;
}

.brand-logo {
  width: 72px;
  height: 72px;
  margin: 0 auto 24px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
}

.logo-icon {
  width: 40px;
  height: 40px;
  color: #fff;
}

.brand-title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 12px;
  letter-spacing: 2px;
}

.brand-desc {
  font-size: 14px;
  opacity: 0.85;
  margin: 0;
  letter-spacing: 1px;
}

.login-right {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 48px 40px;
}

.login-card {
  width: 100%;
  max-width: 360px;
}

.card-title {
  font-size: 24px;
  font-weight: 700;
  color: #1a1a2e;
  margin: 0 0 8px;
}

.card-sub {
  font-size: 14px;
  color: #909399;
  margin: 0 0 32px;
}

.login-form {
  .input-icon {
    height: 16px;
    width: 16px;
    color: #909399;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 0 0 1px #e4e7ed inset;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
  }

  :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #1a73e8 inset;
  }

  :deep(.el-select .el-input__wrapper) {
    border-radius: 8px;
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  :deep(.el-checkbox__label) {
    font-size: 13px;
    color: #606266;
  }
}

.login-btn {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 2px;
  background: linear-gradient(135deg, #1a73e8 0%, #4285f4 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(26, 115, 232, 0.3);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 6px 20px rgba(26, 115, 232, 0.4);
  }

  &:active {
    transform: translateY(0);
  }
}

.login-code {
  width: calc(37% - 10px);
  height: 40px;
  float: right;
  margin-left: 10px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #e4e7ed;

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

.login-footer {
  position: fixed;
  bottom: 24px;
  width: 100%;
  text-align: center;
  color: #909399;
  font-size: 12px;
  letter-spacing: 0.5px;
  z-index: 1;
}

@media (max-width: 1000px) {
  .login-container {
    width: 90vw;
    flex-direction: column;
    min-height: auto;
  }

  .login-left {
    flex: 0 0 auto;
    padding: 40px 20px;
  }

  .login-right {
    padding: 32px 24px;
  }

  .brand-logo {
    width: 56px;
    height: 56px;
    margin-bottom: 16px;
  }

  .brand-title {
    font-size: 22px;
  }
}
</style>
