<template>
  <view class="login-page">
    <view class="brand-area">
      <image class="logo" src="/static/logo.png" mode="aspectFit" />
      <text class="brand-title">小鹅通</text>
      <view class="slogan-area">
        <text class="slogan">让知识创造价值</text>
        <view class="slogan-underline"></view>
      </view>
    </view>
    <view class="phone-area">
      <text class="phone">199****4261</text>
      <text class="carrier">号码认证由中国电信提供</text>
    </view>
    <button class="main-btn login-btn" :disabled="!agreed" @tap="handleLogin">一键登录</button>
    <button class="main-btn wechat-btn" :disabled="!agreed" @tap="socialLogin('wechat')">
      <image class="wechat-icon" src="/static/wechat.png" /> 微信登录
    </button>
    <view class="protocol-area">
      <checkbox :checked="agreed" @tap="agreed = !agreed" color="#2979ff" />
      <text class="protocol-text">
        我已阅读并同意
        <text class="link" @tap="openProtocol('service')">《服务协议》</text>、
        <text class="link" @tap="openProtocol('privacy')">《隐私政策》</text>
      </text>
    </view>
    <view class="other-login">
      <text class="other-title">其他方式登录</text>
      <view class="other-icons">
        <view  @tap="showLoginPopup = true">
	 <image class="icon" src="/static/phone.png" />
	</view>
        <view >
          <image class="icon" src="/static/qq.png" />
        </view>
      </view>
    </view>

    <!-- 登录弹窗 -->
    <view v-if="showLoginPopup" class="popup-mask">
      <view class="popup-box">
        <text class="close-btn" @tap="showLoginPopup = false">×</text>
        <view class="popup-title">登录</view>
        <view class="popup-tabs">
          <text :class="{active: loginTab==='phone'}" @tap="loginTab='phone'">手机号登录</text>
          <text :class="{active: loginTab==='account'}" @tap="loginTab='account'">账号密码登录</text>
        </view>
        <view v-if="loginTab==='phone'">
          <view class="input-row">
            <input v-model="loginPhone" placeholder="请输入手机号" />
          </view>
          <view class="input-row code-row">
            <input v-model="loginCode" placeholder="请输入验证码" />
            <button class="code-btn" :disabled="loginCodeCountdown > 0" @tap="getLoginCode">
              {{ loginCodeCountdown > 0 ? loginCodeCountdown + 's' : '获取验证码' }}
            </button>
          </view>
        </view>
        <view v-else>
          <view class="input-row">
            <input v-model="loginAccount" placeholder="请输入账号" />
          </view>
          <view class="input-row">
            <input v-model="loginPassword" type="password" password placeholder="请输入密码" />
          </view>
        </view>
        <button class="main-btn popup-login-btn" @tap="handlePopupLogin">登录</button>
        <view class="popup-footer">
          <text @tap="openRegister">去注册</text>
        </view>
      </view>
    </view>

    <!-- 注册弹窗 -->
    <view v-if="showRegisterPopup" class="popup-mask">
      <view class="popup-box">
        <text class="close-btn" @tap="showRegisterPopup = false">×</text>
        <view class="popup-title">注册</view>
        <view class="input-row">
          <input v-model="regPhone" placeholder="请输入手机号" />
        </view>
        <view class="input-row code-row">
          <input v-model="regCode" placeholder="请输入验证码" />
          <button class="code-btn" @tap="getRegCode">
			{{ regCodeCountdown > 0 ? regCodeCountdown + 's' : '获取验证码' }}
		  </button>
        </view>
        <view class="input-row">
          <input v-model="regAccount" placeholder="请输入账号" />
        </view>
        <view class="input-row">
          <input v-model="regPassword" type="password" placeholder="请输入密码" />
        </view>
        <button class="main-btn popup-login-btn" @tap="handleRegister">注册</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue'

const agreed = ref(false)
const showLoginPopup = ref(false)
const showRegisterPopup = ref(false)
const loginTab = ref('phone')
const loginPhone = ref('')
const loginCode = ref('')
const loginAccount = ref('')
const loginPassword = ref('')
const regPhone = ref('')
const regCode = ref('')
const regAccount = ref('')
const regPassword = ref('')
const loginCodeCountdown = ref(0)
const regCodeCountdown = ref(0)
let loginCodeTimer = null
let regCodeTimer = null

function handleLogin() {
  if (!agreed.value) {
    uni.showToast({ title: '请先同意协议', icon: 'none' })
    return
  }
  // 登录逻辑
}
function openProtocol(type) {
  const urls = {
    service: '/pages/protocol/service',
    privacy: '/pages/protocol/privacy'
  }
  uni.navigateTo({ url: urls[type] })
}
function socialLogin(type) {
  // 微信、QQ等登录逻辑
}
function openRegister() {
  showLoginPopup.value = false
  showRegisterPopup.value = true
}
function getLoginCode() {
  if (loginCodeCountdown.value > 0) return;
  if (!/^1[3-9]\d{9}$/.test(loginPhone.value)) {
    uni.showToast({ title: '请输入正确手机号', icon: 'none' });
    return;
  }
  
  // 先启动倒计时
  loginCodeCountdown.value = 60;
  loginCodeTimer = setInterval(() => {
    if (loginCodeCountdown.value > 0) {
      loginCodeCountdown.value--;
    } else {
      clearInterval(loginCodeTimer);
      loginCodeTimer = null;
    }
  }, 1000);

  console.log('开始获取验证码...');
  uni.request({
    url: 'http://localhost:9500/user/code',
    method: 'POST',
    data: { phone: loginPhone.value },
    success(res) {
      console.log('验证码响应:', res.data);
      if (res.statusCode === 200) {
        uni.showToast({ title: '验证码已发送', icon: 'none' });
      } else {
        uni.showToast({ title: res.data.msg || '发送失败', icon: 'none' });
      }
    },
    fail(err) {
      console.error('获取验证码失败:', err);
      uni.showToast({ title: '网络错误', icon: 'none' });
    }
  });
}
function getRegCode() {
  if (regCodeCountdown.value > 0) return;
  if (!/^1[3-9]\d{9}$/.test(regPhone.value)) {
    uni.showToast({ title: '请输入正确手机号', icon: 'none' });
    return;
  }
  
  // 先启动倒计时
  regCodeCountdown.value = 60;
  regCodeTimer = setInterval(() => {
    if (regCodeCountdown.value > 0) {
      regCodeCountdown.value--;
    } else {
      clearInterval(regCodeTimer);
      regCodeTimer = null;
    }
  }, 1000);

  console.log('开始获取注册验证码...');
  uni.request({
    url: 'http://localhost:9500/user/code',
    method: 'POST',
    data: { phone: regPhone.value },
    success(res) {
      console.log('验证码响应:', res.data);
      if (res.statusCode === 200) {
        uni.showToast({ title: '验证码已发送', icon: 'none' });
      } else {
        uni.showToast({ title: res.data.msg || '发送失败', icon: 'none' });
      }
    },
    fail(err) {
      console.error('获取验证码失败:', err);
      uni.showToast({ title: '网络错误', icon: 'none' });
    }
  });
}
function handlePopupLogin() {
  if (loginTab.value === 'phone') {
    if (!/^1[3-9]\d{9}$/.test(loginPhone.value)) {
      uni.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }
    if (!loginCode.value) {
      uni.showToast({ title: '请输入验证码', icon: 'none' });
      return;
    }
    
    console.log('开始登录请求...');
    uni.request({
      url: 'http://localhost:9500/user/login',
      method: 'POST',
      data: {
        phone: loginPhone.value,
        code: loginCode.value
      },
      success(res) {
        console.log('登录响应数据:', res.data);
        console.log('响应状态码:', res.statusCode);
        
        // 检查响应状态码和数据结构
        if (res.statusCode === 200) {
          // 存储登录信息
          uni.setStorageSync('userPhone', loginPhone.value);
          uni.setStorageSync('isLoggedIn', true);
          
          // 关闭弹窗
          showLoginPopup.value = false;
          
          // 显示成功提示
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
          
          // 直接使用 reLaunch 跳转
          console.log('开始跳转到首页...');
          uni.reLaunch({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转成功');
            },
            fail: (err) => {
              console.error('reLaunch 跳转失败:', err);
              // 如果 reLaunch 失败，尝试使用 switchTab
              console.log('尝试使用 switchTab 跳转...');
              uni.switchTab({
                url: '/pages/index/index',
                success: () => {
                  console.log('switchTab 跳转成功');
                },
                fail: (err) => {
                  console.error('switchTab 跳转失败:', err);
                  uni.showToast({
                    title: '页面跳转失败，请重试',
                    icon: 'none'
                  });
                }
              });
            }
          });
        } else {
          console.log('登录失败，状态码:', res.statusCode);
          uni.showToast({ 
            title: res.data.msg || '登录失败，请重试', 
            icon: 'none' 
          });
        }
      },
      fail(err) {
        console.error('登录请求失败:', err);
        uni.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  } else {
    if (!loginAccount.value) {
      uni.showToast({ title: '请输入账号', icon: 'none' });
      return;
    }
    if (!loginPassword.value) {
      uni.showToast({ title: '请输入密码', icon: 'none' });
      return;
    }
    
    console.log('开始登录请求...');
    uni.request({
      url: 'http://localhost:9500/user/loginup',
      method: 'POST',
      data: { 
        username: loginAccount.value, 
        password: loginPassword.value 
      },
      success(res) {
        console.log('登录响应数据:', res.data);
        console.log('响应状态码:', res.statusCode);
        
        // 检查响应状态码和数据结构
        if (res.statusCode === 200 && res.data.code === 200) {
          // 存储登录信息
          uni.setStorageSync('userPhone', loginAccount.value);
          uni.setStorageSync('isLoggedIn', true);
          
          // 关闭弹窗
          showLoginPopup.value = false;
          
          // 显示成功提示
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1500
          });
          
          // 直接使用 reLaunch 跳转
          console.log('开始跳转到首页...');
          uni.reLaunch({
            url: '/pages/index/index',
            success: () => {
              console.log('跳转成功');
            },
            fail: (err) => {
              console.error('reLaunch 跳转失败:', err);
              // 如果 reLaunch 失败，尝试使用 switchTab
              console.log('尝试使用 switchTab 跳转...');
              uni.switchTab({
                url: '/pages/index/index',
                success: () => {
                  console.log('switchTab 跳转成功');
                },
                fail: (err) => {
                  console.error('switchTab 跳转失败:', err);
                  uni.showToast({
                    title: '页面跳转失败，请重试',
                    icon: 'none'
                  });
                }
              });
            }
          });
        } else {
          console.log('登录失败，状态码:', res.statusCode);
          console.log('登录失败，错误信息:', res.data.msg);
          uni.showToast({ 
            title: res.data.msg || '账号或密码错误', 
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail(err) {
        console.error('登录请求失败:', err);
        uni.showToast({ 
          title: '网络错误，请稍后重试', 
          icon: 'none',
          duration: 2000
        });
      }
    });
  }
}
function handleRegister() {
  if (!/^1[3-9]\d{9}$/.test(regPhone.value)) {
    uni.showToast({ title: '请输入正确手机号', icon: 'none' });
    return;
  }
  if (!regCode.value) {
    uni.showToast({ title: '请输入验证码', icon: 'none' });
    return;
  }
  if (!regAccount.value) {
    uni.showToast({ title: '请输入账号', icon: 'none' });
    return;
  }
  if (!regPassword.value) {
    uni.showToast({ title: '请输入密码', icon: 'none' });
    return;
  }
  
  console.log('开始注册请求...');
  uni.request({
    url: 'http://localhost:9500/user/register',
    method: 'POST',
    data: {
      phone: regPhone.value,
      code: regCode.value,
      username: regAccount.value,
      password: regPassword.value
    },
    success(res) {
      console.log('注册响应数据:', res.data);
      console.log('响应状态码:', res.statusCode);
      
      if (res.statusCode === 200) {
        // 显示成功提示
        uni.showToast({
          title: '注册成功',
          icon: 'success',
          duration: 1500
        });
        
        // 关闭注册弹窗
        showRegisterPopup.value = false;
        
        // 延迟后打开登录弹窗
        setTimeout(() => {
          showLoginPopup.value = true;
          loginTab.value = 'phone';
          // 自动填充手机号
          loginPhone.value = regPhone.value;
        }, 1500);
      } else {
        console.log('注册失败，状态码:', res.statusCode);
        uni.showToast({ 
          title: res.data.msg || '注册失败，请重试', 
          icon: 'none' 
        });
      }
    },
    fail(err) {
      console.error('注册请求失败:', err);
      uni.showToast({ title: '网络错误', icon: 'none' });
    }
  });
}

onUnmounted(() => {
  if (loginCodeTimer) clearInterval(loginCodeTimer)
  if (regCodeTimer) clearInterval(regCodeTimer)
})
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  padding: 0 40rpx;
}
.brand-area {
  margin-top: 100rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  .logo {
    width: 120rpx;
    height: 120rpx;
    margin-bottom: 20rpx;
  }
  .brand-title {
    font-size: 44rpx;
    font-weight: bold;
    color: #222;
    margin-bottom: 20rpx;
  }
  .slogan-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    .slogan {
      font-size: 28rpx;
      color: #2979ff;
      margin-bottom: 8rpx;
    }
    .slogan-underline {
      width: 220rpx;
      height: 8rpx;
      background: #e3f0ff;
      border-radius: 4rpx;
    }
  }
}
.phone-area {
  margin: 500rpx 0 40rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  .phone {
    font-size: 36rpx;
    color: #222;
    font-weight: 500;
    margin-bottom: 10rpx;
  }
  .carrier {
    font-size: 24rpx;
    color: #aaa;
  }
}
.main-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 32rpx;
}
.login-btn {
  background: #1976ff;
  color: #fff;
  border: none;
}
.wechat-btn {
  background: #1aad19;
  color: #fff;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  .wechat-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 16rpx;
    vertical-align: middle;
  }
}
.protocol-area {
  display: flex;
  align-items: center;
  margin: 30rpx 0 0 0;
  .protocol-text {
    font-size: 22rpx;
    color: #999;
    margin-left: 10rpx;
    .link {
      color: #1976ff;
    }
  }
}
.other-login {
  margin-top: 80rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  .other-title {
    font-size: 24rpx;
    color: #bbb;
    margin-bottom: 20rpx;
  }
  .other-icons {
    display: flex;
    gap: 60rpx;
    .icon {
      width: 60rpx;
      height: 60rpx;
    }
  }
}
.icon-circle {
  width: 80rpx;
  height: 80rpx;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 20rpx;
  background: #fff;
}
.popup-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.popup-box {
  width: 90vw;
  max-width: 600rpx;
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.10);
  padding: 60rpx 40rpx 40rpx 40rpx;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.close-btn {
  position: absolute;
  right: 32rpx;
  top: 24rpx;
  font-size: 48rpx;
  color: #bbb;
  z-index: 2;
  font-weight: bold;
}
.popup-title {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #222;
  margin-bottom: 32rpx;
  letter-spacing: 2rpx;
}
.popup-tabs {
  display: flex;
  justify-content: center;
  margin-bottom: 32rpx;
  text {
    font-size: 28rpx;
    margin: 0 36rpx;
    color: #888;
    padding-bottom: 8rpx;
    position: relative;
    &.active {
      color: #1976ff;
      font-weight: bold;
    }
    &.active::after {
      content: '';
      display: block;
      position: absolute;
      left: 0; right: 0; bottom: 0;
      height: 4rpx;
      background: #1976ff;
      border-radius: 2rpx;
    }
  }
}
.input-row {
  margin-bottom: 28rpx;
  display: flex;
  align-items: center;
  input {
    flex: 1;
    height: 80rpx;
    border-radius: 40rpx;
    background: #f7f8fa;
    border: 1px solid #eee;
    padding: 0 32rpx;
    font-size: 28rpx;
    color: #333;
  }
}
.code-row {
  input {
    flex: 1;
    margin-right: 16rpx;
  }
  .code-btn {
    width: 160rpx;
    height: 64rpx;
    border-radius: 32rpx;
    background: #1976ff;
    color: #fff;
    font-size: 24rpx;
    border: none;
    padding: 0;
  }
}
.popup-login-btn {
  margin-top: 12rpx;
  margin-bottom: 16rpx;
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 500;
  background: #1976ff;
  color: #fff;
  border: none;
}
.popup-footer {
  text-align: center;
  margin-top: 10rpx;
  color: #1976ff;
  font-size: 26rpx;
  font-weight: 500;
  letter-spacing: 1rpx;
}
</style>