<template>
  <view class="normal-login-container">
    <view class="background-decoration"></view>
    
    <view class="logo-content">
      <view class="logo-wrapper">
        <image class="logo-image" :src="globalConfig.appInfo.logo" mode="aspectFit"></image>
      </view>
      <text class="title">XXXXXXX平台</text>
      <text class="subtitle">专业的XXXX工具</text>
    </view>
    
    <view class="login-form-content">
      <view class="form-card">
        <view class="input-item">
          <view class="input-icon">
            <uni-icons type="person" size="20" color="#667eea"></uni-icons>
          </view>
          <input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
        </view>
        
        <view class="input-item">
          <view class="input-icon">
            <uni-icons type="locked" size="20" color="#667eea"></uni-icons>
          </view>
          <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
        </view>
        
        <view class="remember-section">
          <up-checkbox
            :customStyle="{marginBottom: '8px'}"
            label="记住密码"
            name="agree"
            usedAlone
            @change="rememberMeChange()"
            v-model:checked="rememberMe"
          >
          </up-checkbox>
        </view>
        
        <view class="action-btn">
          <button @click="handleLogin" class="login-btn">
            <text class="btn-text">登录</text>
          </button>
        </view>
      </view>
    </view>

    <view class="footer-links">
      <text @click="handleRegister" class="link-item">立即注册</text>
      <text class="separator">·</text>
      <text @click="handleWebsite" class="link-item">官方网站</text>
      <text class="separator">·</text>
      <text @click="handleUserAgrement" class="link-item">服务协议</text>
    </view>
  </view>
</template>

<script setup>
import modal from '@/plugins/modal'
import { getCodeImg } from '@/api/login'
import { ref , onMounted } from "vue";
import config from '@/config.js'
import useUserStore from '@/store/modules/user'
import { getWxCode } from '@/utils/geek';
import { wxLogin } from '@/api/oauth';
import { setToken } from '@/utils/auth';
import { encrypt, decrypt } from '@/utils/jsencrypt'
const userStore = useUserStore()
const codeUrl = ref("");
const captchaEnabled = ref(true); // 是否开启验证码
const useWxLogin = ref(false); // 是否使用微信登录
const globalConfig = ref(config);
const rememberMe = ref(false);
const loginForm = ref({
  tenantId: "000000",
  username: "",
  password: "",
  code: "",
  uuid: '',
  rememberMe: false
});

if (useWxLogin.value) {
  getWxCode().then(res => {
    console.log(res);
    wxLogin('miniapp',res).then(res => {
      if(res.token != null){
        setToken(res.token);
        loginSuccess()
      }
    });
  })
}
// 页面加载时检查是否记住了密码
onMounted(() => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  if (tenantId) {
    loginForm.value.tenantId = tenantId;
  }
  if (username && password) {
    loginForm.value.username = username;
    loginForm.value.password = decrypt(password);
    rememberMe.value = true;
  }
});

// 获取图形验证码
function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      loginForm.value.uuid = res.uuid
    }
  })
};
function handleRegister() {
  uni.navigateTo({
    url: `/pages/register`
  });
};

async function handleLogin() {
  if (loginForm.value.username === "") {
    modal.msgError("请输入您的账号")
  } else if (loginForm.value.password === "") {
    modal.msgError("请输入您的密码")
  } else {
    modal.loading("登录中，请等待...")
    pwdLogin()
  }
};
// 密码登录
async function pwdLogin() {
  userStore.login(loginForm.value).then(() => {
    modal.closeLoading()
    loginSuccess()
  }).catch((error) => {
    modal.closeLoading()
    // 显示错误信息
    if (error && typeof error === 'string') {
      modal.msgError(error)
    }
    // 登录失败后重新获取验证码
    if (captchaEnabled.value) {
      getCode()
    }
  })
};
function loginSuccess(result) {
  // 保存记住密码信息
  if (rememberMe.value) {
    localStorage.setItem('tenantId', loginForm.value.tenantId);
    localStorage.setItem('username', loginForm.value.username);
    localStorage.setItem('password', encrypt(loginForm.value.password));
  } else {
    rememberMe.value=false
    localStorage.removeItem('tenantId');
    localStorage.removeItem('username');
    localStorage.removeItem('password');
  }
  
  // 等待一下确保token保存成功
  setTimeout(() => {
    // 设置用户信息
    userStore.getInfo().then(res => {
      uni.switchTab({
        url: '/pages/health/homepage/index'
      });
    }).catch(err => {
      modal.msgError('获取用户信息失败，请重新登录');
    });
  }, 100);
}

function rememberMeChange(){
  rememberMe.value = !rememberMe.value;	

}
// 官方网址
function handleWebsite() {
  let site = globalConfig.value.appInfo.site_url;
  uni.navigateTo({
    url: `/pages/common/webview/index?title=智聪网络科技官网&url=${site}`
  });
};
// 用户协议
function handleUserAgrement() {
  let site = globalConfig.value.appInfo.agreements[1]
  uni.navigateTo({
    url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
  });
};
getCode();
</script>

<style lang="scss" scoped>
page {
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100%;
  height: auto;
}

.normal-login-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  
  .background-decoration {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(circle at top right, rgba(255, 255, 255, 0.1) 0%, transparent 60%);
    pointer-events: none;
  }

  .logo-content {
    width: 100%;
    text-align: center;
    padding-top: 120rpx;
    position: relative;
    z-index: 1;
    
    .logo-wrapper {
      display: inline-block;
      margin-bottom: 32rpx;
      
      .logo-image {
        width: 140rpx;
        height: 140rpx;
        border-radius: 28rpx;
        box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.2);
        background: #ffffff;
        padding: 20rpx;
      }
    }

    .title {
      display: block;
      font-size: 48rpx;
      font-weight: 700;
      color: #ffffff;
      margin-bottom: 12rpx;
    }
    
    .subtitle {
      display: block;
      font-size: 26rpx;
      color: rgba(255, 255, 255, 0.8);
    }
  }

  .login-form-content {
    flex: 1;
    margin-top: 80rpx;
    padding: 0 48rpx;
    position: relative;
    z-index: 1;
    
    .form-card {
      background: #ffffff;
      border-radius: 32rpx;
      padding: 48rpx 40rpx;
      box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.15);
    }

    .input-item {
      margin-bottom: 32rpx;
      background-color: #f5f7fa;
      height: 96rpx;
      border-radius: 48rpx;
      display: flex;
      align-items: center;
      padding: 0 32rpx;
      transition: all 0.3s ease;
      
      &:focus-within {
        background-color: #eff1f5;
        box-shadow: 0 0 0 4rpx rgba(102, 126, 234, 0.1);
      }

      .input-icon {
        margin-right: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .input {
        flex: 1;
        font-size: 28rpx;
        color: #303133;
        
        &::placeholder {
          color: #c0c4cc;
        }
      }
    }
    
    .remember-section {
      margin-bottom: 40rpx;
      padding-left: 8rpx;
    }

    .action-btn {
      margin-top: 48rpx;
      
      .login-btn {
        width: 100%;
        height: 96rpx;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 48rpx;
        border: none;
        box-shadow: 0 12rpx 32rpx rgba(102, 126, 234, 0.4);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        
        &::after {
          border: none;
        }
        
        &:active {
          transform: scale(0.98);
          box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
        }
        
        .btn-text {
          color: #ffffff;
          font-size: 32rpx;
          font-weight: 600;
        }
      }
    }
  }

  .footer-links {
    text-align: center;
    padding: 60rpx 0 80rpx;
    position: relative;
    z-index: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16rpx;
    
    .link-item {
      color: rgba(255, 255, 255, 0.9);
      font-size: 26rpx;
      transition: all 0.3s ease;
      
      &:active {
        opacity: 0.7;
      }
    }
    
    .separator {
      color: rgba(255, 255, 255, 0.5);
      font-size: 26rpx;
    }
  }
}
</style>
