<template>
  <view class="login-page">
    <view class="login-content">
      <!-- Logo 区域 -->
      <view class="logo-section">
        <view class="logo">
          <view class="logo-icon">
            <view class="logo-leaf"></view>
            <view class="logo-leaf right"></view>
          </view>
        </view>
        <text class="brand-name">哈哈运营平台</text>
      </view>
      
      <!-- 登录表单 -->
      <view class="login-card">
        <view class="form-group">
          <view class="input-wrapper">
            <view class="input-icon user"></view>
            <input 
              class="form-input" 
              type="text" 
              v-model="formData.username" 
              placeholder="请输入用户名"
              placeholder-class="input-placeholder"
            />
          </view>
        </view>
        
        <view class="form-group">
          <view class="input-wrapper">
            <view class="input-icon lock"></view>
            <input 
              class="form-input" 
              :password="!showPassword" 
              v-model="formData.password" 
              placeholder="请输入密码"
              placeholder-class="input-placeholder"
            />
            <view class="input-action" @click="showPassword = !showPassword">
              <view :class="['eye-icon', { active: showPassword }]"></view>
            </view>
          </view>
        </view>
        
        <button class="login-btn" :loading="loading" :disabled="loading" @click="handleLogin">
          <text v-if="!loading">立即登录</text>
          <text v-else>登录中...</text>
        </button>
        
        <!-- 分隔线 -->
        <view class="login-divider">
          <view class="divider-line"></view>
          <text class="divider-text">其他登录方式</text>
          <view class="divider-line"></view>
        </view>
        
        <!-- 微信登录 -->
        <button class="wechat-btn" :loading="wechatLoading" :disabled="wechatLoading" @click="handleWechatLogin">
          <view class="wechat-icon"></view>
          <text>补货员微信一键登录</text>
        </button>

        <!-- 绑定码登录 -->
        <view class="bind-section" v-if="showBindInput">
          <view class="divider-line"></view>
          <text class="bind-hint">该微信未绑定补货员账号，请扫码或输入管理员提供的一次性绑定码：</text>
          <view class="bind-input-wrapper">
            <input
              class="bind-input"
              type="text"
              v-model="bindingCode"
              placeholder="请输入24位绑定码"
              placeholder-class="input-placeholder"
              maxlength="24"
            />
            <view class="scan-bind-btn" @click="handleScanBindCode">
              <text class="scan-icon-text">扫码</text>
            </view>
          </view>
          <button class="bind-btn" :loading="bindLoading" :disabled="bindLoading || !bindingCode" @click="handleBindWechat">
            <text v-if="!bindLoading">绑定微信并登录</text>
            <text v-else>绑定中...</text>
          </button>
        </view>
        <text v-else class="bind-toggle" @click="showBindInput = true">已有绑定码？点击绑定微信</text>
        
        <view class="login-tips">
          <view class="tips-icon"></view>
          <text class="tips-label">测试账号</text>
          <text class="tips-value">admin / admin123</text>
        </view>
      </view>
    </view>
    
    <!-- 底部 -->
    <view class="login-footer">
      <text>© 2025 哈哈零售 All Rights Reserved</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { login } from '@/api/auth';
import { isLoggedIn } from '@/utils/auth';

const formData = reactive({
  username: '',
  password: ''
});

const showPassword = ref(false);
const loading = ref(false);
const wechatLoading = ref(false);
const showBindInput = ref(false);
const bindingCode = ref('');
const bindLoading = ref(false);

onMounted(() => {
  if (isLoggedIn()) {
    uni.switchTab({ url: '/pages/index/index' });
  }
});

const handleLogin = async () => {
  if (!formData.username) {
    uni.showToast({ title: '请输入用户名', icon: 'none' });
    return;
  }
  if (!formData.password) {
    uni.showToast({ title: '请输入密码', icon: 'none' });
    return;
  }
  
  loading.value = true;
  try {
    await login(formData);
    uni.showToast({ title: '登录成功', icon: 'success' });
    setTimeout(() => {
      uni.switchTab({ url: '/pages/index/index' });
    }, 500);
  } catch (error: any) {
    uni.showToast({ title: error.message || '登录失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

const handleWechatLogin = async () => {
  wechatLoading.value = true;
  try {
    // 1. 微信授权获取code
    const loginRes = await new Promise<any>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      });
    });
    
    if (!loginRes.code) {
      uni.showToast({ title: '微信授权失败', icon: 'none' });
      return;
    }
    
    // 2. 调用后端登录接口
    const { loginByWechat } = await import('@/api/replenish');
    await loginByWechat({ code: loginRes.code });
    
    uni.showToast({ title: '登录成功', icon: 'success' });
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/replenish/index' });
    }, 500);
  } catch (error: any) {
    // 如果是未绑定的账号，显示绑定码输入
    if (error.message && error.message.includes('未绑定')) {
      showBindInput.value = true;
      uni.showToast({ title: '该微信未绑定账号，请输入绑定码', icon: 'none' });
    } else {
      uni.showToast({ title: error.message || '登录失败', icon: 'none' });
    }
  } finally {
    wechatLoading.value = false;
  }
};

/**
 * 扫码识别绑定码
 */
const handleScanBindCode = () => {
  uni.scanCode({
    onlyFromCamera: false,
    scanType: ['qrCode'],
    success: (res: any) => {
      const result = (res.result || '').trim();
      // 绑定码为24位大写字母数字组合
      if (/^[A-Z0-9]{24}$/.test(result)) {
        bindingCode.value = result;
        uni.showToast({ title: '已识别绑定码', icon: 'success' });
      } else {
        uni.showToast({ title: '无效的绑定码二维码', icon: 'none' });
      }
    },
    fail: () => {
      // 用户取消扫码
    }
  });
};

/**
 * 补货员绑定微信
 */
const handleBindWechat = async () => {
  if (!bindingCode.value || bindingCode.value.length < 4) {
    uni.showToast({ title: '请输入有效的绑定码', icon: 'none' });
    return;
  }
  
  bindLoading.value = true;
  try {
    // 1. 微信授权获取code
    const loginRes = await new Promise<any>((resolve, reject) => {
      uni.login({
        provider: 'weixin',
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      });
    });
    
    if (!loginRes.code) {
      uni.showToast({ title: '微信授权失败', icon: 'none' });
      return;
    }
    
    // 2. 调用绑定接口
    const { bindWechat } = await import('@/api/replenish');
    await bindWechat({
      bindingCode: bindingCode.value.trim().toUpperCase(),
      code: loginRes.code
    });
    
    uni.showToast({ title: '绑定成功', icon: 'success' });
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/replenish/index' });
    }, 500);
  } catch (error: any) {
    uni.showToast({ title: error.message || '绑定失败', icon: 'none' });
  } finally {
    bindLoading.value = false;
  }
};
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: $bg-color-page;
  display: flex;
  flex-direction: column;
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
}

.login-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 0 40rpx;
}

/* Logo 区域 */
.logo-section {
  text-align: center;
  margin-bottom: 48rpx;
  
  .logo {
    width: 120rpx;
    height: 120rpx;
    background: $primary-color;
    border-radius: 32rpx;
    margin: 0 auto 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    
    .logo-icon {
      position: relative;
      width: 48rpx;
      height: 48rpx;
      
      .logo-leaf {
        position: absolute;
        width: 24rpx;
        height: 40rpx;
        background: $bg-color-card;
        border-radius: 50% 50% 50% 50% / 60% 60% 40% 40%;
        left: 0;
        top: 4rpx;
        transform: rotate(-20deg);
        
        &.right {
          left: auto;
          right: 0;
          transform: rotate(20deg);
        }
      }
    }
  }
  
  .brand-name {
    display: block;
    font-size: 44rpx;
    font-weight: 700;
    color: $text-color-primary;
    margin-bottom: 12rpx;
    letter-spacing: 2rpx;
  }
  
  .brand-subtitle {
    display: block;
    font-size: 28rpx;
    color: $text-color-tertiary;
  }
}

/* 登录卡片 */
.login-card {
  background: $bg-color-card;
  border: 1rpx solid $border-color;
  border-radius: 24rpx;
  padding: 40rpx 32rpx;
}

.form-group {
  margin-bottom: 28rpx;
  
  .form-label {
    display: block;
    font-size: 26rpx;
    color: $text-color-secondary;
    margin-bottom: 12rpx;
    font-weight: 500;
  }
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: $bg-color-page;
  border: 2rpx solid $border-color;
  border-radius: 16rpx;
  padding: 0 20rpx;
  transition: all 0.2s;
  
  &:focus-within {
    border-color: $primary-color;
    background: $bg-color-card;
    box-shadow: 0 0 0 4rpx rgba(255, 193, 7, 0.1);
  }
  
  .input-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 12rpx;
    flex-shrink: 0;
    
    &.user {
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 6rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 16rpx;
        height: 16rpx;
        background: $text-color-muted;
        border-radius: 50%;
      }
      
      &::after {
        content: '';
        position: absolute;
        bottom: 4rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 26rpx;
        height: 14rpx;
        background: $text-color-muted;
        border-radius: 14rpx 14rpx 0 0;
      }
    }
    
    &.lock {
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 4rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 18rpx;
        height: 14rpx;
        border: 3rpx solid $text-color-muted;
        border-bottom: none;
        border-radius: 16rpx 16rpx 0 0;
      }
      
      &::after {
        content: '';
        position: absolute;
        bottom: 4rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 22rpx;
        height: 18rpx;
        background: $text-color-muted;
        border-radius: 4rpx;
      }
    }
  }
  
  .form-input {
    flex: 1;
    height: 100rpx;
    font-size: 30rpx;
    color: $text-color-primary;
  }
  
  .input-action {
    padding: 16rpx;
    margin: -16rpx;
    margin-left: 0;
    
    .eye-icon {
      width: 40rpx;
      height: 28rpx;
      border: 3rpx solid $text-color-muted;
      border-radius: 50%;
      position: relative;
      
      &::before {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 12rpx;
        height: 12rpx;
        background: $text-color-muted;
        border-radius: 50%;
      }
      
      &.active::before {
        background: $primary-color;
      }
      
      &.active {
        border-color: $primary-color;
      }
    }
  }
}

.input-placeholder {
  color: $text-color-placeholder;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  padding: 0;
  background: $primary-color;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
  border-radius: 16rpx;
  margin-top: 20rpx;
  border: none;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &::after {
    border: none;
  }
  
  &:active {
    background: $primary-color-dark;
    transform: scale(0.98);
  }
  
  &[disabled] {
    opacity: 0.6;
  }
}

.login-tips {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 28rpx;
  padding: 20rpx;
  background: $success-color-bg;
  border-radius: 12rpx;
  
  .tips-icon {
    width: 32rpx;
    height: 32rpx;
    background: $primary-color;
    border-radius: 50%;
    margin-right: 12rpx;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 12rpx;
      height: 4rpx;
      background: #fff;
      border-radius: 2rpx;
    }
    
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 4rpx;
      height: 12rpx;
      background: #fff;
      border-radius: 2rpx;
    }
  }
  
  .tips-label {
    font-size: 24rpx;
    color: $text-color-tertiary;
    margin-right: 12rpx;
  }
  
  .tips-value {
    font-size: 24rpx;
    color: $primary-color;
    font-weight: 600;
  }
}

/* 分隔线 */
.login-divider {
  display: flex;
  align-items: center;
  margin-top: 32rpx;
  margin-bottom: 28rpx;
  
  .divider-line {
    flex: 1;
    height: 1rpx;
    background: $border-color;
  }
  
  .divider-text {
    padding: 0 24rpx;
    font-size: 24rpx;
    color: $text-color-muted;
  }
}

/* 微信登录按钮 */
.wechat-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  padding: 0;
  background: $bg-color-card;
  color: $text-color-primary;
  font-size: 30rpx;
  font-weight: 500;
  border: 2rpx solid $border-color;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  
  &::after {
    border: none;
  }
  
  &:active {
    background: $bg-color-page;
    border-color: $primary-color;
  }
  
  &[disabled] {
    opacity: 0.6;
  }
  
  .wechat-icon {
    width: 36rpx;
    height: 36rpx;
    background: #07c160;
    border-radius: 8rpx;
    margin-right: 12rpx;
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      top: 8rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 14rpx;
      height: 10rpx;
      border: 3rpx solid #fff;
      border-top: none;
      border-right: none;
      transform: translateX(-50%) rotate(-45deg);
    }
    
    &::after {
      content: '';
      position: absolute;
      bottom: 8rpx;
      left: 50%;
      transform: translateX(-50%);
      width: 16rpx;
      height: 10rpx;
      border: 3rpx solid #fff;
      border-bottom: none;
      border-right: none;
      transform: translateX(-50%) rotate(45deg);
    }
  }
}

/* 绑定码切换链接 */
.bind-toggle {
  display: block;
  text-align: center;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: $primary-color;
}

/* 绑定码区域 */
.bind-section {
  margin-top: 20rpx;
  
  .divider-line {
    height: 1rpx;
    background: $border-color;
    margin-bottom: 20rpx;
  }
  
  .bind-hint {
    display: block;
    font-size: 24rpx;
    color: $text-color-tertiary;
    margin-bottom: 16rpx;
    line-height: 1.5;
  }
  
  .bind-input-wrapper {
    display: flex;
    align-items: center;
    background: $bg-color-page;
    border: 2rpx solid $border-color;
    border-radius: 16rpx;
    padding: 0 20rpx;
    margin-bottom: 16rpx;
    transition: all 0.2s;
    
    &:focus-within {
      border-color: $primary-color;
      background: $bg-color-card;
      box-shadow: 0 0 0 4rpx rgba(255, 193, 7, 0.1);
    }
    
    .bind-input {
      flex: 1;
      height: 100rpx;
      font-size: 30rpx;
      color: $text-color-primary;
      letter-spacing: 4rpx;
    }

    .scan-bind-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 72rpx;
      padding: 0 24rpx;
      margin-right: 8rpx;
      background: $primary-color;
      border-radius: 12rpx;

      .scan-icon-text {
        font-size: 24rpx;
        color: #fff;
        font-weight: 600;
      }

      &:active {
        opacity: 0.85;
      }
    }
  }

  .bind-btn {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    padding: 0;
    background: $primary-color;
    color: #fff;
    font-size: 30rpx;
    font-weight: 600;
    border-radius: 16rpx;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    
    &::after {
      border: none;
    }
    
    &:active {
      background: $primary-color-dark;
    }
    
    &[disabled] {
      opacity: 0.6;
    }
  }
}

/* 底部 */
.login-footer {
  padding: 40rpx 0;
  text-align: center;
  
  text {
    font-size: 24rpx;
    color: $text-color-placeholder;
  }
}
</style>
