<template>
  <view class="login-container">
    <!-- 语言切换按钮 -->
    <view class="language-switcher" :style="{ top: languageSwitcherTop + 'px' }" @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="header-bg" :style="{ paddingTop: statusBarHeight + 'px' }">
      <text class="app-title">{{ t('login.appTitle') }}</text>
      <text class="app-subtitle">{{ t('login.welcome') }}</text>
    </view>
    
    <!-- 登录表单卡片 -->
    <view class="login-card">
      <view class="card-title">{{ t('login.title') }}</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="#1EC9C9"
              />
              <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, onMounted } 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 statusBarHeight = ref(0)

// 语言切换按钮的top位置
const languageSwitcherTop = computed(() => {
  return statusBarHeight.value + 50 // 状态栏高度 + 50px间距，确保不被遮挡
})

onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0
})

// 当前语言名称
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')
    })
    
    // 显示切换成功提示
    uni.showToast({
      title: t('common.language.switchSuccess'),
      icon: 'success',
      duration: 1500
    })
  } 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-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  position: relative;
}

// 语言切换按钮
.language-switcher {
  position: fixed;
  right: 32rpx;
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10rpx);
  border-radius: 30rpx;
  padding: 12rpx 24rpx;
  cursor: pointer;
  transition: all 0.3s;
  gap: 8rpx;
  z-index: 100;
  
  &:active {
    transform: scale(0.95);
    background: rgba(255, 255, 255, 0.3);
  }
  
  .language-text {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.7);
    font-weight: 500;
    transition: all 0.3s;
    
    &.active {
      color: #ffffff;
      font-weight: 700;
    }
  }
  
  .language-separator {
    font-size: 24rpx;
    color: rgba(255, 255, 255, 0.5);
    font-weight: 300;
  }
}

// 顶部渐变背景
.header-bg {
  background: linear-gradient(180deg, #1ec9c9 0%, #1eb8b8 100%);
  min-height: 500rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 0 40rpx 60rpx;
  
  .app-title {
    font-size: 52rpx;
    font-weight: 700;
    color: #ffffff;
    letter-spacing: 2rpx;
    margin-bottom: 16rpx;
    text-align: center;
    line-height: 1.3;
    word-break: break-word;
    max-width: 600rpx;
  }
  
  .app-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.9);
    letter-spacing: 2rpx;
    text-align: center;
  }
}

// 登录卡片
.login-card {
  background: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  margin-top: -60rpx;
  padding: 48rpx 32rpx;
  flex: 1;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 5;
  
  .card-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 32rpx;
  }
}

.form-section {
  width: 100%;
}

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

.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: #1ec9c9;
    box-shadow: 0 0 0 4rpx rgba(30, 201, 201, 0.1);
  }
}

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

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

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

.agreement-section {
  margin-top: 32rpx;
  margin-bottom: 16rpx;
}

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

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

.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: #1ec9c9;
    text-decoration: none;
    margin: 0 4rpx;
    
    &:active {
      opacity: 0.7;
    }
  }
}

.login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #1ec9c9 0%, #1eb8b8 100%);
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 16rpx;
  border: none;
  margin-top: 32rpx;
  transition: all 0.3s;
  box-shadow: 0 6rpx 20rpx rgba(30, 201, 201, 0.3);
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
  
  &::after {
    border: none;
  }
}
</style>
