<template>
  <view class="login-page">
    <view class="status_bar"></view>

    <!-- 登录标题 -->
    <view class="login-title">{{ loginMode === 'sms' ? '手机验证码登录' : '账号密码登录' }}</view>

    <!-- ====== 验证码登录模式 ====== -->
    <template v-if="loginMode === 'sms'">
      <!-- 手机号输入框 -->
      <view class="input-item">
        <view class="input-icon">
          <image src="https://wuye.ckdzkj.com/images/login/phone.png" mode="" style="height: 100%;width: 100%;"></image>
        </view>
        <input class="input-content native-input" :type="inputType" v-model="phoneNumber"
          placeholder="请输入手机号" placeholder-style="font-size:24rpx" maxlength="11"  />
      </view>

      <!-- 验证码输入框 + 获取验证码按钮 -->
      <view class="input-item verify-item">
        <view class="input-icon">
          <image src="https://wuye.ckdzkj.com/images/login/code.png" mode="" style="height: 100%;width: 100%;"></image>
        </view>
        <input class="input-content verify-input native-input" :type="inputType" v-model="verifyCode"
          placeholder="请输入验证码" maxlength="6" placeholder-style="font-size:24rpx"/>
        <button class="get-verify-btn" :disabled="!canGetVerify || countDown > 0" @click="getVerifyCode">
          {{ countDown > 0 ? `${countDown}s后重新获取` : '获取验证码' }}
        </button>
      </view>
    </template>

    <!-- ====== 账号密码登录模式 ====== -->
    <template v-if="loginMode === 'pwd'">
      <!-- 账号输入框 -->
      <view class="input-item">
        <view class="input-icon">
          <image src="https://wuye.ckdzkj.com/images/login/phone.png" mode="" style="height: 100%;width: 100%;"></image>
        </view>
        <uni-easyinput class="input-content" type="text" v-model="account"
          placeholder="请输入帐号" :inputBorder="false" maxlength="20" :placeholderStyle="placeholderStyle">
        </uni-easyinput>
      </view>

      <!-- 密码输入框 -->
      <view class="input-item">
        <view class="input-icon">
          <image src="https://wuye.ckdzkj.com/images/login/password.png" mode="" style="height: 100%;width: 100%;"></image>
        </view>
        <uni-easyinput class="input-content" type="password" v-model="password"
          placeholder="请输入密码" :inputBorder="false" maxlength="16" :placeholderStyle="placeholderStyle">
        </uni-easyinput>
      </view>
    </template>

    <!-- 协议勾选 + 忘记密码 -->
    <view class="agreement-wrap">
      <view class="agreement-item">
        <view @click="toggleAgreement" class="checkbox-icon">
          <uni-icons type="checkbox-filled" size="24" color="#007aff" v-if="agreeAgreement"></uni-icons>
          <uni-icons type="checkbox" size="24" color="#999" v-else></uni-icons>
        </view>
        <text class="agreement-text">我已阅读并同意
          <text class="agreePrivacy" @click.stop="goToUserAgreement">《用户协议》</text>和
          <text class="agreePrivacy" @click.stop="goToPrivacy">《隐私政策》</text>
        </text>
      </view>
      <text class="forget-pwd" v-if="loginMode === 'pwd'" @click="goForgetPwd">忘记密码？</text>
    </view>

    <!-- 登录按钮 -->
    <button class="login-btn" @click="handleLogin">登录</button>

    <!-- 底部链接 -->
    <view class="bottom-link">
      <text class="link-item" @click="switchMode">{{ loginMode === 'sms' ? '账号密码登录' : '验证码登录' }}</text>
      <navigator class="link-item" url="/pageSubPack/loginSub/register-new-user">注册新用户</navigator>
    </view>

    <!-- 隐私协议弹窗 -->
    <privacy-popup v-model:show="showPrivacyPopup" @agree="agreePrivacy" @disagree="disagreePrivacy" @close="showPrivacyPopup = false" />
  </view>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import { getLoginBySms, getLoginPassword, getSendCode } from '../api/api.js'
import PrivacyPopup from '@/components/privacy-popup/privacy-popup.vue'
import { resetLoginLock } from '@/common/checkLogin.js'

// 输入框类型：统一用 text，避免 number 在真机上把 -/. 过滤掉导致手机号被误判合法；非法手机号由 canGetVerify 禁用获取验证码按钮
const inputType = 'text'

// ========== 模式切换 ==========
// 'sms' = 手机验证码登录, 'pwd' = 账号密码登录
const loginMode = ref('pwd')

// ========== 响应式数据 ==========
const phoneNumber = ref('')  // 短信登录：手机号
const verifyCode = ref('')   // 短信登录：验证码
const account = ref('')      // 密码登录：账号
const password = ref('')     // 密码登录：密码
const agreeAgreement = ref(false)
const placeholderStyle = ref('font-size:24rpx')

// 验证码倒计时
const countDown = ref(0)
let timer = null

// 隐私弹窗
const showPrivacyPopup = ref(false)
const pendingAction = ref('')

// ========== onLoad: 读取 mode 参数 ==========
onLoad((options) => {
  // 重置登录跳转锁，允许下次未登录时再次跳转
  resetLoginLock()
  if (options && options.mode === 'sms') {
    loginMode.value = 'sms'
  } else if (options && options.mode === 'pwd') {
    loginMode.value = 'pwd'
  }
})

// ========== 计算属性 ==========
// 短信模式：是否可获取验证码
const canGetVerify = computed(() => {
  if (loginMode.value !== 'sms') return false
  const phoneReg = /^1[3-9]\d{9}$/
  return phoneReg.test(phoneNumber.value)
})

// ========== 共享方法 ==========
const toggleAgreement = () => { agreeAgreement.value = !agreeAgreement.value }

const goToUserAgreement = () => {
  uni.navigateTo({ url: '/pageSubPack/loginSub/user-agreement' })
}

const goToPrivacy = () => {
  uni.navigateTo({ url: '/pageSubPack/loginSub/privacy' })
}

const openPrivacyPopup = (action) => {
  pendingAction.value = action || ''
  showPrivacyPopup.value = true
}

const agreePrivacy = () => {
  showPrivacyPopup.value = false
  agreeAgreement.value = true
  if (pendingAction.value === 'login') {
    doLogin()
  }
  pendingAction.value = ''
}

const disagreePrivacy = () => {
  showPrivacyPopup.value = false
  pendingAction.value = ''
}

// 切换登录模式
const switchMode = () => {
  if (loginMode.value === 'sms') {
    loginMode.value = 'pwd'
  } else {
    loginMode.value = 'sms'
  }
  // 重置相关字段
  agreeAgreement.value = false
  if (timer) { clearInterval(timer); timer = null }
  countDown.value = 0
}

// 忘记密码跳转
const goForgetPwd = () => {
  uni.navigateTo({ url: '/pageSubPack/loginSub/forget-pwd' })
}

// ========== 验证码登录：获取验证码 ==========
const getVerifyCode = () => {
  if (!canGetVerify.value) return
  uni.showLoading({ title: '发送中...', mask: true })
  getSendCode({ phone: phoneNumber.value, scene: 'login' }).then(res => {
    uni.hideLoading()
    if (res.code === 200) {
      uni.showToast({ title: '验证码已发送', icon: 'success' })
      countDown.value = 60
      timer = setInterval(() => {
        countDown.value--
        if (countDown.value <= 0) {
          clearInterval(timer)
          timer = null
        }
      }, 1000)
    } else {
      uni.showToast({ title: '验证码发送失败', icon: 'none' })
    }
  }).catch(err => {
    uni.hideLoading()
    uni.showToast({ title: err.msg || '网络异常', icon: 'none' })
  })
}

// ========== 登录处理（分发） ==========
const handleLogin = () => {
  if (loginMode.value === 'sms') {
    handleSmsLogin()
  } else {
    handlePwdLogin()
  }
}

// ========== 验证码登录 ==========
const handleSmsLogin = () => {
  if (!phoneNumber.value) { uni.showToast({ title: '请输入手机号', icon: 'none' }); return }
  if (!/^1[3-9]\d{9}$/.test(phoneNumber.value)) { uni.showToast({ title: '请输入正确的手机号', icon: 'none' }); return }
  if (!verifyCode.value) { uni.showToast({ title: '请输入验证码', icon: 'none' }); return }
  if (!/^\d{6}$/.test(verifyCode.value)) { uni.showToast({ title: '验证码为 6 位数字', icon: 'none' }); return }
  if (!agreeAgreement.value) { openPrivacyPopup('login'); return }
  doLogin()
}

// ========== 密码登录 ==========
const handlePwdLogin = () => {
  if (!account.value) { uni.showToast({ title: '请输入账号', icon: 'none' }); return }
  if (account.value.length < 4 || account.value.length > 20) { uni.showToast({ title: '账号长度需为 4-20 位', icon: 'none' }); return }
  if (!password.value) { uni.showToast({ title: '请输入密码', icon: 'none' }); return }
  if (password.value.length < 6) { uni.showToast({ title: '密码至少输入 6 位', icon: 'none' }); return }
  if (password.value.length > 16) { uni.showToast({ title: '密码不能超过 16 位', icon: 'none' }); return }
  if (/\s/.test(password.value)) { uni.showToast({ title: '密码格式不对', icon: 'none' }); return }
  if (!agreeAgreement.value) { openPrivacyPopup('login'); return }
  doLogin()
}

// ========== 执行登录 ==========
const doLogin = () => {
  uni.showLoading({ title: '登录中...', mask: true })
  const push_cid = uni.getStorageSync('push_cid')

  if (loginMode.value === 'sms') {
    // 验证码登录
    getLoginBySms({ phone: phoneNumber.value, smsCode: verifyCode.value, scene: 'login', cid: push_cid })
      .then(onLoginSuccess).catch(onLoginError)
  } else {
    // 密码登录
    getLoginPassword({ username: account.value, password: password.value, cid: push_cid })
      .then(onLoginSuccess).catch(onLoginError)
  }
}

const onLoginSuccess = (res) => {
  if (res.code === 200 && res.data) {
    // 换号登录时清除旧用户的所有缓存，防止新用户看到旧用户的小区数据和公告
    const oldUserId = uni.getStorageSync('userId')
    if (res.data.userId && String(oldUserId) !== String(res.data.userId)) {
      uni.removeStorageSync('home_cache')
      uni.removeStorageSync('home_cache_' + oldUserId)
      uni.removeStorageSync('communityName')
      uni.removeStorageSync('communityId')
      uni.removeStorageSync('needReloadUserInfo')
    }
    uni.setStorageSync('token', res.data.token)
    if (res.data.userId) { uni.setStorageSync('userId', res.data.userId) }
    const currentVillageId = res.data.currentVillageId || 0
    uni.setStorageSync('currentVillageId', currentVillageId)
    uni.hideLoading()
    uni.showToast({ title: '登录成功', icon: 'success' })
    setTimeout(() => { uni.switchTab({ url: '/pages/index/index' }) }, 1500)
  } else {
    uni.hideLoading()
    uni.showToast({ title: res.msg || '登录失败', icon: 'none' })
  }
}

const onLoginError = (err) => {
  uni.hideLoading()
  uni.showToast({ title: err.msg || '网络异常，请重试', icon: 'none' })
}

// ========== 生命周期 ==========
onUnmounted(() => {
  if (timer) { clearInterval(timer) }
})
</script>

<style scoped>
/* 页面容器 */
.login-page {
  padding: 80rpx 40rpx 40rpx;
  height: 100vh;
  overflow: hidden;
  box-sizing: border-box;
  background: repeating-linear-gradient(to bottom, #E2F0FF, #F6FAFF );
}

.status_bar {
  height: 160px;
  width: 100%;
}

/* 登录标题 */
.login-title {
  font-size: 52rpx;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 142rpx;
}

/* 输入框项 */
.input-item {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 40rpx;
  padding: 0 30rpx;
  height: 88rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

/* 验证码输入项（特殊布局） */
.verify-item {
  position: relative;
  padding-right: 220rpx;
}

/* 输入框图标 */
.input-icon {
  width: 50rpx;
  height: 50rpx;
  margin-right: 20rpx;
}

/* 输入框内容 */
.input-content {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  height: 100%;
}

/* 原生 input 垂直居中 */
.native-input {
  line-height: 88rpx;
}


/* 深度覆盖 uni-easyinput 内部默认样式 */
.input-content :deep(.uni-easyinput__content) {
  height: 100% !important;
  min-height: unset !important;
  padding: 0 !important;
  background-color: transparent !important;
}

.input-content :deep(.uni-easyinput__content-input) {
  height: 100% !important;
  min-height: unset !important;
  padding: 0 !important;
  line-height: 88rpx;
}

/* 验证码输入框 */
.verify-input {
  padding-right: 20rpx;
}

/* 获取验证码按钮 */
.get-verify-btn {
  position: absolute;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 200rpx;
  height: 70rpx;
  line-height: 70rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 35rpx;
  font-size: 28rpx;
  padding: 0;
  margin: 0;
}

.get-verify-btn:disabled {
  background-color: #ccc;
  color: #fff;
  border-radius: 50px;
}

.get-verify-btn::after {
  border-radius: 50px;
}

/* 协议和忘记密码行 */
.agreement-wrap {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin: 70rpx 0 28rpx 0;
  padding: 0 10rpx;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
  flex: 1;
  min-width: 0;
}

.checkbox-icon {
  flex-shrink: 0;
  margin-top: 2rpx;
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
  line-height: 1.5;
}

.agreePrivacy {
  color: #2F77FD;
}

.forget-pwd {
  font-size: 24rpx;
  color: #666;
  flex-shrink: 0;
  margin-left: 16rpx;
  line-height: 1.5;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-bottom: 60rpx;
}

.login-btn:disabled {
  background-color: #99c8ff;
  color: #fff;
}

button:after {
  border-radius: 8px;
}

/* 底部链接 */
.bottom-link {
  display: flex;
  justify-content: space-between;
  padding: 0 20rpx;
}

.link-item {
  font-size: 28rpx;
  color: #007aff;
  text-decoration: none;
}
</style>
