<template>
  <view class="login-page">
    <view class="login-content">
      <!-- Logo -->
      <view class="brand">
        <view class="brand-mark"></view>
        <text class="brand-name">超级进化</text>
        <text class="brand-sub">运营管理平台</text>
      </view>

      <!-- Form -->
      <view class="form">
        <view class="field">
          <view class="field-header">
            <AppIcon name="smartphone" size="18" color="#999999" />
            <text class="field-label">手机号</text>
          </view>
          <input
            v-model="loginForm.mobilePhone"
            type="number"
            placeholder="请输入手机号"
            maxlength="11"
            class="field-input"
          />
        </view>

        <view class="field">
          <view class="field-header">
            <AppIcon name="lock" size="18" color="#999999" />
            <text class="field-label">密码</text>
          </view>
          <input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            @confirm="handleLogin"
            class="field-input"
          />
        </view>

        <view class="remember-row" @click="rememberMe = !rememberMe">
          <view class="remember-check" :class="{ checked: rememberMe }">
            <text v-if="rememberMe" class="remember-tick">✓</text>
          </view>
          <text class="remember-label">记住密码</text>
        </view>

        <button class="submit-btn" @click="handleLogin" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { login } from '../../api/auth.js'
import { loadDicts } from '../../utils/dict.js'
import { storage, showToast } from '../../utils/index.js'
import JSEncrypt from 'jsencrypt'

const loading = ref(false)
const rememberMe = ref(false)
const loginForm = ref({
  mobilePhone: '',
  password: ''
})

const encryptData = (str) => {
  let encryptor = new JSEncrypt()
  let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNc4Zrvk3E0mUkO8NOeNYOOaPI4uLoBAuDt9Rp0urX7y0wq7vvQzytvwzXXeM9Xp89j7g4ZLR7qBLBCj3QNPH0SUjE1yy9KVBKdjkPre7WT+plS74s2rJz/hygKiJ3Vxa+Z15v6JEHy/3/+i9gW3p/bCLaMQtvGemNvDXwCTwINQIDAQAB'
  encryptor.setPublicKey(publicKey)
  return encryptor.encrypt(str)
}

const REMEMBER_KEY = 'remembered_login'

onMounted(() => {
  const saved = storage.get(REMEMBER_KEY)
  if (saved) {
    loginForm.value.mobilePhone = saved.mobilePhone || ''
    loginForm.value.password = saved.password || ''
    rememberMe.value = true
  }
})

const loadDictionaries = async () => {
  await loadDicts()
}

const handleLogin = async () => {
  const phone = loginForm.value.mobilePhone.trim()
  if (!phone) {
    showToast('请输入手机号')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(phone)) {
    showToast('请输入正确的手机号')
    return
  }

  if (!loginForm.value.password) {
    showToast('请输入密码')
    return
  }

  loading.value = true

  try {
    const encryptedPassword = encryptData(loginForm.value.password)
    const res = await login(phone, encryptedPassword)

    if (res && res.code === 200) {
      if (rememberMe.value) {
        storage.set(REMEMBER_KEY, {
          mobilePhone: phone,
          password: loginForm.value.password
        })
      } else {
        storage.remove(REMEMBER_KEY)
      }

      storage.set('token', res.data.accessToken)
      storage.set('userInfo', {
        id: res.data.id,
        name: res.data.username || phone,
        mobilePhone: phone
      })

      await loadDictionaries()

      showToast('登录成功', 'success')

      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }, 800)
    } else {
      showToast(res.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    showToast(error.msg || '网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  background: #F5F7FA;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60rpx 40rpx;
  box-sizing: border-box;
}

.login-content {
  width: 100%;
  max-width: 600rpx;
}

/* Brand */
.brand {
  margin-bottom: 80rpx;
}

.brand-mark {
  width: 8rpx;
  height: 40rpx;
  background: #C6171E;
  border-radius: 4rpx;
  margin-bottom: 24rpx;
}

.brand-name {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  color: #1A1A1A;
  letter-spacing: 2rpx;
  line-height: 1.2;
}

.brand-sub {
  display: block;
  font-size: 26rpx;
  color: #999999;
  margin-top: 12rpx;
  font-weight: 400;
}

/* Form */
.form {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.field-header {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.field-label {
  font-size: 26rpx;
  font-weight: 500;
  color: #666666;
}

.field-input {
  height: 96rpx;
  padding: 0 28rpx;
  background: #F0F0F0;
  border: none;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #1A1A1A;
  box-sizing: border-box;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.field-input:focus {
  background: #FFFFFF;
  box-shadow: 0 0 0 3px rgba(198, 23, 30, 0.2);
  outline: none;
}

.field-input::placeholder {
  color: #B0B0B0;
}

/* Remember Me */
.remember-row {
  display: flex;
  align-items: center;
  gap: 14rpx;
  cursor: pointer;
}

.remember-check {
  width: 36rpx;
  height: 36rpx;
  border-radius: 8rpx;
  border: 2rpx solid #CCCCCC;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.remember-check.checked {
  background: #C6171E;
  border-color: #C6171E;
}

.remember-tick {
  font-size: 22rpx;
  color: #FFFFFF;
  font-weight: 700;
  line-height: 1;
}

.remember-label {
  font-size: 26rpx;
  color: #666666;
}

/* Button */
.submit-btn {
  width: 100%;
  height: 96rpx;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 48rpx;
  font-size: 30rpx;
  font-weight: 600;
  margin-top: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.submit-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

.submit-btn:disabled {
  background: #CCCCCC;
  opacity: 0.6;
  transform: none;
}
</style>
