<template>
  <view class="container">
    <!-- 背景层 -->
    <view class="bg-layer">
      <view class="gradient-orb"></view>
    </view>

    <!-- 主内容区 -->
    <view class="main-content">
      <!-- 品牌展示区 -->
      <view class="brand-showcase">
        <view class="logo-wrapper">
          <view class="logo-ring">
            <view class="logo-glow"></view>
            <view class="logo-circle">
              <image class="logo" src="/static/brand-logo.svg" mode="aspectFit"></image>
            </view>
          </view>
        </view>

        <text class="brand-name">AI零售柜</text>
        <text class="brand-desc">扫码开门 · 即拿即走</text>

        <view class="feature-tags">
          <view class="tag">
            <text class="tag-text">秒级开门</text>
          </view>
          <view class="tag">
            <text class="tag-text">安全支付</text>
          </view>
          <view class="tag">
            <text class="tag-text">AI识别</text>
          </view>
        </view>
      </view>

      <!-- 登录卡片 -->
      <view class="login-card">
        <view class="card-header">
          <view class="header-line"></view>
          <text class="card-title">快速登录</text>
          <view class="header-line"></view>
        </view>

        <button
          class="login-btn"
          open-type="getPhoneNumber"
          @getphonenumber="onGetPhoneNumber"
          :loading="isLoading"
          hover-class="login-btn-hover"
        >
          <text class="login-btn-text">一键登录</text>
        </button>
      </view>

      <!-- 用户协议 -->
      <view class="agreement">
        <text class="agreement-text">登录即表示您已阅读并同意</text>
        <view class="agreement-links">
          <text class="link" @tap="goToServiceAgreement">《用户服务协议》</text>
          <text class="link-sep">与</text>
          <text class="link" @tap="goToPrivacyPolicy">《隐私政策》</text>
        </view>
      </view>

      <!-- 底部装饰 -->
      <view class="footer-dots">
        <view class="dot"></view>
        <view class="dot"></view>
        <view class="dot"></view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { loginByMiniappPhone } from '@/api/user';
import type { LoginResult } from '@/api/user';
import { setToken, setUserInfo } from '@/utils/auth';
import { logger } from '@/utils/logger';

const isLoading = ref(false);

const redirectUrl = ref('');

onLoad((options: any) => {
  if (options.redirect) {
    redirectUrl.value = decodeURIComponent(options.redirect);
  }
});

const onGetPhoneNumber = async (e: any) => {
  logger.log('[登录] 获取手机号事件:', e.detail);

  if (e.detail.errMsg !== 'getPhoneNumber:ok') {
    logger.error('[登录] 获取手机号失败:', e.detail.errMsg);
    uni.showToast({
      title: '获取手机号失败，请重试',
      icon: 'none'
    });
    return;
  }

  isLoading.value = true;
  uni.showLoading({ title: '登录中...' });

  try {
    logger.log('[登录] 开始获取login code...');
    const loginRes = await new Promise<any>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          logger.log('[登录] login成功:', res);
          resolve(res);
        },
        fail: (err) => {
          logger.error('[登录] login失败:', err);
          reject(err);
        }
      });
    });

    logger.log('[登录] loginRes:', loginRes);
    logger.log('[登录] phoneCode:', e.detail.code);

    const { code, encryptedData, iv } = e.detail;
    const res = await loginByMiniappPhone({
      code: loginRes.code,
      phoneCode: code
    });
    logger.log('[登录] 登录成功:', res);
    handleLoginSuccess(res);
  } catch (error: any) {
    logger.error('[登录] 微信手机号登录失败', error);
    logger.error('[登录] 错误详情:', error.message || error);
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none',
      duration: 3000
    });
  } finally {
    uni.hideLoading();
    isLoading.value = false;
  }
};

const handleLoginSuccess = (res: LoginResult) => {
  logger.log('[登录成功] 收到的响应数据:', res);
  logger.log('[登录成功] token:', res.token);
  logger.log('[登录成功] userInfo:', res.userInfo);

  setToken(res.token);
  setUserInfo(res.userInfo);

  const savedToken = uni.getStorageSync('accessToken');
  logger.log('[登录成功] 保存后验证 - token:', savedToken ? '已保存' : '保存失败');

  uni.vibrateShort({ type: 'medium' });

  uni.showToast({
    title: '登录成功',
    icon: 'success'
  });

  setTimeout(() => {
    if (redirectUrl.value) {
      uni.reLaunch({ url: redirectUrl.value });
    } else {
      const pages = getCurrentPages();
      if (pages.length > 1) {
        uni.navigateBack();
      } else {
        uni.reLaunch({ url: '/pages/index/index' });
      }
    }
  }, 1000);
};

const goToServiceAgreement = () => {
  uni.navigateTo({
    url: '/pages/agreement/serviceAgreement'
  });
};

const goToPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/agreement/privacyPolicy'
  });
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: linear-gradient(180deg, $color-primary-bg 0%, #FFF9E6 30%, $color-bg-secondary 100%);
  position: relative;
  overflow: hidden;
}

/* ========== 背景层 ========== */
.bg-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  pointer-events: none;
}

.gradient-orb {
  position: absolute;
  width: 500rpx;
  height: 500rpx;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(255, 215, 0, 0.15) 0%, transparent 70%);
  top: -120rpx;
  right: -80rpx;
  animation: orb-float 8s ease-in-out infinite;
}

/* ========== 主内容区 ========== */
.main-content {
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 48rpx;
  padding-bottom: calc(80rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(80rpx + env(safe-area-inset-bottom));
}

/* ========== 品牌展示区 ========== */
.brand-showcase {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 160rpx;
  padding-bottom: 72rpx;
  animation: slide-down 0.35s $ease-out;
}

.logo-wrapper {
  margin-bottom: 48rpx;

  .logo-ring {
    width: 220rpx;
    height: 220rpx;
    border-radius: 50%;
    border: 2rpx solid rgba(255, 193, 7, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    animation: ring-rotate 30s linear infinite;

    .logo-glow {
      position: absolute;
      width: 200rpx;
      height: 200rpx;
      border-radius: 50%;
      background: radial-gradient(circle, rgba(255, 193, 7, 0.12) 0%, transparent 70%);
      animation: glow-pulse 3s ease-in-out infinite;
    }

    .logo-circle {
      width: 170rpx;
      height: 170rpx;
      background: $color-bg-primary;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: $shadow-md, inset 0 2rpx 8rpx rgba(255, 255, 255, 0.6);
      padding: 32rpx;
      position: relative;
      z-index: 1;

      .logo {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.brand-name {
  font-size: 48rpx;
  font-weight: 700;
  color: $color-text-primary;
  letter-spacing: 6rpx;
  margin-bottom: 12rpx;
}

.brand-desc {
  font-size: 26rpx;
  color: $color-text-secondary;
  letter-spacing: 2rpx;
  margin-bottom: 40rpx;
}

.feature-tags {
  display: flex;
  gap: 20rpx;

  .tag {
    padding: 12rpx 24rpx;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 40rpx;
    box-shadow: $shadow-sm;

    .tag-text {
      font-size: 22rpx;
      color: #555555;
      font-weight: 500;
    }
  }
}

/* ========== 登录卡片 ========== */
.login-card {
  width: 100%;
  background: $color-bg-primary;
  border-radius: $radius-xl;
  padding: 48rpx 40rpx 40rpx;
  box-shadow: $shadow-lg;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  animation: slide-up 0.35s $ease-out 0.1s both;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  margin-bottom: 48rpx;

  .header-line {
    width: 64rpx;
    height: 2rpx;
    background: linear-gradient(90deg, transparent, $color-primary-light);

    &:last-child {
      background: linear-gradient(90deg, $color-primary-light, transparent);
    }
  }

  .card-title {
    font-size: 28rpx;
    font-weight: 600;
    color: $color-text-primary;
    letter-spacing: 2rpx;
  }
}

.login-btn {
  width: 100%;
  height: 108rpx;
  background: linear-gradient(135deg, #FFD700, $color-primary, $color-primary-dark);
  border-radius: 54rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: $shadow-primary, 0 4rpx 16rpx rgba(255, 193, 7, 0.2);

  &::after {
    border: none;
  }

  &:active {
    transform: scale(0.98);
  }
}

.login-btn-hover {
  transform: translateY(-2rpx) scale(1.01);
  box-shadow: 0 12rpx 36rpx rgba(255, 193, 7, 0.4), 0 6rpx 20rpx rgba(255, 193, 7, 0.25);
}

.login-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  letter-spacing: 4rpx;
}

/* ========== 用户协议 ========== */
.agreement {
  text-align: center;
  padding: 40rpx 32rpx 0;
  animation: fade-in 0.4s $ease-out 0.2s both;
}

.agreement-text {
  font-size: 24rpx;
  color: $color-text-tertiary;
  display: block;
  margin-bottom: 8rpx;
}

.agreement-links {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4rpx;
  flex-wrap: wrap;
}

.link {
  font-size: 24rpx;
  color: $color-primary-dark;
  font-weight: 500;

  &:active {
    opacity: 0.6;
  }
}

.link-sep {
  font-size: 24rpx;
  color: $color-text-tertiary;
}

/* ========== 底部装饰 ========== */
.footer-dots {
  display: flex;
  gap: 12rpx;
  justify-content: center;
  margin-top: auto;
  padding-top: 64rpx;

  .dot {
    width: 10rpx;
    height: 10rpx;
    border-radius: 50%;
    background: $color-primary-light;
    opacity: 0.5;
  }
}

/* ========== 动画 ========== */
@keyframes orb-float {
  0%, 100% { transform: translateY(0) scale(1); }
  50% { transform: translateY(-24rpx) scale(1.04); }
}

@keyframes ring-rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes glow-pulse {
  0%, 100% { opacity: 0.6; transform: scale(1); }
  50% { opacity: 1; transform: scale(1.08); }
}

@keyframes slide-down {
  from { opacity: 0; transform: translateY(-40rpx); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes slide-up {
  from { opacity: 0; transform: translateY(40rpx); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fade-in {
  from { opacity: 0; }
  to { opacity: 1; }
}
</style>
