<script lang="ts" setup>
import type { ILoginForm } from '@/api/login'
import type { ICaptcha } from '@/api/types/login'
import { computed, onMounted, ref } from 'vue'
import { getCaptcha } from '@/api/login'
import { useAuthStore } from '@/store/auth'

definePage({
  style: {
    navigationBarTitleText: '登录',
  },
})

const authStore = useAuthStore()

// 验证码响应实体类
const captchaInfo = ref<ICaptcha>({
  captchaEnabled: false,
  img: '',
  uuid: '',
})

// 登录表单数据
const loginForm = ref<ILoginForm>({
  username: '',
  password: '',
  code: '',
  uuid: '',
})

// 验证码相关数据
const captchaData = ref({
  code: '',
  uuid: '',
})

// 重定向地址
const redirectUrl = ref('')

// 表单验证规则
const formRules = computed(() => ({
  username: {
    required: true,
    message: '请输入用户名',
    trigger: 'blur',
  },
  password: {
    required: true,
    message: '请输入密码',
    trigger: 'blur',
  },
  code: {
    required: captchaInfo.value.captchaEnabled,
    message: '请输入验证码',
    trigger: 'blur',
  },
}))

// 获取验证码接口
async function loadCaptcha() {
  try {
    const resp = await getCaptcha()
    if (resp.captchaEnabled && resp.img) {
      resp.img = `data:image/png;base64,${resp.img}`
    }
    captchaInfo.value = resp
    loginForm.value.uuid = resp.uuid || ''
  }
  catch (error) {
    console.error('获取验证码失败:', error)
    uni.showToast({
      title: '获取验证码失败',
      icon: 'none',
      duration: 2000
    })
  }
}

// uni-app页面生命周期钩子
onLoad((options) => {
  // 获取重定向地址
  if (options?.redirect) {
    redirectUrl.value = decodeURIComponent(options.redirect)
  }
})

onMounted(async () => {
  await loadCaptcha()
})

// 处理登录
async function handleLogin() {
  try {
    // 构建登录参数
    const requestParam: ILoginForm = {
      username: loginForm.value.username,
      password: loginForm.value.password,
      code: '',
      uuid: '',
    }

    // 如果需要验证码，添加验证码参数
    if (captchaInfo.value.captchaEnabled) {
      requestParam.code = loginForm.value.code
      requestParam.uuid = loginForm.value.uuid
    }

    // 调用登录接口
    await authStore.authLogin(requestParam)
    uni.showToast({
      title: '登录成功',
      icon: 'success',
    })

    // 登录成功后跳转
    setTimeout(() => {
      if (redirectUrl.value) {
        // 如果有重定向地址，跳转到指定页面
        if (redirectUrl.value.startsWith('/pages/')) {
          // 检查是否为tabbar页面
          const tabbarPages = ['/pages/schedule/view/index', '/pages/report/index', '/pages/radar/index', '/pages/archive/index', '/pages/knowledge/index']
          if (tabbarPages.includes(redirectUrl.value)) {
            uni.switchTab({
              url: redirectUrl.value,
            })
          }
          else {
            uni.redirectTo({
              url: redirectUrl.value,
            })
          }
        }
        else {
          uni.redirectTo({
            url: redirectUrl.value,
          })
        }
      }
      else {
        // 没有重定向地址，跳转到首页
        uni.switchTab({
          url: '/pages/schedule/view/index',
        })
      }
    }, 1500)
  }
  catch (error) {
    console.error('登录失败:', error)
    uni.showToast({
      title: '登录失败，请检查用户名密码',
      icon: 'none',
      duration: 2000
    })
    
    // 处理验证码错误，刷新验证码
    if (captchaInfo.value.captchaEnabled) {
      await loadCaptcha()
      loginForm.value.code = ''
    }
  }
}

// 表单提交
function onSubmit() {
  handleLogin()
}

// 刷新验证码
function refreshCaptcha() {
  loadCaptcha()
}

// 表单验证
const formRef = ref()

function validateForm() {
  formRef.value?.validate().then(() => {
    onSubmit()
  }).catch(() => {
    uni.showToast({
      title: '请检查表单输入',
      icon: 'error',
    })
  })
}
</script>

<template>
  <view class="login-container">
    <!-- 登录头部 -->
    <view class="login-header">
      <view class="logo-container">
        <image src="/static/logo.svg" class="logo" mode="aspectFit" />
      </view>
      <text class="login-title">用户登录</text>
    </view>

    <!-- 登录表单 -->
    <view class="login-form">
      <wd-form ref="formRef" :model="loginForm" :rules="formRules">
        <!-- 用户名输入 -->
        <wd-form-item prop="username" label="用户名" required>
          <wd-input v-model="loginForm.username" placeholder="请输入用户名" clearable :show-clear="true" />
        </wd-form-item>

        <!-- 密码输入 -->
        <wd-form-item prop="password" label="密码" required>
          <wd-input v-model="loginForm.password" placeholder="请输入密码" clearable show-password />
        </wd-form-item>

        <!-- 验证码输入 -->
        <wd-form-item v-if="captchaInfo && captchaInfo.captchaEnabled" prop="code" label="验证码" required>
          <view class="captcha-container">
            <wd-input v-model="loginForm.code" placeholder="请输入验证码" clearable :show-clear="true" class="captcha-input" />
            <view class="captcha-image-wrapper" @click="refreshCaptcha">
              <image v-if="captchaInfo && captchaInfo.img" :src="captchaInfo.img" class="captcha-image" mode="aspectFit" />
              <text v-else class="captcha-placeholder">点击获取</text>
            </view>
          </view>
        </wd-form-item>
      </wd-form>

      <!-- 登录按钮 -->
      <view class="login-actions">
        <wd-button type="primary" round block :loading="authStore.loginLoading" @click="validateForm">
          {{ authStore.loginLoading ? '登录中...' : '登录' }}
        </wd-button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 0 32rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-header {
  text-align: center;
  margin-bottom: 80rpx;

  .logo-container {
    margin-bottom: 40rpx;

    .logo {
      width: 120rpx;
      height: 120rpx;
    }
  }

  .login-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: white;
    margin-bottom: 16rpx;
  }

  .login-subtitle {
    display: block;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.login-form {
  background: white;
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);

  .test-section {
    margin-bottom: 32rpx;
    padding: 16rpx;
    background: #f0f8ff;
    border-radius: 8rpx;

    text {
      display: block;
      margin-bottom: 16rpx;
      font-size: 28rpx;
      color: #333;
    }
  }

  :deep(.wd-form-item) {
    margin-bottom: 32rpx;
  }

  :deep(.wd-form-item__label) {
    font-weight: 500;
    color: #333;
  }

  :deep(.wd-input) {
    height: 88rpx;
    border-radius: 12rpx;
    background: #f8f9fa;
  }

  .captcha-container {
    display: flex;
    align-items: center;
    gap: 16rpx;

    .captcha-input {
      flex: 1;
    }

    .captcha-image-wrapper {
      width: 160rpx;
      height: 88rpx;
      border-radius: 12rpx;
      background: #f8f9fa;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #e9ecef;
      cursor: pointer;
      transition: all 0.3s ease;

      &:active {
        transform: scale(0.95);
        background: #e9ecef;
      }

      .captcha-image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }

      .captcha-placeholder {
        font-size: 24rpx;
        color: #999;
      }
    }
  }

  .login-actions {
    margin: 48rpx 0 32rpx;

    :deep(.wd-button) {
      height: 96rpx;
      font-size: 32rpx;
      font-weight: 600;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
  }

  .login-footer {
    text-align: center;

    .footer-text {
      font-size: 28rpx;
      color: #666;
    }

    .register-link {
      font-size: 28rpx;
      color: #667eea;
      font-weight: 500;
      margin-left: 8rpx;
    }
  }
}
</style>
