<template>
  <view class="login-page">
    <!-- 顶部装饰 -->
    <view class="header-decoration">
      <view class="decoration-circle circle-1"></view>
      <view class="decoration-circle circle-2"></view>
    </view>

    <!-- Logo 区域 -->
    <view class="logo-section">
      <view class="logo-icon">
        <u-icon name="home-fill" :size="60" color="#fff" />
      </view>
      <text class="app-name">品住会</text>
      <text class="app-slogan">舒适住宿，温馨服务</text>
    </view>

    <!-- 登录选项区域 -->
    <view class="form-section">
      <text class="form-title">欢迎使用</text>
      <text class="form-subtitle">选择登录方式</text>

      <!-- 一键登录按钮（微信获取手机号） -->
      <button
        v-if="isWechatMiniProgram"
        class="quick-login-button"
        open-type="getPhoneNumber"
        @getphonenumber="handleQuickLogin"
      >
        <u-icon name="phone-fill" :size="24" color="#fff" style="margin-right: 12rpx;" />
        一键登录
      </button>

      <!-- 手机号安全登录按钮 -->
      <button class="phone-login-button" @tap="handleShowPhoneModal">
        <u-icon name="lock-fill" :size="24" color="#fff" style="margin-right: 12rpx;" />
        手机号安全登录
      </button>

      <!-- 暂时不登录文字按钮 -->
      <view class="skip-login-text" @tap="handleSkipLogin">
        暂时不登录
      </view>

      <!-- 协议勾选 -->
      <view class="agreement-section">
        <view class="checkbox-wrapper" @tap="toggleAgreement">
          <view class="checkbox" :class="{ checked: agreed }">
            <view v-if="agreed" class="check-icon">
              <u-icon name="checkmark" :size="16" color="#fff" />
            </view>
          </view>
          <text class="agreement-text">
            我已阅读并同意
            <text class="link" @tap.stop="handleViewAgreement('user')">《用户协议》</text>
            和
            <text class="link" @tap.stop="handleViewAgreement('privacy')">《隐私政策》</text>
          </text>
        </view>
      </view>
    </view>

    <!-- 协议确认弹窗 -->
    <view v-if="showAgreementModal" class="modal-overlay" @tap="closeAgreementModal">
      <view class="modal-content" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">服务协议及隐私保护</text>
        </view>
        <view class="modal-body">
          <text class="modal-text">
            为了更好的保障您的合法权益，请您阅读并同意以下协议
            <text class="link" @tap.stop="handleViewAgreement('user')">《用户协议》</text>
            和
            <text class="link" @tap.stop="handleViewAgreement('privacy')">《隐私政策》</text>
          </text>
        </view>
        <view class="modal-footer">
          <button class="modal-button cancel" @tap="closeAgreementModal">取消</button>
          <button class="modal-button confirm" @tap="confirmAgreement">确定</button>
        </view>
      </view>
    </view>

    <!-- 手机号登录弹窗 -->
    <view v-if="showPhoneModal" class="modal-overlay" @tap="closePhoneModal">
      <view class="modal-content phone-modal" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">手机号安全登录</text>
          <view class="modal-close" @tap="closePhoneModal">
            <u-icon name="close" :size="20" color="#999" />
          </view>
        </view>
        <view class="modal-body">
          <!-- 手机号输入 -->
          <view class="input-group">
            <view class="input-wrapper">
              <text class="input-prefix">+86</text>
              <input
                v-model="phone"
                type="number"
                maxlength="11"
                placeholder="请输入手机号"
                class="input"
                placeholder-class="placeholder"
              />
            </view>
          </view>

          <!-- 验证码输入 -->
          <view class="input-group">
            <view class="input-wrapper">
              <input
                v-model="code"
                type="number"
                maxlength="6"
                placeholder="请输入验证码"
                class="input"
                placeholder-class="placeholder"
              />
              <text
                class="code-btn"
                :class="{ disabled: countdown > 0 }"
                @tap="handleSendCode"
              >
                {{ countdown > 0 ? `${countdown}s` : '获取验证码' }}
              </text>
            </view>
          </view>

          <!-- 登录按钮 -->
          <button class="modal-login-button" @tap="handlePhoneLogin">登录</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { sendCode, loginByPhone, loginByWechatPhone } from '@/api/user/auth';
import { useUserStore } from '@/store/user';

const phone = ref('');
const code = ref('');
const countdown = ref(0);
const agreed = ref(false);
const isWechatMiniProgram = ref(false);
const showAgreementModal = ref(false);
const showPhoneModal = ref(false);
const userStore = useUserStore();

let timer: ReturnType<typeof setInterval> | null = null;
let pendingAction: (() => void) | null = null;

onMounted(() => {
  // 判断运行环境
  const systemInfo = uni.getSystemInfoSync();
  isWechatMiniProgram.value = systemInfo.uniPlatform === 'mp-weixin';
});

function toggleAgreement() {
  agreed.value = !agreed.value;
}

// 检查协议是否同意
function checkAgreement(action: () => void) {
  if (!agreed.value) {
    pendingAction = action;
    showAgreementModal.value = true;
    return false;
  }
  return true;
}

// 关闭协议弹窗
function closeAgreementModal() {
  showAgreementModal.value = false;
  pendingAction = null;
}

// 确认协议
function confirmAgreement() {
  agreed.value = true;
  showAgreementModal.value = false;
  if (pendingAction) {
    pendingAction();
    pendingAction = null;
  }
}

// 一键登录（微信获取手机号）
async function handleQuickLogin(e: any) {
  const action = async () => {
    try {
      const { code, encryptedData, iv } = e.detail;

      if (!code) {
        uni.showToast({ title: '获取手机号失败', icon: 'none' });
        return;
      }

      uni.showLoading({ title: '登录中...' });

      // 获取待绑定的邀请码
      const inviteCode = uni.getStorageSync('pendingInviteCode');

      // 调用后端接口，使用微信手机号登录
      const res = await loginByWechatPhone(code, encryptedData, iv, inviteCode);

      // 登录成功后清除邀请码
      if (inviteCode) {
        uni.removeStorageSync('pendingInviteCode');
      }

      userStore.setLogin(res.data);
      uni.hideLoading();
      uni.showToast({ title: '登录成功', icon: 'success' });

      setTimeout(() => {
        uni.switchTab({ url: '/pages/index/index' });
      }, 500);
    } catch (error: any) {
      uni.hideLoading();
      console.error('一键登录失败', error);
      uni.showToast({
        title: error.message || '登录失败，请重试',
        icon: 'none'
      });
    }
  };

  if (!checkAgreement(action)) {
    return;
  }

  await action();
}

// 显示手机号登录弹窗
function handleShowPhoneModal() {
  const action = () => {
    showPhoneModal.value = true;
  };

  if (!checkAgreement(action)) {
    return;
  }

  action();
}

// 关闭手机号登录弹窗
function closePhoneModal() {
  showPhoneModal.value = false;
  phone.value = '';
  code.value = '';
  if (timer) {
    clearInterval(timer);
    timer = null;
    countdown.value = 0;
  }
}

// 暂时不登录
function handleSkipLogin() {
  uni.switchTab({ url: '/pages/index/index' });
}

// 查看协议
function handleViewAgreement(type: 'user' | 'privacy') {
  uni.navigateTo({
    url: `/pages/agreement/index?type=${type}`
  });
}

// 发送验证码
async function handleSendCode() {
  if (countdown.value > 0) return;

  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }

  try {
    await sendCode(phone.value);
    uni.showToast({ title: '验证码已发送', icon: 'success' });
    countdown.value = 60;
    timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0 && timer) {
        clearInterval(timer);
        timer = null;
      }
    }, 1000);
  } catch (e) {
    console.error(e);
  }
}

// 手机号登录
async function handlePhoneLogin() {
  if (!phone.value || !code.value) {
    uni.showToast({ title: '请填写完整信息', icon: 'none' });
    return;
  }

  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }

  if (code.value.length !== 6) {
    uni.showToast({ title: '请输入6位验证码', icon: 'none' });
    return;
  }

  try {
    uni.showLoading({ title: '登录中...' });

    // 获取待绑定的邀请码
    const inviteCode = uni.getStorageSync('pendingInviteCode');

    const res = await loginByPhone(phone.value, code.value, inviteCode);

    // 登录成功后清除邀请码
    if (inviteCode) {
      uni.removeStorageSync('pendingInviteCode');
    }

    userStore.setLogin(res.data);
    uni.hideLoading();
    uni.showToast({ title: '登录成功', icon: 'success' });
    closePhoneModal();
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index/index' });
    }, 500);
  } catch (e) {
    uni.hideLoading();
    console.error(e);
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0 48rpx;
  position: relative;
  overflow: hidden;
}

// 顶部装饰
.header-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 400rpx;
  overflow: hidden;

  .decoration-circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);

    &.circle-1 {
      width: 300rpx;
      height: 300rpx;
      top: -100rpx;
      right: -50rpx;
    }

    &.circle-2 {
      width: 200rpx;
      height: 200rpx;
      top: 100rpx;
      left: -80rpx;
    }
  }
}

// Logo 区域
.logo-section {
  position: relative;
  z-index: 1;
  padding-top: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;

  .logo-icon {
    width: 120rpx;
    height: 120rpx;
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10rpx);
    border-radius: 30rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 24rpx;
    box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  }

  .app-name {
    font-size: 48rpx;
    font-weight: 700;
    color: #fff;
    margin-bottom: 12rpx;
    letter-spacing: 2rpx;
  }

  .app-slogan {
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

// 表单区域
.form-section {
  position: relative;
  z-index: 1;
  background: #fff;
  border-radius: 32rpx;
  padding: 48rpx 40rpx;
  box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.15);

  .form-title {
    font-size: 36rpx;
    font-weight: 700;
    color: #222;
    display: block;
    margin-bottom: 12rpx;
  }

  .form-subtitle {
    font-size: 26rpx;
    color: #666;
    display: block;
    margin-bottom: 48rpx;
  }
}

// 登录按钮样式
.quick-login-button,
.phone-login-button {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  margin-bottom: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &:active {
    transform: translateY(2rpx);
  }
}

.quick-login-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);

  &:active {
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  }
}

.phone-login-button {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(245, 87, 108, 0.3);

  &:active {
    box-shadow: 0 4rpx 16rpx rgba(245, 87, 108, 0.4);
  }
}

// 暂时不登录文字按钮
.skip-login-text {
  text-align: center;
  font-size: 28rpx;
  color: #999;
  padding: 24rpx 0;
  margin-bottom: 16rpx;
  transition: color 0.2s;

  &:active {
    color: #667eea;
  }
}

// 协议
.agreement-section {
  margin-bottom: 0;
}

.checkbox-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 12rpx;

  .checkbox {
    width: 32rpx;
    height: 32rpx;
    border: 2rpx solid #ddd;
    border-radius: 6rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-top: 2rpx;
    transition: all 0.2s;

    &.checked {
      background: #667eea;
      border-color: #667eea;

      .check-icon {
        font-size: 20rpx;
        color: #fff;
        font-weight: 700;
        line-height: 1;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .agreement-text {
    flex: 1;
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;

    .link {
      color: #667eea;
    }
  }
}

// 弹窗遮罩
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 0 48rpx;
}

// 弹窗内容
.modal-content {
  background: #fff;
  border-radius: 24rpx;
  width: 100%;
  max-width: 600rpx;
  overflow: hidden;
  animation: modalSlideUp 0.3s ease-out;
}

@keyframes modalSlideUp {
  from {
    opacity: 0;
    transform: translateY(50rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: 40rpx 32rpx 24rpx;
  position: relative;

  .modal-title {
    font-size: 32rpx;
    font-weight: 700;
    color: #222;
    display: block;
    text-align: center;
  }

  .modal-close {
    position: absolute;
    top: 32rpx;
    right: 32rpx;
    width: 48rpx;
    height: 48rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.modal-body {
  padding: 0 32rpx 32rpx;

  .modal-text {
    font-size: 28rpx;
    color: #666;
    line-height: 1.8;
    display: block;

    .link {
      color: #667eea;
    }
  }
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #f0f0f0;

  .modal-button {
    flex: 1;
    height: 96rpx;
    line-height: 96rpx;
    font-size: 30rpx;
    font-weight: 600;
    border: none;
    background: transparent;
    transition: all 0.2s;

    &.cancel {
      color: #999;
      border-right: 1rpx solid #f0f0f0;

      &:active {
        background: #f7f8fa;
      }
    }

    &.confirm {
      color: #667eea;

      &:active {
        background: rgba(102, 126, 234, 0.1);
      }
    }
  }
}

// 手机号登录弹窗
.phone-modal {
  .modal-body {
    padding: 24rpx 32rpx 40rpx;
  }
}

// 输入框组
.input-group {
  margin-bottom: 24rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  height: 96rpx;
  background: #f7f8fa;
  border-radius: 16rpx;
  padding: 0 24rpx;
  transition: all 0.3s;

  &:focus-within {
    background: #fff;
    box-shadow: 0 0 0 2rpx #667eea;
  }

  .input-prefix {
    font-size: 28rpx;
    color: #666;
    margin-right: 16rpx;
    padding-right: 16rpx;
    border-right: 2rpx solid #e0e0e0;
  }

  .input {
    flex: 1;
    font-size: 28rpx;
    color: #222;
    height: 96rpx;
    line-height: 96rpx;
    background: transparent;
  }

  .placeholder {
    color: #bbb;
  }

  .code-btn {
    font-size: 26rpx;
    font-weight: 600;
    color: #667eea;
    white-space: nowrap;
    padding: 12rpx 20rpx;
    background: rgba(102, 126, 234, 0.1);
    border-radius: 8rpx;
    transition: all 0.2s;

    &:active:not(.disabled) {
      background: rgba(102, 126, 234, 0.2);
    }

    &.disabled {
      color: #bbb;
      background: #f0f0f0;
    }
  }
}

// 弹窗内登录按钮
.modal-login-button {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border-radius: 16rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  margin-top: 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s;

  &:active {
    transform: translateY(2rpx);
    box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.4);
  }
}
</style>
