<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <img src="@/assets/logo.png" alt="logo" class="logo">
        <h2>省信息中心对话系统</h2>
      </div>
      <div class="login-form">
        <div class="form-item">
          <div class="input-with-icon">
            <img src="@/assets/login-user.png" alt="账号" class="input-icon">
            <input type="text" v-model="username" placeholder="请输入账号">
          </div>
        </div>
        <div class="form-item">
          <div class="input-with-icon">
            <img src="@/assets/login-password.png" alt="密码" class="input-icon">
            <input type="password" v-model="password" placeholder="请输入登录密码">
          </div>
        </div>
        <div class="form-item">
          <div class="captcha-container">
            <input type="text" v-model="captcha" placeholder="请输入验证码" class="captcha-input">
            <img :src="captchaUrl" alt="验证码" class="captcha-img" @click="refreshCaptcha">
          </div>
        </div>
        <div class="form-options">
          <label class="remember-pwd">
            <input type="checkbox" v-model="rememberPassword">
            <span>记住密码</span>
          </label>
          <!-- <a href="#" class="forget-pwd" @click.prevent="handleForgetPassword">忘记密码？</a> -->
        </div>
        <div class="form-item">
          <button @click="handleLogin" :disabled="loading">
            {{ loading ? '登录中...' : '登录' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUuid } from '@/utils'
import { post, get } from '@/utils/request'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const username = ref('')
const password = ref('')
const loading = ref(false)
const rememberPassword = ref(false)
const captcha = ref('')
const uuid = ref('')
const captchaUrl = ref('')


// 刷新验证码
const refreshCaptcha = () => {
  uuid.value = getUuid()
  console.log('import.meta.env.VITE_API_BASE_URL', import.meta.env.VITE_API_BASE_URL);
  
  captchaUrl.value = `${import.meta.env.VITE_API_BASE_URL}/admin/captcha?uuid=${uuid.value}&t=${Date.now()}`
}

onMounted(() => {
  const savedUsername = localStorage.getItem('remembered_username')
  const savedPassword = localStorage.getItem('remembered_password')
  const remembered = localStorage.getItem('remember_password') === 'true'
  
  if (remembered && savedUsername && savedPassword) {
    username.value = savedUsername
    password.value = savedPassword
    rememberPassword.value = true
  }
  
  // 初始化验证码
  refreshCaptcha()
})

const handleForgetPassword = () => {
  // 处理忘记密码
  console.log('忘记密码')
}

const saveLoginInfo = () => {
  if (rememberPassword.value) {
    localStorage.setItem('remembered_username', username.value)
    localStorage.setItem('remembered_password', password.value)
    localStorage.setItem('remember_password', 'true')
  } else {
    localStorage.removeItem('remembered_username')
    localStorage.removeItem('remembered_password')
    localStorage.setItem('remember_password', 'false')
  }
}

const handleLogin = async () => {
  if (!username.value || !password.value || !captcha.value) {
    alert('请输入账号、密码和验证码')
    return
  }

  loading.value = true
  try {
    // 这里添加实际的登录逻辑
    const res = await post('/admin/login',{
      username: username.value,
      password: password.value,
      uuid: uuid.value,
      captcha: captcha.value,
      userType: 2
    })
    // console.log('res', res)
    const userStore = useUserStore()
    userStore.setToken(res.data.token)
    
    // 获取用户信息
    const userInfoRes = await get('/admin/sys/user/info')||{}
    userStore.setUserInfo(userInfoRes.data)
    
    // 保存登录信息（如果勾选了记住密码）
    saveLoginInfo()

     // 通过接口检查密码是否过期
     const pwdExpireRes = await get('/admin/sys/user/pwdExpire')
    //  console.log('pwdExpireRes', pwdExpireRes);
     if(pwdExpireRes.data.isExpire ){
      ElMessage.error(pwdExpireRes.data.tipMsg||'密码已过期，请修改密码');
      return
     }  
    
    // 模拟登录成功
    // localStorage.setItem('token', 'demo-token')
    router.push('/')
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.data.msg||'登录失败，请重试')
    // 登录失败时刷新验证码
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  background: url('@/assets/login-bg.png') no-repeat center center;
  background-size: cover;

  .login-box {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.95);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    margin-right: 10%;

    .login-header {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        width: 80px;
        height: 80px;
        margin-bottom: 16px;
      }

      h2 {
        color: #333;
        font-size: 24px;
        margin: 0;
      }
    }

    .login-form {
      .form-item {
        margin-bottom: 20px;

        .input-with-icon {
          position: relative;
          
          .input-icon {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            width: 20px;
            height: 20px;
          }

          input {
            width: 100%;
            height: 40px;
            padding: 0 15px 0 45px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            
            &:focus {
              border-color: #409eff;
              outline: none;
            }
          }
        }

        .captcha-container {
          display: flex;
          gap: 10px;

          .captcha-input {
            flex: 1;
            height: 40px;
            padding: 0 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            font-size: 14px;
            
            &:focus {
              border-color: #409eff;
              outline: none;
            }
          }

          .captcha-img {
            width: 120px;
            height: 40px;
            border-radius: 4px;
            cursor: pointer;
          }
        }

        button {
          width: 100%;
          height: 40px;
          background: linear-gradient(135deg, #FF6B6B 0%, #FF4141 100%);
          border: none;
          border-radius: 4px;
          color: white;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            opacity: 0.9;
            transform: translateY(-1px);
          }

          &:disabled {
            background: $primary-color;
            opacity: 0.5;
            cursor: not-allowed;
          }
        }
      }

      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        font-size: 14px;

        .remember-pwd {
          display: flex;
          align-items: center;
          cursor: pointer;

          input[type="checkbox"] {
            margin-right: 5px;
          }
        }

        .forget-pwd {
          color: #409eff;
          text-decoration: none;

          &:hover {
            color: #66b1ff;
          }
        }
      }
    }
  }
}
</style> 