<template>
  <div class="login">
    <div class="login-container">
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <img class="title-logo" src="../assets/images/login-logo.png" alt="瑞鲸科技"/>
        <h3 class="title">{{ title }}</h3>
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              type="text"
              size="large"
              auto-complete="off"
              placeholder="账号"
          >
            <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              size="large"
              auto-complete="off"
              placeholder="密码"
              @keyup.enter="handleLogin"
          >
            <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
              v-model="loginForm.code"
              size="large"
              auto-complete="off"
              placeholder="验证码"
              style="width: 63%"
              @keyup.enter="handleLogin"
          >
            <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img"/>
          </div>
        </el-form-item>
<!--        <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>-->

        <!-- 同意用户协议和隐私协议复选框（已移除Cookie政策） -->
        <el-form-item prop="agree" style="margin-bottom: 20px;">
          <el-checkbox v-model="loginForm.agree">
            我已阅读并同意
            <el-link type="primary" :underline="false" href="https://rjsd.mychery.com/user_agreement.html" target="_blank">《用户协议》</el-link>
            和
            <el-link type="primary" :underline="false" href="https://rjsd.mychery.com/privacy_policy.html" target="_blank">《隐私政策》</el-link>
          </el-checkbox>
        </el-form-item>

        <el-form-item style="width:100%;">
          <el-button
              :loading="loading"
              size="large"
              type="primary"
              style="width:100%;"
              @click.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!-- Cookie同意横幅（底部，含查看链接和同意按钮） -->
    <div v-if="showCookieBanner" class="cookie-banner">
      <span class="cookie-text">
        我们将使用Cookie优化您的浏览体验，并通过第三方SDK实现网站功能。
        <el-link type="primary" :underline="false" href="https://rjsd.mychery.com/cookie.html" target="_blank">查看《Cookie政策》</el-link>
      </span>
      <el-button type="primary" size="small" @click="acceptCookies">同意</el-button>
    </div>

    <!-- 底部版权信息 -->
    <div class="el-login-footer">
      <span>{{ footerContent }}</span>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'
import defaultSettings from '@/settings'
import { ElMessage } from "element-plus"
import { ref, watch, getCurrentInstance, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const title = import.meta.env.VITE_APP_TITLE
const footerContent = defaultSettings.footerContent
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 登录表单数据
const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: "",
  agree: false          // 仅用于用户协议和隐私政策
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
  agree: [{ required: true, trigger: "change", message: "请同意用户协议和隐私政策" }]
}

const codeUrl = ref("")
const loading = ref(false)
const captchaEnabled = ref(true)   // 验证码开关
const register = ref(false)        // 注册开关
const redirect = ref(undefined)
const showCookieBanner = ref(false) // 控制Cookie横幅显示

// 监听重定向地址
watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

// 登录处理
function handleLogin() {
  if (!proxy.$refs.loginRef) return

  proxy.$refs.loginRef.validate((valid) => {
    // 检查是否已同意用户协议和隐私政策
    if (!loginForm.value.agree) {
      ElMessage.warning('请先同意用户协议和隐私政策')
      return
    }

    // 检查是否已同意Cookie政策
    const cookieConsented = localStorage.getItem('cookieConsent') === 'true'
    // if (!cookieConsented) {
    //   ElMessage.warning('请先同意Cookie政策')
    //   // 如果未同意，显示横幅引导用户操作
    //   showCookieBanner.value = true
    //   return
    // }

    if (valid) {
      loading.value = true
      // 记住密码
      // if (loginForm.value.rememberMe) {
      //   Cookies.set("username", loginForm.value.username, { expires: 30 })
      //   Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
      //   Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
      // } else {
      //   Cookies.remove("username")
      //   Cookies.remove("password")
      //   Cookies.remove("rememberMe")
      // }

      userStore.login(loginForm.value).then(() => {
        const query = route.query
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        router.push({ path: redirect.value || "/", query: otherQueryParams })
      }).catch(() => {
        loading.value = false
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}

// 获取验证码
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
    }
  })
}

// 从Cookie读取记住的密码
function getCookie() {
  try {
    const username = Cookies.get("username")
    const password = Cookies.get("password")
    const rememberMe = Cookies.get("rememberMe")

    if (username !== undefined) loginForm.value.username = username
    if (password !== undefined) {
      try {
        loginForm.value.password = decrypt(password)
      } catch (e) {
        console.warn('密码解密失败', e)
        loginForm.value.password = ''
      }
    }
    if (rememberMe !== undefined) loginForm.value.rememberMe = Boolean(rememberMe)
  } catch (e) {
    console.error('读取Cookie失败', e)
  }
}

// 检查Cookie同意状态，控制横幅显示
function checkCookieConsent() {
  const consented = localStorage.getItem('cookieConsent') === 'true'
  showCookieBanner.value = !consented   // 未同意则显示横幅
}

// 同意Cookie（点击横幅按钮）
function acceptCookies() {
  localStorage.setItem('cookieConsent', 'true')
  showCookieBanner.value = false
  // ElMessage.success('感谢您同意Cookie政策')
}

// 初始化
onMounted(() => {
  getCode()
  // getCookie()
  checkCookieConsent()
})
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.png");
  background-size: cover;
}
.login-container{
  background: #ffffff;
  width: 40%;
  height: 100%;
  position: absolute;
  right: 0;
  padding-top: 5%;

  .title-logo {
    margin: 30px auto;
    color: #333;
    font-size: 24px;
    width: 100%;
    height: 100%;
    font-weight: bold;
  }

  .title {
    margin: 0px auto 30px auto;
    text-align: center;
    color: #333;
    font-size: 24rpx;
    line-height: 32rpx;
  }
}

.login-form {
  z-index: 1;
  display: flex;
  flex-direction: column;
  margin: 0px 30%;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  height: 40px;
}

/* Cookie同意横幅样式：深色字体，浅色背景，固定在底部 */
.cookie-banner {
  position: fixed;
  bottom: 40px;          /* 位于版权信息上方 */
  left: 0;
  width: 100%;
  background-color: #f9f9f9;  /* 浅色背景 */
  color: #333;                /* 深色字体 */
  padding: 12px 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  box-shadow: 0 -2px 8px rgba(0,0,0,0.1);
  z-index: 1000;
  font-size: 14px;
  flex-wrap: wrap;
  text-align: center;
}
.cookie-text {
  max-width: 70%;
  line-height: 1.5;
}
.el-button--small {
  background-color: #409EFF;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-weight: 500;
}
.el-button--small:hover {
  background-color: #66b1ff;
}
/* 底部查看链接样式 */
.cookie-text .el-link {
  margin-left: 4px;
  font-weight: 500;
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>