<template>
  <view v-if="checkingToken" class="token-transition-screen">
    <view class="token-loading-card">
      <view class="token-loading-spinner"></view>
      <text class="token-loading-text">正在加载中...</text>
    </view>
  </view>

  <view v-else class="login-container">
    <!-- Logo和标题区域 -->
    <view class="header-section">
      <view class="logo-box">
        <image class="logo" :src="globalConfig.appInfo.logo" mode="aspectFit"></image>
      </view>
      <text class="app-title">暖康档案管理平台</text>
      <text class="app-subtitle">专业的健康管理工具</text>
    </view>
    
    <!-- 登录表单卡片 -->
    <view class="form-card">
      <!-- 账号输入 -->
      <view class="input-item">
        <uni-icons type="person" size="20" color="#E8841A"></uni-icons>
        <input 
          v-model="loginForm.username" 
          class="input-field" 
          type="text" 
          placeholder="请输入账号" 
          placeholder-class="placeholder"
          maxlength="30" 
        />
      </view>
      
      <!-- 密码输入 -->
      <view class="input-item password-item">
        <uni-icons type="locked" size="20" color="#E8841A"></uni-icons>
        <input 
          v-model="loginForm.password" 
          type="text"
          password
          class="input-field" 
          placeholder="请输入密码"
          placeholder-class="placeholder"
          maxlength="20" 
        />
        <!-- H5 端记住密码开关（在密码框右侧） -->
        <view v-if="isH5" class="pwd-remember" @click.stop="rememberChange">
          <text class="pwd-remember-text">记住密码</text>
          <view :class="['mini-switch', rememberPwd ? 'on' : '']">
            <view class="mini-switch-dot"></view>
          </view>
        </view>
      </view>
      
      <!-- 用户协议 -->
      <view class="agreement-box">
        <view class="agreement-row" @click="agreeChange">
          <view :class="['checkbox-small', agree ? 'checked' : '']">
            <uni-icons v-if="agree" type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
          </view>
          <text class="agreement-text">已阅读并同意</text>
          <text class="link-text" @click.stop="handleUserAgrement">《用户协议》</text>
          <text class="agreement-text">和</text>
          <text class="link-text" @click.stop="handlePrivacy">《隐私协议》</text>
        </view>
      </view>
      
      <!-- 登录按钮 -->
      <button @click="handleLogin" class="login-btn">登录</button>
      
      <!-- 立即注册按钮 -->
      <view class="register-btn" @click="handleRegister">
        <text>立即注册</text>
      </view>
    </view>
    
    <!-- 版权信息 -->
    <view class="copyright">
      <text>Copyright © {{ currentYear }} qdintc All Rights Reserved.</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 { getToken, setToken } from '@/utils/auth';
import { encrypt, decrypt } from '@/utils/jsencrypt'

// 动态显示当前年份
const currentYear = new Date().getFullYear()

// ========== 平台判断（条件编译）==========
// H5 端为 true，其他端为 false。条件编译保证仅 H5 打包对应逻辑
let isH5 = false
// #ifdef H5
isH5 = true
// #endif

const REMEMBER_KEY = 'remember_login_info'

const userStore = useUserStore()
const codeUrl = ref("");
const captchaEnabled = ref(true); // 是否开启验证码
const useWxLogin = ref(false); // 是否使用微信登录
const globalConfig = ref(config);
const agree = ref(isH5 ? true : false); // H5 端默认勾选同意协议
const rememberPwd = ref(false); // 记住密码
const checkingToken = ref(true); // 是否正在校验本地 token
const loginForm = ref({
  username: "",
  password: "",
  code: "",
  uuid: ''
});

if (useWxLogin.value) {
  getWxCode().then(res => {
    console.log(res);
    wxLogin('miniapp',res).then(res => {
      if(res.token != null){
        setToken(res.token);
        loginSuccess()
      }
    });
  })
}
// 页面加载时先校验本地 token，仍有效则直接进入系统；无效时再显示账号密码登录
onMounted(() => {
  initLoginPage()
});

async function initLoginPage() {
  const token = getToken()
  if (token) {
    checkingToken.value = true
    let tokenValid = false
    try {
      await userStore.getInfo(true)
      tokenValid = true
    } catch (error) {
      if (error && error.code === 401) {
        userStore.resetToken()
      }
    }

    if (tokenValid) {
      goHome()
      return
    }
  }

  checkingToken.value = false
  loadRememberedLogin()
  getCode()
}

// 读取本地记住的登录信息（仅 H5）
function loadRememberedLogin() {
  if (!isH5) return
  try {
    const raw = uni.getStorageSync(REMEMBER_KEY)
    if (!raw) return
    const info = JSON.parse(raw)
    if (info && info.username) {
      loginForm.value.username = info.username
      // 密码以 base64 存储，解码后回填
      if (info.password) {
        try {
          loginForm.value.password = decodeURIComponent(escape(atob(info.password)))
        } catch (e) {
          loginForm.value.password = ''
        }
      }
      rememberPwd.value = true
    }
  } catch (e) {
    console.error('读取记住的登录信息失败', e)
    uni.removeStorageSync(REMEMBER_KEY)
  }
}

// 保存或清除记住的登录信息（仅 H5）
function saveRememberedLogin() {
  if (!isH5) return
  if (rememberPwd.value && loginForm.value.username) {
    const info = {
      username: loginForm.value.username,
      // 密码使用 base64 简单编码，避免明文存储
      password: btoa(unescape(encodeURIComponent(loginForm.value.password || '')))
    }
    uni.setStorageSync(REMEMBER_KEY, JSON.stringify(info))
  } else {
    uni.removeStorageSync(REMEMBER_KEY)
  }
}

// 获取图形验证码
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 if (!agree.value) {
    modal.msgError("请先阅读并同意用户协议和隐私协议")
  } else {
    modal.loading("登录中，请等待...")
    pwdLogin()
  }
};
// 密码登录
async function pwdLogin() {
  userStore.login(loginForm.value).then(() => {
    modal.closeLoading()
    // 登录成功后保存或清除记住的密码
    saveRememberedLogin()
    loginSuccess()
  }).catch(() => {
    if (captchaEnabled.value) {
      modal.closeLoading()
      getCode()
    }
  })
};
function loginSuccess(result) {
  // 设置用户信息
  userStore.getInfo().then(res => {
    goHome()
  })
}

function goHome() {
  uni.switchTab({
    url: '/pages/health/homepage/index'
  });
}

function agreeChange(){
  agree.value = !agree.value;
}

// 切换记住密码状态
function rememberChange(){
  rememberPwd.value = !rememberPwd.value;
}

// 隐私协议
function handlePrivacy() {
  uni.navigateTo({
    url: '/pages/common/privacy/index'
  });
}

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

<style lang="scss" scoped>
page {
  background: linear-gradient(160deg, #FFF3D6 0%, #FFE0A0 60%, #FFCC6E 100%);
  height: 100%;
}

.login-container {
  min-height: 100vh;
  background: linear-gradient(160deg, #FFF3D6 0%, #FFE0A0 60%, #FFCC6E 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 48rpx;
}

.token-transition-screen {
  width: 100%;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(160deg, #FFF3D6 0%, #FFE0A0 60%, #FFCC6E 100%);
}

.token-loading-card {
  min-width: 220rpx;
  min-height: 180rpx;
  padding: 40rpx 48rpx;
  border-radius: 32rpx;
  background: rgba(255, 255, 255, 0.72);
  border: 1rpx solid rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 16rpx 48rpx rgba(139, 69, 0, 0.14);
}

.token-loading-spinner {
  width: 58rpx;
  height: 58rpx;
  border-radius: 50%;
  border: 6rpx solid rgba(232, 132, 26, 0.2);
  border-top-color: #E8841A;
  animation: token-loading-spin 0.8s linear infinite;
  margin-bottom: 24rpx;
}

.token-loading-text {
  font-size: 28rpx;
  color: #8B4500;
  font-weight: 500;
}

@keyframes token-loading-spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

.header-section {
  padding-top: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
  
  .logo-box {
    width: 160rpx;
    height: 160rpx;
    background: #ffffff;
    border-radius: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 32rpx;
    
    .logo {
      width: 120rpx;
      height: 120rpx;
    }
  }
  
  .app-title {
    font-size: 40rpx;
    font-weight: 600;
    color: #8B4500;
    margin-bottom: 12rpx;
  }
  
  .app-subtitle {
    font-size: 24rpx;
    color: rgba(139, 69, 0, 0.65);
  }
}

.form-card {
  width: 100%;
  background: #ffffff;
  border-radius: 24rpx;
  padding: 48rpx 40rpx 40rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
}

.input-item {
  height: 88rpx;
  background: #f7f8fa;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  padding: 0 28rpx;
  margin-bottom: 24rpx;
  
  .input-field {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    margin-left: 20rpx;
  }
  
  .placeholder {
    color: #c0c4cc;
  }
  
  /* H5 端记住密码开关 */
  .pwd-remember {
    display: flex;
    align-items: center;
    margin-left: 16rpx;
    flex-shrink: 0;
    padding: 6rpx 4rpx;
    
    .pwd-remember-text {
      font-size: 22rpx;
      color: #909399;
      margin-right: 10rpx;
      line-height: 1;
    }
    
    /* 迷你开关（关闭：灰色） */
    .mini-switch {
      width: 56rpx;
      height: 30rpx;
      border-radius: 15rpx;
      background: #dcdfe6;
      position: relative;
      transition: background 0.25s ease;
      
      &.on {
        background: #E8841A;
      }
      
      .mini-switch-dot {
        position: absolute;
        top: 3rpx;
        left: 3rpx;
        width: 24rpx;
        height: 24rpx;
        border-radius: 50%;
        background: #ffffff;
        transition: transform 0.25s ease;
        box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.15);
      }
      
      &.on .mini-switch-dot {
        transform: translateX(26rpx);
      }
    }
  }
}

.agreement-box {
  margin-bottom: 32rpx;
  margin-top: 24rpx;
  padding: 0 4rpx;
  
  .agreement-row {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    line-height: 1.6;
    
    .checkbox-small {
      width: 28rpx;
      height: 28rpx;
      border: 2rpx solid #dcdfe6;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 10rpx;
      flex-shrink: 0;
      
      &.checked {
        background: #E8841A;
        border-color: #E8841A;
      }
    }
    
    .agreement-text {
      font-size: 24rpx;
      color: #606266;
      line-height: 1.6;
    }
    
    .link-text {
      font-size: 24rpx;
      color: #E8841A;
      text-decoration: none;
      line-height: 1.6;
    }
  }
}

.login-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #E8841A 0%, #F5A623 100%);
  border-radius: 44rpx;
  border: none;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 500;
  margin-bottom: 24rpx;
  
  &::after {
    border: none;
  }
  
  &:active {
    opacity: 0.9;
  }
}

.register-btn {
  width: 100%;
  height: 88rpx;
  background: transparent;
  border: 2rpx solid #E8841A;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  text {
    font-size: 32rpx;
    color: #E8841A;
    font-weight: 500;
  }
  
  &:active {
    opacity: 0.8;
    background: rgba(232, 132, 26, 0.05);
  }
}

.copyright {
  text-align: center;
  padding: 40rpx 0 60rpx;
  
  text {
    font-size: 22rpx;
    color: #8B4500;
  }
}
</style>
