<template>
  <view class="login-container">
    <!-- 语言切换按钮 -->
    <view class="language-switcher" @click="switchLanguage">
      <text class="language-text" :class="{ active: locale === 'zh-CN' }">中</text>
      <text class="language-separator">|</text>
      <text class="language-text" :class="{ active: locale === 'en-US' }">EN</text>
    </view>
    
    <view class="login-box">
      <view class="logo-section">
        <text class="app-title">{{ $t('login.appTitle') }}</text>
        <text class="app-subtitle">{{ $t('login.welcome') }}</text>
      </view>
      
      <view class="form-section">
        <view class="form-item">
          <view class="input-wrapper">
            <image class="input-icon" src="/static/pages/login/phone.png" mode="aspectFit" />
            <input
              v-model="phone"
              type="text"
              maxlength="11"
              :placeholder="$t('login.phonePlaceholder')"
              class="input-field"
              @input="onPhoneInput"
            />
          </view>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <image class="input-icon" src="/static/pages/login/password.png" mode="aspectFit" />
            <input
              v-model="password"
              :password="!showPassword"
              :placeholder="$t('login.passwordPlaceholder')"
              class="input-field"
            />
            <text 
              class="toggle-password" 
              @click="togglePassword"
            >
              {{ showPassword ? '👁' : '👁‍🗨' }}
            </text>
          </view>
        </view>
        
        <!-- 协议勾选 -->
        <view class="agreement-section">
          <checkbox-group @change="handleAgreementChange">
            <label class="agreement-label">
              <checkbox 
                :checked="agreedToTerms" 
                class="agreement-checkbox"
                color="#2E7CF6"
              />
              <view class="agreement-text">
                <text class="prefix">{{ $t('login.agreePrefix') }}</text>
                <text class="link" @click.stop="viewUserAgreement">{{ $t('login.userAgreement') }}</text>
                <text class="prefix">{{ $t('login.and') }}</text>
                <text class="link" @click.stop="viewPrivacyPolicy">{{ $t('login.privacyPolicy') }}</text>
              </view>
            </label>
          </checkbox-group>
        </view>
        
        <button 
          class="login-btn"
          @click="handleLogin"
        >
          {{ $t('login.loginButton') }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '@/store/index'
import { useLocaleStore } from '@/store/locale'
import request from '@/utils/request.js'

const { t, locale } = useI18n()
const userStore = useUserStore()
const localeStore = useLocaleStore()

const phone = ref('')
const password = ref('')
const showPassword = ref(false)
const isLanguageSwitching = ref(false)
const agreedToTerms = ref(false)

// 当前语言名称
const currentLanguageName = computed(() => {
  return localeStore.getCurrentLocaleName()
})

// 页面显示时更新标题
onShow(() => {
  // 更新导航栏标题
  uni.setNavigationBarTitle({
    title: t('login.title')
  })
})

// 切换语言 - 优化版本，避免页面重绘
const switchLanguage = async () => {
  // 防止频繁切换
  if (isLanguageSwitching.value) {
    return
  }
  
  isLanguageSwitching.value = true
  
  try {
    // 直接切换语言，i18n 会自动处理文本更新
    localeStore.toggleLocale()
    
    // 使用 nextTick 确保在 DOM 更新后再更新导航栏
    await nextTick()
    
    // 异步更新导航栏标题
    uni.setNavigationBarTitle({
      title: t('login.title')
    })
  } finally {
    // 短暂延迟后允许再次切换
    setTimeout(() => {
      isLanguageSwitching.value = false
    }, 300)
  }
}

// 验证手机号格式
const isValidPhone = computed(() => {
  return /^1[3-9]\d{9}$/.test(phone.value)
})

// 是否可以提交
const canSubmit = computed(() => {
  return isValidPhone.value && password.value.length >= 6
})

// 手机号输入处理
const onPhoneInput = (e) => {
  // 限制只能输入数字
  phone.value = e.detail.value.replace(/[^\d]/g, '')
}

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

// 协议勾选变化
const handleAgreementChange = (e) => {
  agreedToTerms.value = e.detail.value.length > 0
}

// 查看用户协议
const viewUserAgreement = () => {
  uni.navigateTo({
    url: '/pages-content/my/aggreement/detail?type=user'
  })
}

// 查看隐私协议
const viewPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages-content/my/aggreement/detail?type=privacy'
  })
}

// 登录处理
const handleLogin = async () => {
  // 验证手机号
  if (!isValidPhone.value) {
    uni.showToast({
      title: t('login.phoneError'),
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 验证密码
  if (password.value.length < 6) {
    uni.showToast({
      title: t('login.passwordError'),
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 验证是否同意协议
  if (!agreedToTerms.value) {
    uni.showToast({
      title: t('login.agreementError'),
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  try {
    uni.showLoading({
      title: t('login.loggingIn'),
      mask: true
    })
    
    // 准备登录参数
    const loginContent = JSON.stringify({
      phoneNumber: phone.value,
      password: password.value
    })
    
    // 调用新的登录接口
    const res = await request({
      url: '/applet/auth/login/password',
      method: 'POST',
      data: {
        clientId: '2f847927afb2b3ebeefc870c13d623f2',
        content: loginContent
      }
    })
    
    // 保存 token
    userStore.setToken(res.data.token)
    
    uni.hideLoading()
    
    uni.showToast({
      title: t('login.loginSuccess'),
      icon: 'success',
      duration: 1500
    })
    
    // 登录成功后跳转到首页
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/index'
      })
    }, 1500)
    
  } catch (error) {
    uni.hideLoading()
    console.error('登录失败:', error)
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #2E7CF6 0%, #1A5FC7 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 40rpx;
  padding-top: 270rpx;
  position: relative;
}

.language-switcher {
  align-self: flex-end;
  margin-bottom: 32rpx;
  margin-right: 40rpx;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10rpx);
  border-radius: 30rpx;
  padding: 12rpx 24rpx;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  gap: 8rpx;
  
  &:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 1);
  }
}

.login-box {
  width: 100%;
  max-width: 600rpx;
  background: #ffffff;
  border-radius: 32rpx;
  padding: 60rpx 40rpx;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
}

.language-text {
  font-size: 26rpx;
  color: #999;
  font-weight: 500;
  transition: all 0.3s;
  
  &.active {
    color: #2E7CF6;
    font-weight: 700;
  }
}

.language-separator {
  font-size: 26rpx;
  color: #ccc;
  font-weight: 300;
}

.logo-section {
  text-align: center;
  margin-bottom: 80rpx;
}

.app-title {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.app-subtitle {
  display: block;
  font-size: 28rpx;
  color: #999;
}

.form-section {
  width: 100%;
}

.form-item {
  margin-bottom: 32rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 16rpx;
  padding: 0 24rpx;
  height: 96rpx;
  transition: all 0.3s;
  border: 2rpx solid transparent;
  
  &:focus-within {
    background: #fff;
    border-color: #2E7CF6;
    box-shadow: 0 0 0 4rpx rgba(46, 124, 246, 0.1);
  }
}

.input-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 16rpx;
  opacity: 0.6;
}

.input-field {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  
  &::placeholder {
    color: #999;
  }
}

.toggle-password {
  font-size: 40rpx;
  cursor: pointer;
  padding: 8rpx;
}

.login-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #2E7CF6 0%, #1A5FC7 100%);
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  border-radius: 16rpx;
  border: none;
  margin-top: 48rpx;
  transition: all 0.3s;
  
  &:active {
    opacity: 0.8;
    transform: scale(0.98);
  }
}

.login-btn-disabled {
  background: #ccc;
  opacity: 0.6;
  
  &:active {
    transform: none;
  }
}

.agreement-section {
  margin-top: 24rpx;
  margin-bottom: 8rpx;
}

.agreement-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.agreement-checkbox {
  margin-right: 12rpx;
  transform: scale(0.7);
}

.agreement-text {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  line-height: 1.6;
  
  .prefix {
    font-size: 24rpx;
    color: #666;
    margin-right: 4rpx;
  }
  
  .link {
    font-size: 24rpx;
    color: #2E7CF6;
    text-decoration: none;
    margin: 0 4rpx;
    
    &:active {
      opacity: 0.7;
    }
  }
}
</style>
