<template>
  <view class="login-page">
    <view class="login-content">
      <!-- Logo 区域 -->
      <view class="logo-section">
        <image class="logo-img" src="/static/logo.png" mode="aspectFit" />
        <text class="brand-name">富玉餐饮运营</text>
      </view>
      
      <!-- 管理员登录 -->
      <view class="login-card">
        <text class="card-label">运营登录</text>
        <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>
        <view class="remember-row" @click="rememberMe = !rememberMe">
          <view :class="['remember-checkbox', { checked: rememberMe }]">
            <text v-if="rememberMe" class="check-mark">✓</text>
          </view>
          <text class="remember-label">记住我</text>
        </view>
        <button class="login-btn" :loading="loading" :disabled="loading" @click="handleLogin">
          <text v-if="!loading">立即登录</text>
          <text v-else>登录中...</text>
        </button>
      </view>

      <!-- 补货员登录 -->
      <view class="replenisher-card">
        <text class="card-label">补货员登录</text>
        <button class="wechat-btn" hover-class="none" :loading="wechatLoading" :disabled="wechatLoading" @click="handleWechatLogin">
          <image class="wechat-icon-img" src="/static/icon-wechat.svg" />
          <text>微信一键登录</text>
        </button>
        <view class="bind-toggle" v-if="!showBindInput" @click="showBindInput = true">
          <text>已有绑定码？扫码或输入绑定</text>
        </view>
        <view class="bind-section" v-if="showBindInput">
          <view class="bind-input-wrapper">
            <input class="bind-input" type="text" v-model="bindingCode" placeholder="请输入24位绑定码" placeholder-class="input-placeholder" maxlength="32" />
            <view class="scan-bind-btn" @click="handleScanBindCode"><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>
          <text class="bind-cancel" @click="showBindInput = false">取消绑定</text>
        </view>
      </view>

    </view>
    
  </view>
</template>

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

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

const navigateHome = () => {
  const home = getHomePath();
  if (home === '/pages/replenish/home') {
    uni.reLaunch({ url: home });
  } else {
    uni.switchTab({ url: home });
  }
};

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

const REMEMBERED_KEY = 'remembered_login';

onMounted(() => {
  if (isLoggedIn()) {
    navigateHome();
    return;
  }
  // 读取记住的账号和密码
  const saved = uni.getStorageSync(REMEMBERED_KEY);
  if (saved) {
    try {
      const data = JSON.parse(saved);
      if (data.username) formData.username = data.username;
      if (data.password) formData.password = data.password;
      rememberMe.value = true;
    } catch { /* ignore */ }
  }
});

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);
    // 记住/清除账号和密码
    if (rememberMe.value) {
      uni.setStorageSync(REMEMBERED_KEY, JSON.stringify({
        username: formData.username,
        password: formData.password,
      }));
    } else {
      uni.removeStorageSync(REMEMBERED_KEY);
    }
    uni.showToast({ title: '登录成功', icon: 'success' });
    setTimeout(() => {
      navigateHome();
    }, 500);
  } catch (error: any) {
    uni.showToast({ title: error.message || '登录失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

const handleWechatLogin = async () => {
  wechatLoading.value = true;
  try {
    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; }

    await loginByWechat({ code: loginRes.code });
    uni.showToast({ title: '登录成功', icon: 'success' });
    setTimeout(() => uni.reLaunch({ url: '/pages/replenish/home' }), 500);
  } catch (error: any) {
    if (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 () => {
  const code = (bindingCode.value || '').replace(/\s/g, '').toUpperCase();
  if (!/^[A-Z0-9]{24}$/.test(code)) {
    uni.showToast({ title: '绑定码格式不正确，应为24位字母数字', icon: 'none' });
    return;
  }

  bindLoading.value = true;
  try {
    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;
    }

    await bindWechat({
      bindingCode: code,
      code: loginRes.code
    });
    
    uni.showToast({ title: '绑定成功', icon: 'success' });
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/replenish/home' });
    }, 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-img {
    width: 160rpx;
    height: 160rpx;
    margin: 0 auto 28rpx;
    display: block;
  }
  
  .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;
  }
}

/* 卡片公共 */
.card-label { display: block; font-size: $font-size-sm; color: $text-color-muted; margin-bottom: 16rpx; text-align: center; letter-spacing: 0.05em; }

/* 登录卡片 */
.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;
}

/* 记住账号 */
.remember-row {
  display: flex;
  align-items: center;
  margin-top: 4rpx;
  padding: 8rpx 0;

  .remember-checkbox {
    width: 36rpx;
    height: 36rpx;
    border: 2rpx solid $border-color;
    border-radius: 6rpx;
    margin-right: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;

    &.checked {
      background: $primary-color;
      border-color: $primary-color;

      .check-mark {
        color: #fff;
        font-size: 22rpx;
        font-weight: 700;
      }
    }
  }

  .remember-label {
    font-size: 26rpx;
    color: $text-color-secondary;
  }
}

/* 登录按钮 */
.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;
  }
}

/* 补货员登录卡片 */
.replenisher-card {
  margin-top: 24rpx; padding: 32rpx 28rpx; background: $bg-color-card; border: 1rpx solid $border-color; border-radius: 24rpx;
}

/* 分隔线 */
.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: 88rpx; padding: 0; background: #2DC100; border-radius: 12rpx;
  display: flex; align-items: center; justify-content: center; gap: 12rpx;
  &::after { border: none; }
  &:active { opacity: 0.85; }
  &[disabled] { opacity: 0.6; }
  .wechat-icon-img { width: 44rpx; height: 44rpx; flex-shrink: 0; }
  text { font-size: $font-size-base; font-weight: 500; color: #fff; }
}

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

.bind-cancel {
  display: block;
  text-align: center;
  margin-top: 16rpx;
  font-size: 24rpx;
  color: $text-color-muted;
}

/* 绑定码区域 */
.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>
