<template>
  <div class="login-wrapper">
    <div class="user-card">
      <div class="brand">
        <img src="@/assets/images/logo.png" alt="logo" class="logo" />
      </div>

      <div class="form-section">
        <h2 class="section-title">欢迎回来</h2>
        <p class="section-tip">请输入您的账号信息</p>

        <div class="login-tabs">
          <div
            v-for="tab in tabList"
            :key="tab.name"
            :class="['tab-item', { active: activeTab === tab.name }]"
            @click="activeTab = tab.name"
          >
            {{ tab.label }}
          </div>
        </div>

        <el-form class="form-body" ref="loginFormRef" :model="loginForm" :rules="rules" @submit.prevent="handleLogin">
          <el-form-item v-if="activeTab === 'email'" prop="email">
            <el-input v-model="loginForm.email" placeholder="邮箱地址" size="large" clearable />
          </el-form-item>

          <el-form-item class="phone-item" prop="phone" v-else>
            <el-select class="country-select" v-model="loginForm.countryCode" :teleported="false" value-key="code" size="large">
              <el-option v-for="item in countryOptions" :key="item.code" :label="item.code" :value="item.code" />
            </el-select>
            <el-input v-model="loginForm.phone" placeholder="手机号码" size="large" clearable @keyup.enter.prevent="handleLogin" />
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="loginForm.password" placeholder="登录密码" type="password" show-password size="large" @keyup.enter.prevent="handleLogin" />
          </el-form-item>

          <el-button type="primary" class="submit-btn" @click="handleLogin" :loading="buttonLoading">登 录</el-button>

          <div class="link-row">
            <span class="link" @click="handleForgotPassword">忘记密码？</span>
            <span class="link" @click="handleRegister">没有账号？立即注册</span>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { useButtonLoading } from '@/composables/useLoading'
import { setStorage, getStorage } from '@/utils/storage'
import { countryOptions } from '@/views/user/config/mock'
import { passwordRules, emailRules, phoneRules } from './config/rules'

const router = useRouter()
const { buttonLoading, startButtonLoading, stopButtonLoading } = useButtonLoading()
const userStore = useUserStore()

const tabList = ref([
  { label: '邮箱登录', name: 'email' },
  { label: '手机登录', name: 'phone' },
])
const activeTab = ref<string>('email')
const loginFormRef = ref()
const loginForm = ref({
  email: '',
  countryCode: '+86',
  phone: '',
  password: '',
})

const rules = {
  email: emailRules().email,
  phone: phoneRules(loginForm.value).phone,
  password: passwordRules(loginForm.value).password,
}

function generateDeviceNo() {
  return Date.now().toString() + Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
}

async function handleLogin() {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    startButtonLoading()
    
    try {
      const deviceNo = getStorage('device_no', 'session') || generateDeviceNo()
      await userStore.login({
        email: loginForm.value.email,
        mobile: loginForm.value.countryCode + loginForm.value.phone,
        login_type: activeTab.value === 'email' ? 1 : 2,
        password: loginForm.value.password,
        device_no: deviceNo+'',
      })
      setStorage('device_no', deviceNo)
    } finally {
      stopButtonLoading()
    }
  } catch (error) {
    console.error('登录失败：', error)
  }
}

function handleRegister() {
  userStore.clearUserInfo()
  router.push('/user/register')
}

function handleForgotPassword() {
  userStore.clearUserInfo()
  router.push('/user/forgot-password')
}
</script>

<style scoped lang="scss">
.login-wrapper {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: radial-gradient(ellipse at center, #f0f7ff 0%, #e8f4fd 40%, #f5f9ff 100%);
}

.user-card {
  width: 600px;
  padding: 0px 36px 40px 36px;
  background: #ffffff;
  border-radius: 18px;
  box-shadow: 
    0 2px 4px rgba(0, 0, 0, 0.02),
    0 6px 12px rgba(0, 0, 0, 0.03),
    0 16px 32px rgba(0, 0, 0, 0.04);

  .brand {
    display: flex;
    flex-direction: column;
    // align-items: center;
    // justify-content: center;
    margin-bottom: 32px;
    padding-top: 8px;

    .logo {
      width: 160px;
      height: auto;
      // margin-bottom: 28px;
    }

    .brand-name {
      font-size: 22px;
      font-weight: 700;
      color: #1a365d;
      letter-spacing: 1px;
    }
  }

  .form-section {
    .section-title {
      text-align: center;
      font-size: 26px;
      font-weight: 700;
      color: #0f172a;
      margin: 0 0 8px;
    }

    .section-tip {
      text-align: center;
      font-size: 12px;
      color: #a0aec0;
      margin: 0 0 28px;
      font-weight: 400;
    }
  }
}

.login-tabs {
  display: flex;
  gap: 0;
  margin-bottom: 28px;
  position: relative;

  .tab-item {
    flex: 1;
    padding: 12px 0;
    text-align: center;
    font-size: 15px;
    color: #a0aec0;
    cursor: pointer;
    font-weight: 500;
    position: relative;
    transition: all 0.2s ease;

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 0;
      height: 3px;
      background: #1e40af;
      border-radius: 3px;
      transition: width 0.25s ease;
    }

    &.active {
      color: #1e40af;
      font-weight: 600;

      &::after {
        width: 44px;
      }
    }

    &:not(.active):hover {
      color: #64748b;
    }
  }
}

.form-body {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-input__wrapper) {
    padding: 8px 14px;
    border-radius: 10px;
    // border: 1.5px solid #e2e8f0;
    transition: all 0.2s ease;
    background: #fafbfc;
    
    &:hover {
      border-color: #cbd5e1;
      background: #f5f7fa;
    }
    
    &.is-focus {
      border-color: #1e40af;
      background: #ffffff;
      box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.08);
    }
  }

  :deep(.el-input__inner) {
    height: 36px;
    font-size: 14px;
    color: #1e293b;
    
    &::placeholder {
      color: #b0b8c4;
    }
  }

  .phone-item {
    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }

    :deep(.el-select) {
      width: 130px;
      margin-right: 10px;
    }
    
    :deep(.el-select--large .el-select__wrapper) {
      border-radius: 10px;
      border: 1px solid #e2e8f0;
      background: #fafbfc;
      box-shadow: none !important;
      padding: 18px 12px;
    }
    
    :deep(.el-select:hover .el-input__wrapper) {
      border-color: #cbd5e1;
      background: #f5f7fa;
    }
    
    :deep(.el-select.is-focus .el-input__wrapper) {
      border-color: #1e40af !important;
      background: #ffffff;
      box-shadow: 0 0 0 3px rgba(30, 64, 175, 0.08) !important;
    }
  }

  .submit-btn {
    width: 100%;
    height: 46px;
    font-size: 15px;
    font-weight: 600;
    letter-spacing: 3px;
    border-radius: 10px;
    margin-top: 16px;
    background: linear-gradient(135deg, #1e40af 0%, #2563eb 100%);
    border: none;
    box-shadow: 0 4px 14px rgba(30, 64, 175, 0.25);
    transition: all 0.25s ease;

    &:hover {
      background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
      transform: scale(1.01);
      box-shadow: 0 6px 18px rgba(30, 64, 175, 0.32);
    }

    &:active {
      transform: scale(1);
      box-shadow: 0 3px 10px rgba(30, 64, 175, 0.25);
    }
  }

  .link-row {
    display: flex;
    justify-content: space-between;
    margin-top: 24px;

    .link {
      font-size: 14px;
      color: #1e40af;
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        color: #1e3a8a;
        text-decoration: underline;
      }
    }
  }
}
</style>
