<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
      </image>
      <text class="title">哎呀电子小说</text>
    </view>

    <view class="login-form-content">
      <!-- 用户名密码登录 -->
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
      </view>
      
      <!-- 修复验证码显示 -->
      <view class="input-item flex align-center" v-if="captchaEnabled">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="text" class="input" placeholder="请输入验证码" maxlength="4" />
        <view class="login-code"> 
          <image :src="codeUrl" @click="getCode" class="login-code-img" mode="widthFix"></image>
        </view>
      </view>

      <view class="action-btn">
        <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">账号登录</button>
      </view>

      <view class="reg text-center" v-if="register">
        <text class="text-grey1">没有账号？</text>
        <text @click="handleUserRegister" class="text-blue">立即注册</text>
      </view>
      <view class="xieyi text-center">
        <text class="text-grey1">登录即代表同意</text>
        <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
        <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getCodeImg, login } from '@/api/login'
import { setToken } from '@/utils/auth'

export default {
  data() {
    return {
      codeUrl: "",
      captchaEnabled: true,
      register: true,
      globalConfig: {
        appInfo: {
          logo: '/static/logo.png',
          agreements: []
        }
      },
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: ''
      }
    }
  },
  onLoad(options) {
    console.log('登录页面参数:', options)
    this.redirectUrl = options.redirect || ''
    this.safeInitConfig()
    this.getCode()
  },
  methods: {
    // 安全初始化配置
    safeInitConfig() {
      try {
        const app = getApp()
        if (app && app.globalData && app.globalData.config) {
          this.globalConfig = app.globalData.config
        }
      } catch (error) {
        console.warn('获取全局配置失败:', error)
      }
    },

    // 获取图形验证码
    async getCode() {
      try {
        const res = await getCodeImg()
        console.log('验证码响应:', res)
        
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
        if (this.captchaEnabled) {
          this.codeUrl = 'data:image/gif;base64,' + res.img
          this.loginForm.uuid = res.uuid
          console.log('验证码URL设置成功')
        }
      } catch (error) {
        console.error('获取验证码失败:', error)
        this.captchaEnabled = false
        this.$modal.msgError("验证码加载失败")
      }
    },

    // 登录方法 - 简化版
    async handleLogin() {
      if (!this.loginForm.username) {
        this.$modal.msgError("请输入您的账号")
        return
      }
      if (!this.loginForm.password) {
        this.$modal.msgError("请输入您的密码")
        return
      }
      if (this.captchaEnabled && !this.loginForm.code) {
        this.$modal.msgError("请输入验证码")
        return
      }

      this.$modal.loading("登录中，请耐心等待...")
      
      try {
        // 直接调用登录API
        const res = await login(
          this.loginForm.username,
          this.loginForm.password,
          this.loginForm.code,
          this.loginForm.uuid
        )
        
        console.log('登录响应:', res)
        
        if (res.code === 200 && res.token) {
          // 存储token
          setToken(res.token)
          
          this.$modal.msgSuccess("登录成功")
          
          // 触发全局登录状态更新
          uni.$emit('loginStatusUpdate', { isLoggedIn: true })
          
          // 跳转逻辑
          setTimeout(() => {
            this.loginSuccess()
          }, 1000)
          
        } else {
          this.$modal.msgError(res.msg || '登录失败')
          if (this.captchaEnabled) {
            this.getCode()
          }
        }
        
      } catch (error) {
        console.error('登录失败:', error)
        this.$modal.msgError(error.msg || '登录失败，请重试')
        if (this.captchaEnabled) {
          this.getCode()
        }
      } finally {
        this.$modal.closeLoading()
      }
    },

    // 登录成功处理
    loginSuccess() {
      console.log('登录成功，准备跳转')
      
      // 如果有重定向URL，跳转到指定页面
      if (this.redirectUrl) {
        console.log('跳转到重定向页面:', this.redirectUrl)
        uni.redirectTo({
          url: this.redirectUrl
        })
      } else {
        // 默认跳转到首页
        console.log('跳转到首页')
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
    },

    // 其他方法保持不变
    handleUserRegister() {
      uni.navigateTo({
        url: '/pages/register/index'
      })
    },
    
    handlePrivacy() {
      const site = this.globalConfig.appInfo.agreements[0] || { title: '隐私协议', url: '' }
      uni.navigateTo({
        url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      })
    },
    
    handleUserAgrement() {
      const site = this.globalConfig.appInfo.agreements[1] || { title: '用户协议', url: '' }
      uni.navigateTo({
        url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
      })
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

.normal-login-container {
  width: 100%;
  min-height: 100vh;
  padding: 40rpx;

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 15%;
    flex-direction: column;

    image {
      border-radius: 4px;
    }

    .title {
      margin: 10px 0;
      font-size: 24px;
      color: #e94f87;
    }
  }

  .login-form-content {
    text-align: center;
    margin: 20px auto;
    margin-top: 10%;
    width: 100%;

    .input-item {
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 20px;
      display: flex;
      align-items: center;
      padding: 0 15px;

      .icon {
        font-size: 20px;
        color: #999;
        margin-right: 10px;
      }

      .input {
        flex: 1;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        background: transparent;
      }
    }

    .login-btn {
      margin-top: 40px;
      height: 45px;
      background: #e94f87 !important;
      color: #fff;
      border-radius: 25px;
      font-size: 16px;
    }
    
    .reg {
      margin-top: 15px;
      font-size: 14px;
    }
    
    .xieyi {
      color: #333;
      margin-top: 20px;
      font-size: 12px;
    }
    
    .login-code {
      margin-left: 10px;
      
      .login-code-img {
        height: 38px;
        width: 100px;
        border-radius: 4px;
      }
    }
  }
}
</style>