<template>
  <view class="login-container">
    <view class="login-form">
      <view class="logo-section">
        <view class="logo-text">自助洗车</view>
        <view class="logo-subtitle">运营管理小程序</view>
      </view>
      
      <view class="input-group">
        <view class="input-label">
          <text class="iconfont">📱</text>
          <text class="label">手机号</text>
        </view>
        <input 
          v-model="loginForm.mobilePhone" 
          type="number" 
          placeholder="请输入手机号"
          maxlength="11"
          class="input-field"
        />
      </view>
      
      <view class="input-group">
        <view class="input-label">
          <text class="iconfont">🔒</text>
          <text class="label">密码</text>
        </view>
        <input 
          v-model="loginForm.password" 
          type="password" 
          placeholder="请输入密码"
          @confirm="handleLogin"
          class="input-field"
        />
      </view>
      
      <button class="login-btn" @click="handleLogin" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </view>
  </view>
</template>

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

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

// RSA加密函数（与admin-web保持一致）
const encryptData = (str) => {
  let encryptor = new JSEncrypt()
  // 设置公钥（从后端配置文件获取，与admin-web相同）
  let publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNc4Zrvk3E0mUkO8NOeNYOOaPI4uLoBAuDt9Rp0urX7y0wq7vvQzytvwzXXeM9Xp89j7g4ZLR7qBLBCj3QNPH0SUjE1yy9KVBKdjkPre7WT+plS74s2rJz/hygKiJ3Vxa+Z15v6JEHy/3/+i9gW3p/bCLaMQtvGemNvDXwCTwINQIDAQAB'
  encryptor.setPublicKey(publicKey)
  // 加密数据
  return encryptor.encrypt(str)
}

// 加载字典数据（与admin-web保持一致）
const loadDictionaries = async () => {
  try {
    const res = await getDataDictList()
    if (res && res.code === 200) {
      const list = res.data
      // 按code分组，与admin-web保持一致
      const dictGroup = {}
      list.forEach(item => {
        if (!dictGroup[item.code]) {
          dictGroup[item.code] = []
        }
        dictGroup[item.code].push(item)
      })
      // 保存到缓存
      storage.set('dicts', dictGroup)
      console.log('字典数据加载成功:', dictGroup)
    }
  } catch (error) {
    console.error('加载字典数据失败:', error)
  }
}

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 {
    // RSA加密密码
    const encryptedPassword = encryptData(loginForm.value.password)
    const res = await login(phone, encryptedPassword)
    
    if (res && res.code === 200) {
      // 保存token和用户信息
      storage.set('token', res.data.accessToken)
      storage.set('userInfo', {
        id: res.data.id,
        name: res.data.username || phone,
        mobilePhone: phone
      })
      
      // 登录成功后加载字典数据（与admin-web保持一致）
      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-container {
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 60rpx 30rpx;
  box-sizing: border-box;
}

/* 登录表单卡片 */
.login-form {
  background-color: #FFFFFF;
  border-radius: 32rpx;
  padding: 80rpx 60rpx;
  width: 100%;
  max-width: 650rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
}

/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 80rpx;
}

.logo-text {
  font-size: 56rpx;
  font-weight: 700;
  color: #667EEA;
  margin-bottom: 16rpx;
  display: block;
  letter-spacing: 4rpx;
}

.logo-subtitle {
  font-size: 28rpx;
  color: #999999;
  display: block;
  font-weight: 400;
}

/* 输入组 */
.input-group {
  margin-bottom: 40rpx;
}

.input-label {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.input-label .iconfont {
  font-size: 32rpx;
  margin-right: 12rpx;
  color: #667EEA;
}

.label {
  color: #1A1A1A;
  font-size: 28rpx;
  font-weight: 600;
}

/* 输入框 */
.input-field {
  width: 100%;
  height: 90rpx;
  padding: 0 30rpx;
  border: 2rpx solid #E8E8E8;
  border-radius: 16rpx;
  font-size: 28rpx;
  color: #1A1A1A;
  box-sizing: border-box;
  background-color: #F8F9FA;
  transition: all 0.3s;
}

.input-field:focus {
  border-color: #667EEA;
  background-color: #FFFFFF;
  outline: none;
  box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(90deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  margin-top: 60rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s;
}

.login-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.5);
}

.login-btn:disabled {
  background: linear-gradient(90deg, #CCCCCC 0%, #BBBBBB 100%);
  box-shadow: none;
  opacity: 0.6;
}
</style>