<template>
  <n-modal
    v-model:show="showModal"
    :mask-closable="false"
    :close-on-esc="false"
    class="login-modal"
  >
    <div class="login-modal-container">
      <!-- 关闭按钮 -->
      <button class="close-btn" @click="closeModal">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
        </svg>
      </button>

      <div class="login-content">
        <h2 class="form-title">账号登录</h2>
        
        <form @submit.prevent="handleLogin">
          <div class="form-group">
            <div class="input-wrapper">
              <svg class="input-icon" width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M8 8C10.2091 8 12 6.20914 12 4C12 1.79086 10.2091 0 8 0C5.79086 0 4 1.79086 4 4C4 6.20914 5.79086 8 8 8Z" fill="#999"/>
                <path d="M8 10C3.58172 10 0 13.5817 0 18H16C16 13.5817 12.4183 10 8 10Z" fill="#999"/>
              </svg>
              <input
                v-model="loginForm.account"
                type="text"
                placeholder="请输入手机号或邮箱"
                class="form-input"
                required
              />
            </div>
          </div>

          <div class="form-group">
            <div class="input-wrapper">
              <svg class="input-icon" width="16" height="16" viewBox="0 0 16 16" fill="none">
                <path d="M4 7V5C4 2.79086 5.79086 1 8 1C10.2091 1 12 2.79086 12 5V7H13C13.5523 7 14 7.44772 14 8V14C14 14.5523 13.5523 15 13 15H3C2.44772 15 2 14.5523 2 14V8C2 7.44772 2.44772 7 3 7H4Z" fill="#999"/>
              </svg>
              <input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                class="form-input"
                required
              />
            </div>
          </div>

          <div class="form-options">
            <label class="checkbox-wrapper">
              <input v-model="loginForm.remember" type="checkbox" />
              <span class="checkbox-text">下次自动登录</span>
            </label>
            <a href="#" class="forgot-password">忘记密码</a>
          </div>

          <button type="submit" class="submit-btn" :disabled="isLoading">
            {{ isLoading ? '登录中...' : '登录' }}
          </button>
        </form>

        <div class="form-footer">
          <p>登录即代表同意我们的 <a href="#" class="link">《服务协议和隐私政策》</a></p>
        </div>
      </div>
    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { AuthApi } from '@/api'

interface Props {
  show: boolean
}

interface Emits {
  (e: 'update:show', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const message = useMessage()
const userStore = useUserStore()

const showModal = computed({
  get: () => props.show,
  set: (value) => emit('update:show', value)
})

const isLoading = ref(false)

// 登录表单数据
const loginForm = reactive({
  account: '',
  password: '',
  remember: false
})

// 关闭模态框
const closeModal = () => {
  showModal.value = false
}

// 处理登录
const handleLogin = async () => {
  if (!loginForm.account || !loginForm.password) {
    message.warning('请填写完整的登录信息')
    return
  }

  if (loginForm.password.length < 3) {
    message.warning('密码长度不能少于3位')
    return
  }

  isLoading.value = true
  try {
    // 判断输入的是手机号还是邮箱
    const isPhone = /^[0-9]+$/.test(loginForm.account)

    // 调用登录API
    const response = await AuthApi.login({
      ...(isPhone ? { phone: loginForm.account } : { email: loginForm.account }),
      password: loginForm.password
    })

    if (response.code === 200 || response.code === 0) {
      const { user, token, refreshToken } = response.data

      // 保存用户信息和token到store
      userStore.user = user
      userStore.token = token

      // 保存到本地存储
      localStorage.setItem('token', token)
      localStorage.setItem('refreshToken', refreshToken)
      localStorage.setItem('user', JSON.stringify(user))

      // 如果选择了记住我，设置更长的过期时间
      if (loginForm.remember) {
        localStorage.setItem('rememberMe', 'true')
      }

      message.success('登录成功！')
      emit('success')
      closeModal()

      // 清空表单
      loginForm.account = ''
      loginForm.password = ''
      loginForm.remember = false
    } else {
      message.error(response.message || '登录失败')
    }

  } catch (error: any) {
    console.error('登录失败:', error)

    // 处理不同类型的错误
    if (error.response?.status === 401) {
      message.error('邮箱或密码错误')
    } else if (error.response?.status === 429) {
      message.error('登录尝试过于频繁，请稍后再试')
    } else if (error.response?.data?.message) {
      // 显示后端返回的具体错误信息
      message.error(error.response.data.message)
    } else if (error.message) {
      // 显示错误对象中的消息
      message.error(error.message)
    } else {
      message.error('网络错误，请检查网络连接')
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-modal-container {
  position: relative;
  background: white;
  border-radius: 12px;
  width: 400px;
  max-width: 90vw;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  background: none;
  border: none;
  color: #999;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.2s;
  z-index: 10;
}

.close-btn:hover {
  color: #666;
  background: #f5f5f5;
}

.login-content {
  padding: 40px;
}

.form-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 30px 0;
  text-align: center;
}

.form-group {
  margin-bottom: 20px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.input-icon {
  position: absolute;
  left: 12px;
  z-index: 2;
  color: #999;
}

.form-input {
  width: 100%;
  height: 48px;
  padding: 0 16px 0 40px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
  background: #fafafa;
  transition: all 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: #1890ff;
  background: white;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.form-input::placeholder {
  color: #999;
}

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

.checkbox-wrapper {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: #666;
}

.checkbox-wrapper input[type="checkbox"] {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

.forgot-password {
  color: #1890ff;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.submit-btn {
  width: 100%;
  height: 48px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 20px;
}

.submit-btn:hover:not(:disabled) {
  background: #40a9ff;
}

.submit-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.form-footer {
  text-align: center;
}

.form-footer p {
  font-size: 12px;
  color: #999;
  line-height: 1.4;
  margin: 0;
}

.link {
  color: #1890ff;
  text-decoration: none;
}

.link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-modal-container {
    width: 95vw;
    margin: 20px;
  }
  
  .login-content {
    padding: 30px 20px;
  }
  
  .form-title {
    font-size: 20px;
    margin-bottom: 20px;
  }
}
</style>
