<template>
  <div class="login">
    <!-- 登录表单 -->
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title-box">
        <h3 class="title">香港SMT订单物流管理系统</h3>
        <p class="subtitle">智能化物流解决方案</p>

        <!-- 右上角语言切换按钮 -->
        <!--        <div class="language-switcher" @click="toggleLanguage">-->
        <!--          <svg-icon icon-class="language" class="language-icon" />-->
        <!--        </div>-->
      </div>

      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="用户名">
          <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="密码" @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">
        <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
          <template #prefix>
            <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item>

      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0"> 记住密码</el-checkbox>

      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" class="login-btn" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>

        <!--        <div style="float: right; margin-top: 15px">-->
        <!--          <router-link class="link-type" to="/register"> 注册新账号 </router-link>-->
        <!--        </div>-->
      </el-form-item>
    </el-form>

    <!-- 品牌展示区域 -->
    <div class="brand-section">
      <div class="brand-logo"></div>
      <div class="slogan">
        <h2>智慧物流管理系统</h2>
        <p>让供应链更智能，让物流更高效</p>
      </div>
    </div>

    <!-- 底部版权信息 -->
    <div class="el-login-footer">
      <span>
        Copyright © 2005 瑷胜科技
        <el-link type="primary" href="https://beian.miit.gov.cn/" target="_blank"> 粤ICP备2025398203号 </el-link>
        All Rights Reserved.
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
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';
import { useRouter } from 'vue-router';
import { ElForm, ElMessage } from 'element-plus';

const { t, locale } = useI18n();
const userStore = useUserStore();
const router = useRouter();

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

const loginRules = ref({
  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<InstanceType<typeof ElForm>>();
const tenantList = ref<TenantVO[]>([]);

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

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', loginForm.value.tenantId);
        localStorage.setItem('username', loginForm.value.username);
        localStorage.setItem('password', loginForm.value.password);
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }

      try {
        await userStore.login(loginForm.value);
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
      } catch (error) {
        console.error('登录失败:', error);
        if (captchaEnabled.value) {
          await getCode();
        }
      } finally {
        loading.value = false;
      }
    }
  });
};

const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled ?? true;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  loginForm.value = {
    tenantId: localStorage.getItem('tenantId') || '000000',
    username: localStorage.getItem('username') || '',
    password: localStorage.getItem('password') || '',
    rememberMe: localStorage.getItem('rememberMe') === 'true'
  };
};

const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled ?? true;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value?.length) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

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);
    }
  });
};

const toggleLanguage = () => {
  locale.value = locale.value === 'zh-CN' ? 'en-US' : 'zh-CN';
  ElMessage.success(t('login.languageChanged'));
};

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

<style lang="scss" scoped>
.brand-section {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 50%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-left: 10%;
  z-index: 1;
  @media (max-width: 768px) {
    display: none;
  }

  .brand-logo {
    width: 120px;
    height: 120px;
    background: linear-gradient(135deg, #ffffff 0%, #e3f2fd 100%);
    border-radius: 24px;
    margin-bottom: 30px;
    position: relative;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);

    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 80px;
      height: 80px;
      background: url('../assets/logo/logo.png') no-repeat center;
      background-size: contain;
    }
  }

  .slogan {
    color: white;
    text-align: center;

    h2 {
      font-size: 36px;
      font-weight: 600;
      margin-bottom: 15px;
      text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    }

    p {
      font-size: 18px;
      opacity: 0.9;
    }
  }
}

.login {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  min-height: 100vh;
  padding-right: 20%;
  position: relative;
  overflow: hidden;

  // 使用原始背景
  background:
    radial-gradient(circle at 90% 50%, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0.4) 60%, transparent 100%),
    url('@/assets/images/background.svg') center/cover;

  // 登录表单
  .login-form {
    position: relative;
    z-index: 10;
    width: 400px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
    border: 1px solid rgba(220, 220, 235, 0.3);
    transition:
      transform 0.3s,
      box-shadow 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
    }

    .title-box {
      text-align: center;
      margin-bottom: 25px;
      position: relative;

      .title {
        margin: 0 0 8px 0;
        color: #2c3e50;
        font-size: 24px;
        font-weight: 700;
        letter-spacing: 0.5px;
        position: relative;
        padding-bottom: 15px;

        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 20%;
          right: 20%;
          height: 2px;
          background: linear-gradient(90deg, transparent, #409eff, transparent);
        }
      }

      .subtitle {
        color: #5a5e66;
        font-size: 14px;
        font-weight: 400;
        margin-top: 5px;
      }

      .language-switcher {
        position: absolute;
        top: 10px;
        right: 10px;
        cursor: pointer;
        padding: 8px;
        border-radius: 50%;
        transition: all 0.3s;
        color: #409eff;

        &:hover {
          background-color: rgba(64, 158, 255, 0.1);
          transform: scale(1.1);
        }

        .language-icon {
          font-size: 20px;
        }
      }
    }

    .el-form-item {
      margin-bottom: 22px;

      .el-input {
        height: 46px;
        transition: all 0.3s;
        border-radius: 8px;

        :deep(.el-input__wrapper) {
          border-radius: 8px;
          box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
          transition: box-shadow 0.3s;

          &:hover {
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.25);
          }

          &:focus-within {
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
          }
        }
      }
    }

    .login-btn {
      height: 48px;
      width: 100%;
      border-radius: 8px;
      font-weight: 500;
      letter-spacing: 0.8px;
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
      transition: all 0.3s;
      background: linear-gradient(135deg, #1a5098, #409eff);
      border: none;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 7px 14px rgba(64, 158, 255, 0.5);
      }

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

    .el-checkbox {
      .el-checkbox__label {
        color: #5a5e66;
        font-weight: 500;
      }
    }

    .login-code {
      border-radius: 6px;
      overflow: hidden;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      &:hover {
        transform: translateY(-3px);
        box-shadow: 0 5px 10px rgba(0, 0, 0, 0.15);
      }

      .login-code-img {
        height: 42px;
        cursor: pointer;
        display: block;
        width: 120px;
      }
    }

    .link-type {
      color: #1a5098;
      font-size: 14px;
      text-decoration: none;
      font-weight: 500;
      transition: all 0.2s;

      &:hover {
        color: #409eff;
        text-decoration: underline;
      }
    }
  }

  // 底部版权信息
  .el-login-footer {
    position: fixed;
    bottom: 20px;
    left: 0;
    right: 0;
    text-align: center;
    color: #fff;
    font-size: 13px;
    letter-spacing: 0.4px;
    z-index: 10;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);

    .el-link {
      color: rgba(255, 255, 255, 0.9);
      font-size: 13px;
      text-decoration: none;

      &:hover {
        color: #fff;
        text-decoration: underline;
      }
    }
  }
}

@media (max-width: 768px) {
  .login {
    justify-content: center;
    padding-right: 0;

    .login-form {
      width: 90%;
      margin: 0 auto;

      &:hover {
        transform: none;
      }
    }
  }
}
</style>
