<template>
  <div class="login-container">
    <!-- 左侧背景面板 -->
    <div class="left-panel">
      <div class="background-overlay"></div>
      <div class="content-wrapper">
        <div class="logo-section">
          <img src="/logo.svg" alt="Logo" class="logo animate-float" />
        </div>
        <div class="title-section">
          <h1 class="main-title">医梦AI管理系统</h1>
          <p class="subtitle">欢迎使用智能管理系统</p>
        </div>
      </div>
    </div>

    <!-- 右侧登录面板 -->
    <div class="right-panel">
      <div class="login-form-container">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
          <div class="title-box">
            <h3 class="form-title">登录</h3>
            <lang-select />
          </div>
          
          <el-form-item v-if="tenantEnabled" prop="tenantId" class="tenant-select-item">
            <el-select v-model="loginForm.tenantId" filterable :placeholder="proxy.$t('login.selectPlaceholder')" class="tenant-select">
              <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-container">
              <el-input
                v-model="loginForm.code"
                size="large"
                auto-complete="off"
                :placeholder="proxy.$t('login.code')"
                class="captcha-input"
                @keyup.enter="handleLogin"
              >
                <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
              </el-input>
              <div class="captcha-image">
                <img :src="codeUrl" class="captcha-img" @click="getCode" />
              </div>
            </div>
          </el-form-item>
          
          <div class="form-options">
            <el-checkbox v-model="loginForm.rememberMe">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
            <div v-if="register" class="register-link">
              <router-link class="link-type" :to="'/register'">{{ proxy.$t('login.switchRegisterPage') }}</router-link>
            </div>
          </div>
          
          
          <el-form-item class="login-button">
            <el-button :loading="loading" size="large" type="primary" style="width: 100%" @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 class="el-login-footer">
          <span>© 2020-2025 回车网络 版权所有</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } 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: '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) {
    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) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

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

<style lang="scss" scoped>
.login-container {
  display: flex;
  min-height: 100vh;
  width: 100%;
}

.left-panel {
  flex: 1;
  position: relative;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.background-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    154deg,
    rgba(255, 255, 255, 0.3) 30%,
    rgba(59, 130, 246, 0.2) 48%,
    rgba(255, 255, 255, 0.3) 64%
  );
  filter: blur(100px);
}

.content-wrapper {
  position: relative;
  z-index: 2;
  text-align: center;
  color: white;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.logo-section {
  margin-bottom: 3rem;
  
  .logo {
    width: 80%;
    height: auto;
    max-width: 600px;
    filter: brightness(0) invert(0);
    opacity: 0.8;
  }
}

.title-section {
  .main-title {
    font-size: 2.5rem;
    font-weight: 600;
    margin: 0 0 0.8rem 0;
    color: #1e3a8a;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }
  
  .subtitle {
    font-size: 1.2rem;
    margin: 0;
    opacity: 0.8;
    font-weight: 400;
    color: #3b82f6;
  }
}

.animate-float {
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.right-panel {
  width: 34%;
  min-height: 100vh;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  position: relative;
}

.login-form-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 2rem;
  position: relative;
}

.login-form {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  max-width: 400px;
  margin: 0 auto;
  width: 100%;
}

.title-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;

  .form-title {
    margin: 0;
    font-size: 1.8rem;
    font-weight: 600;
    color: #1f2937;
  }

  :deep(.lang-select--style) {
    line-height: 0;
    color: #6b7280;
  }
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  
  .register-link {
    .link-type {
      color: #3b82f6;
      text-decoration: none;
      font-size: 0.875rem;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
}


.login-button {
  margin-bottom: 0;
  
  .el-button {
    height: 40px;
    font-size: 1rem;
    font-weight: 500;
    border-radius: 8px;
  }
}

.el-input {
  height: 40px;
  
  input {
    height: 40px;
    border-radius: 8px;
    border: 1px solid #d1d5db;
    font-size: 0.95rem;
    
    &:focus {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }
}

.tenant-select-item {
  .el-form-item__content {
    width: 100%;
  }
}

.tenant-select {
  width: 100% !important;
  height: 40px;
  
  .el-select__wrapper {
    height: 40px !important;
    min-height: 40px !important;
    border-radius: 8px;
    border: 1px solid #d1d5db;
    width: 100%;
    padding: 0 12px;
    align-items: center;
    
    &:focus-within {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }
  
  .el-select__prefix {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
  }
  
  .el-select__selection {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
    flex: 1;
  }
  
  .el-select__selected-item {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
  }
  
  .el-select__input-wrapper {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
  }
  
  .el-select__input {
    height: 40px;
    line-height: 40px;
  }
  
  .el-select__placeholder {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
  }
  
  .el-select__suffix {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
  }
  
  .el-select__caret {
    height: 40px;
    line-height: 40px;
    display: flex;
    align-items: center;
  }
}

.input-icon {
  height: 20px;
  width: 20px;
  margin-left: 12px;
  color: #6b7280;
}

.captcha-item {
  .el-form-item__content {
    display: flex;
    align-items: stretch;
  }
}

.captcha-container {
  display: flex;
  gap: 12px;
  width: 100%;
  align-items: stretch;
}

.captcha-input {
  flex: 1;
  
  .el-input__wrapper {
    height: 40px;
    border-radius: 8px;
    border: 1px solid #d1d5db;
    
    &:focus-within {
      border-color: #3b82f6;
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }
  }
}

.captcha-image {
  width: 120px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9fafb;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    background: #f0f9ff;
  }
  
  .captcha-img {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
}

.el-login-footer {
  position: absolute;
  bottom: 1rem;
  left: 0;
  right: 0;
  text-align: center;
  color: #6b7280;
  font-size: 0.75rem;
  font-weight: 400;
}


// 响应式设计
@media (max-width: 1024px) {
  .left-panel {
    display: none;
  }
  
  .right-panel {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .login-form-container {
    padding: 1rem;
  }
  
  .login-form {
    max-width: 100%;
  }
  
  .title-section .main-title {
    font-size: 2rem;
  }
  
  .title-section .subtitle {
    font-size: 1rem;
  }
}
</style>
