<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <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" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
        <view class="login-code"> 
          <image :src="codeUrl" @click="getCode" class="login-code-img"></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 class="reading-tips">
      <text class="tip-text">登录后即可：</text>
      <view class="benefits">
        <text>✓ 继续阅读精彩章节</text>
        <text>✓ 加入书架保存进度</text>
        <text>✓ 获得每日阅读奖励</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      codeUrl: "",
      captchaEnabled: false, // 默认不开启验证码
      register: false,
      // 安全的全局配置访问方式
      globalConfig: {
        appInfo: {
          logo: "",
          agreements: []
        }
      },
      loginForm: {
        username: "",
        password: "",
        code: "",
        uuid: ""
      }
    }
  },
  created() {
    // 安全地获取全局配置
    this.safeInit();
  },
  onLoad() {
    // 如果全局配置已设置，则使用全局配置
    if (this.$config) {
      this.globalConfig = this.$config;
    }
  },
  methods: {
    // 安全的初始化方法
    safeInit() {
      try {
        // 安全地获取全局配置
        if (typeof getApp === 'function') {
          const app = getApp();
          if (app && app.globalData && app.globalData.config) {
            this.globalConfig = app.globalData.config;
          }
        }
        
        // 尝试获取验证码
        this.getCodeSafe();
      } catch (error) {
        console.error('初始化失败:', error);
      }
    },
    
    // 安全的获取验证码方法
    async getCodeSafe() {
      try {
        await this.getCode();
      } catch (error) {
        console.error('获取验证码失败:', error);
        // 可以设置默认行为，比如不显示验证码
        this.captchaEnabled = false;
      }
    },
    
    // 获取验证码
    async getCode() {
      // 确保$http对象可用
      if (!this.$http || typeof this.$http.get !== 'function') {
        console.warn('$http未定义或不可用');
        return;
      }
      
      try {
        const res = await this.$http.get('/captchaImage');
        if (res.code === 200) {
          this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
          if (this.captchaEnabled) {
            this.codeUrl = 'data:image/png;base64,' + res.data.img;
            this.loginForm.uuid = res.data.uuid;
          }
        } else {
          console.error('验证码获取失败:', res.msg);
        }
      } catch (error) {
        console.error('验证码请求失败:', error);
        throw error;
      }
    },
    
    // 用户注册
    handleUserRegister() {
      this.$router.push('/pages/register');
    },
    
    // 隐私协议
    handlePrivacy() {
      // 简化处理，直接跳转到webview页面
      this.$router.push('/pages/common/webview?title=隐私协议&url=https://example.com/privacy');
    },
    
    // 用户协议
    handleUserAgrement() {
      // 简化处理，直接跳转到webview页面
      this.$router.push('/pages/common/webview?title=用户协议&url=https://example.com/agreement');
    },
    
    // 登录方法
    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 {
        await this.pwdLogin();
      } catch (error) {
        this.$modal.closeLoading();
        this.$modal.msgError(error.message || '登录失败');
        
        // 刷新验证码
        if (this.captchaEnabled) {
          this.getCodeSafe();
        }
      }
    },
    
    // 密码登录
    async pwdLogin() {
      try {
        // 使用安全的API调用方式
        if (this.$store && this.$store.dispatch) {
          await this.$store.dispatch('Login', this.loginForm);
          this.$modal.closeLoading();
          this.loginSuccess();
        } else {
          throw new Error('存储系统不可用');
        }
      } catch (error) {
        console.error('登录失败:', error);
        throw error;
      }
    },
    
    // 登录成功后，处理函数
    loginSuccess() {
      // 设置用户信息
      if (this.$store && this.$store.dispatch) {
        this.$store.dispatch('GetInfo').then(() => {
          this.$router.replace('/pages/index');
        }).catch(error => {
          console.error('获取用户信息失败:', error);
          this.$router.replace('/pages/index');
        });
      } else {
        this.$router.replace('/pages/index');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  /* 保持原有样式不变 */
  page {
    background-color: #ffffff;
  }
  
  .reading-tips {
    margin-top: 40rpx;
    padding: 20rpx;
    background-color: #f9f9f9;
    border-radius: 10rpx;
  }
  
  .tip-text {
    font-size: 32rpx;
    font-weight: bold;
    display: block;
    margin-bottom: 20rpx;
  }
  
  .benefits text {
    display: block;
    font-size: 28rpx;
    margin: 10rpx 0;
    color: #2c3e50;
  }
  
  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 15%;
      
      .title {
        margin-left: 10px;
      }
    }

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

      .input-item {
        margin: 20px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }

      }

      .login-btn {
        margin-top: 40px;
        height: 45px;
      }
      
      .reg {
        margin-top: 15px;
      }
      
      .xieyi {
        color: #333;
        margin-top: 20px;
      }
      
      .login-code {
        height: 38px;
        float: right;
      
        .login-code-img {
          height: 38px;
          position: absolute;
          margin-left: 10px;
          width: 200rpx;
        }
      }
    }
  }

</style>
