<template>
  <view class="container">
    <!-- 顶部品牌区 -->
    <view class="brand-section">
      <view class="brand-icon">
        <view class="brand-icon-inner">
          <text class="brand-icon-text">HH</text>
        </view>
      </view>
      <text class="brand-title">哈哈零售</text>
      <text class="brand-subtitle">设备上货员·微信绑定</text>
    </view>

    <!-- 绑定卡片 -->
    <view class="bind-card" v-if="!bound">
      <!-- 绑定码卡片 -->
      <view class="code-card">
        <view class="code-header">
          <text class="code-label">绑定码</text>
          <text class="code-expire">24小时内有效</text>
        </view>
        <text class="code-value">{{ displayCode }}</text>
      </view>

      <!-- 绑定流程步骤 -->
      <view class="steps">
        <view class="step-item" :class="{ active: step === 1, done: step > 1 }">
          <view class="step-circle">
            <text class="step-number" v-if="step === 0">1</text>
            <text class="step-check" v-else-if="step > 0">✓</text>
          </view>
          <view class="step-content">
            <text class="step-title">获取绑定码</text>
            <text class="step-desc">由管理员在后台生成</text>
          </view>
        </view>
        <view class="step-line" :class="{ active: step >= 1 }"></view>
        <view class="step-item" :class="{ active: step === 2, done: step > 2 }">
          <view class="step-circle">
            <text class="step-number" v-if="step <= 1">2</text>
            <text class="step-check" v-else>✓</text>
          </view>
          <view class="step-content">
            <text class="step-title">微信授权绑定</text>
            <text class="step-desc">授权微信账号完成绑定</text>
          </view>
        </view>
        <view class="step-line" :class="{ active: step >= 2 }"></view>
        <view class="step-item" :class="{ active: step === 3 }">
          <view class="step-circle">
            <text class="step-number">3</text>
          </view>
          <view class="step-content">
            <text class="step-title">绑定成功</text>
            <text class="step-desc">进入上货员工作台</text>
          </view>
        </view>
      </view>

      <!-- 绑定按钮 -->
      <button
        class="bind-btn"
        :disabled="bindLoading || !bindingCode"
        :loading="bindLoading"
        hover-class="bind-btn-hover"
        @tap="handleBind"
      >
        <text v-if="!bindLoading && hasValidCode">绑定微信</text>
        <text v-else-if="!hasValidCode">绑定码无效</text>
        <text v-else>绑定中...</text>
      </button>

      <text class="back-link" @tap="goBack">返回首页</text>
    </view>

    <!-- 成功状态 -->
    <view class="success-section" v-else>
      <view class="success-icon">
        <text class="success-check">✓</text>
      </view>
      <text class="success-title">绑定成功</text>
      <text class="success-desc">即将进入上货员工作台...</text>
      <view class="success-dots">
        <view class="dot" v-for="i in 3" :key="i"></view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { bindWechat, loginByWechat } from '@/api/replenish';
import { logger } from '@/utils/logger';

const bindingCode = ref('');
const bindLoading = ref(false);
const bound = ref(false);
const step = ref(0);

const hasValidCode = computed(() => {
  return bindingCode.value && bindingCode.value.length >= 4;
});

const displayCode = computed(() => {
  const code = bindingCode.value;
  if (!code) return '---';
  return code.replace(/(.{4})/g, '$1 ').trim();
});

onLoad((options: any) => {
  logger.log('[补货员绑定] onLoad options:', options);

  // 从 scene 场景值或 query 参数获取绑定码
  if (options.scene) {
    const scene = decodeURIComponent(options.scene);
    if (/^[A-Z0-9]{24}$/.test(scene)) {
      bindingCode.value = scene;
      step.value = 1;
      logger.log('[补货员绑定] 从场景值获取绑定码:', scene);
      return;
    }
  }

  if (options.code) {
    bindingCode.value = options.code;
    step.value = 1;
    logger.log('[补货员绑定] 从参数获取绑定码:', options.code);
    return;
  }

  if (options.bindingCode) {
    bindingCode.value = options.bindingCode;
    step.value = 1;
    logger.log('[补货员绑定] 从参数获取绑定码:', options.bindingCode);
    return;
  }

  // 无绑定码参数时提示
  uni.showToast({ title: '缺少绑定码参数', icon: 'none' });
});

const goBack = () => {
  uni.reLaunch({ url: '/pages/index/index' });
};

const handleBind = async () => {
  if (!hasValidCode.value) {
    uni.showToast({ title: '绑定码无效', icon: 'none' });
    return;
  }

  bindLoading.value = true;
  step.value = 2;

  try {
    // 1. 微信授权获取code
    logger.log('[补货员绑定] 开始微信授权...');
    const loginRes = await new Promise<any>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => {
          logger.log('[补货员绑定] 微信授权成功:', res);
          resolve(res);
        },
        fail: (err) => {
          logger.error('[补货员绑定] 微信授权失败:', err);
          reject(err);
        }
      });
    });

    if (!loginRes.code) {
      uni.showToast({ title: '微信授权失败', icon: 'none' });
      step.value = 1;
      return;
    }

    // 2. 调用绑定接口
    logger.log('[补货员绑定] 开始调用绑定接口...');
    const response = await bindWechat({
      bindingCode: bindingCode.value.trim().toUpperCase(),
      code: loginRes.code
    });

    // 3. 保存登录信息
    if (response.token) {
      uni.setStorageSync('accessToken', response.token);
      uni.setStorageSync('haha-user-info', response.userInfo);
    }

    // 4. 显示成功状态
    bound.value = true;
    step.value = 3;

    setTimeout(() => {
      // 跳转到首页，补货员登录后在首页可能会有对应的入口
      uni.reLaunch({ url: '/pages/index/index' });
    }, 2000);
  } catch (error: any) {
    logger.error('[补货员绑定] 绑定失败:', error);
    step.value = 1;
    // 错误已在 request.ts 中统一 toast
  } finally {
    bindLoading.value = false;
  }
};
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: $color-bg-secondary;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: calc(80rpx + env(safe-area-inset-bottom));
}

/* ===== 品牌区域 ===== */
.brand-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 0 48rpx;
  animation: slideDown 0.3s $ease-out;

  .brand-icon {
    width: 120rpx;
    height: 120rpx;
    background: linear-gradient(135deg, $color-primary 0%, $color-primary-dark 100%);
    border-radius: $radius-xl;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 24rpx;
    box-shadow: $shadow-primary;

    .brand-icon-inner {
      .brand-icon-text {
        font-size: 36rpx;
        font-weight: 700;
        color: #fff;
        letter-spacing: 4rpx;
      }
    }
  }

  .brand-title {
    font-size: 36rpx;
    font-weight: 700;
    color: $color-text-primary;
    margin-bottom: 8rpx;
  }

  .brand-subtitle {
    font-size: 26rpx;
    color: $color-text-secondary;
  }
}

/* ===== 绑定卡片 ===== */
.bind-card {
  width: 100%;
  max-width: 600rpx;
  padding: 0 32rpx;
  animation: slideUp 0.3s $ease-out 0.1s both;
}

/* 绑定码展示 */
.code-card {
  background: $color-bg-primary;
  border: 2rpx dashed $color-primary;
  border-radius: $radius-lg;
  padding: 32rpx;
  text-align: center;
  margin-bottom: 40rpx;
  box-shadow: $shadow-sm;

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

    .code-label {
      font-size: 24rpx;
      color: $color-text-secondary;
    }

    .code-expire {
      font-size: 22rpx;
      color: $color-text-tertiary;
      padding: 4rpx 12rpx;
      background: $color-primary-bg;
      border-radius: $radius-sm;
    }
  }

  .code-value {
    display: block;
    font-size: 38rpx;
    font-weight: 700;
    color: $color-text-primary;
    letter-spacing: 8rpx;
    font-family: 'Courier New', Courier, monospace;
  }
}

/* ===== 步骤流程 ===== */
.steps {
  padding: 0 16rpx;
  margin-bottom: 48rpx;

  .step-item {
    display: flex;
    align-items: flex-start;
    padding: 16rpx 0;
    opacity: 0.4;
    transition: opacity $duration-normal $ease-out;

    &.active {
      opacity: 1;

      .step-circle {
        background: $color-primary;
        border-color: $color-primary;
      }

      .step-title {
        color: $color-text-primary;
        font-weight: 600;
      }
    }

    &.done {
      opacity: 0.7;

      .step-circle {
        background: $color-success;
        border-color: $color-success;
      }

      .step-title {
        color: $color-text-secondary;
      }
    }

    .step-circle {
      width: 48rpx;
      height: 48rpx;
      border-radius: $radius-circle;
      border: 2rpx solid $color-border;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      margin-right: 20rpx;
      transition: all $duration-normal $ease-out;

      .step-number {
        font-size: 24rpx;
        font-weight: 600;
        color: $color-text-tertiary;
      }

      .step-check {
        font-size: 24rpx;
        color: #fff;
        font-weight: 700;
      }
    }

    .step-content {
      flex: 1;
      padding-top: 6rpx;

      .step-title {
        font-size: 28rpx;
        color: $color-text-tertiary;
        margin-bottom: 4rpx;
        transition: color $duration-normal $ease-out;
      }

      .step-desc {
        font-size: 22rpx;
        color: $color-text-tertiary;
      }
    }
  }

  .step-line {
    width: 2rpx;
    height: 40rpx;
    background: $color-border;
    margin-left: 23rpx;
    transition: background $duration-normal $ease-out;

    &.active {
      background: $color-primary;
    }
  }
}

/* ===== 绑定按钮 ===== */
.bind-btn {
  width: 100%;
  height: 100rpx;
  background: linear-gradient(135deg, $color-primary 0%, $color-primary-dark 100%);
  border-radius: 50rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: $shadow-primary;
  transition: all $duration-fast $ease-out;

  &::after {
    border: none;
  }

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

  &.bind-btn-hover {
    opacity: 0.9;
    transform: scale(0.98);
  }

  &[disabled] {
    opacity: 0.5;
    box-shadow: none;
  }
}

.back-link {
  display: block;
  text-align: center;
  margin-top: 32rpx;
  font-size: 26rpx;
  color: $color-text-tertiary;
  padding: 16rpx;

  &:active {
    opacity: 0.6;
  }
}

/* ===== 成功状态 ===== */
.success-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 70vh;
  animation: fadeIn 0.4s $ease-out;

  .success-icon {
    width: 160rpx;
    height: 160rpx;
    background: $color-primary-bg;
    border-radius: $radius-circle;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 32rpx;
    animation: pop-in 0.3s $ease-out;

    .success-check {
      font-size: 72rpx;
      color: $color-primary-dark;
      font-weight: 700;
    }
  }

  .success-title {
    font-size: 40rpx;
    font-weight: 700;
    color: $color-text-primary;
    margin-bottom: 12rpx;
    animation: slideUp 0.4s $ease-out 0.3s both;
  }

  .success-desc {
    font-size: 28rpx;
    color: $color-text-secondary;
    animation: slideUp 0.4s $ease-out 0.4s both;
  }

  .success-dots {
    display: flex;
    gap: 12rpx;
    margin-top: 40rpx;

    .dot {
      width: 12rpx;
      height: 12rpx;
      border-radius: $radius-circle;
      background: $color-primary;
      animation: loadingDot 1.2s ease-in-out infinite;

      &:nth-child(1) { animation-delay: 0s; }
      &:nth-child(2) { animation-delay: 0.2s; }
      &:nth-child(3) { animation-delay: 0.4s; }
    }
  }
}

/* ===== 动画 ===== */
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-40rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

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

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes pop-in {
  0% {
    transform: scale(0);
    opacity: 0;
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes loadingDot {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.4;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>
