<template>
  <h1 style="margin:100px 0px 100px 0px; text-align:center">登录AUTS</h1>
  <div class="login-container">
    <t-form @submit="handleSubmit">
      <t-input v-model="form.username"
               label="账号"
               placeholder="请输入账号"
               @focus="MoveToEnd"
               clearable />
      <t-input v-model="form.password"
               label="密码"
               placeholder="请输入密码"
               @focus="MoveToEnd"
               type="password"
               clearable />
      <t-input v-model="form.code"
               maxlength="4"
               :placeholder="captchaSrc ? '请输入验证码' : '点击获取验证码'"
               label="验证码"
               @focus="getCaptchaSrc"
               clearable>
        <template #suffix>
          <div class="suffix" v-if="captchaSrc">
            <t-image class="image"
                     :src="captchaSrc"
                     @click="generateCaptcha"
                     mode="heightFix"
                     aria-role="img"
                     aria-label="验证码" />
          </div>
        </template>
      </t-input>
      <t-checkbox v-model="form.remember">记住密码</t-checkbox>
      <t-button v-if="!isLocked"
                theme="primary"
                type="submit"
                block
                :loading="loading">登录</t-button>
      <t-button v-if="isLocked"
                theme="danger"
                type="submit"
                ghost
                disabled>密码错误，账号已锁定</t-button>
    </t-form>
  </div>
</template>

<script setup>
  import { inject, ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { Toast } from 'tdesign-mobile-vue'

  const router = useRouter()
  // 存储数据
  //sessionStorage.setItem('test', 'a123');
  //sessionStorage.getItem('username');
  //sessionStorage.removeItem('username');
  const successMethod = () => {
    console.log('验证成功')
  }

  const form = ref({
    username: '',
    password: '',
    remember: false,
    code: ''
  })

  // 状态定义
  const isDarkMode = ref(false)
  const loading = ref(false)
  const submitDisabled = ref(false) // 提交禁用状态
  const isLocked = ref(false)       // 账号锁定状态
  const errorAttempts = ref(0)      // 错误尝试次数
  const $http = inject('$http')
  const LOCK_STORAGE_KEY = 'loginLockUntil'  // 锁定时间存储键
  const ATTEMPTS_STORAGE_KEY = 'loginErrorAttempts'
  const captchaSrc = ref('')
  const captchaValue = ref('')
  /*localStorage.removeItem('token')*/

  const checkLoginStatus = inject('checkLoginStatus');
  checkLoginStatus();

  // 初始化认证状态
  const initAuthState = () => {
    const storedLockUntil = localStorage.getItem(LOCK_STORAGE_KEY)
    const storedAttempts = localStorage.getItem(ATTEMPTS_STORAGE_KEY)

    errorAttempts.value = parseInt(storedAttempts) || 0

    if (storedLockUntil) {
      const remainingTime = parseInt(storedLockUntil) - Date.now()

      if (remainingTime > 0) {
        isLocked.value = true
        setupUnlockTimer(remainingTime)
      } else {
        // 清理过期数据
        localStorage.removeItem(LOCK_STORAGE_KEY)
        localStorage.removeItem(ATTEMPTS_STORAGE_KEY)
        errorAttempts.value = 0
      }
    }
  }

  // 设置解锁定时器
  const setupUnlockTimer = (duration) => {
    isLocked.value = true
    const timer = setTimeout(() => {
      isLocked.value = false
      errorAttempts.value = 0
      localStorage.removeItem(LOCK_STORAGE_KEY)
      localStorage.removeItem(ATTEMPTS_STORAGE_KEY)
      clearTimeout(timer)
    }, duration)
  }

  // 初始化认证状态
  onMounted(() => {
    //mountedToken()
    initAuthState()
    localStorage.setItem('login', false)
    getCaptchaSrc()
  });

  const mountedToken = () => {
    $http.post('Login/Helloooo', '')
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          router.push('/home')
          /*Toast({
            className: 'toast-root--success',
            theme: 'success',
            direction: 'column',
            message: '登录成功!',
          });*/

        } else {
          Toast(rs.data.message)
        }

      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {

      })
  }
  // 新增深色模式状态
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    isDarkMode.value = true;
  } else {
    isDarkMode.value = false;
  }


  const clearUsername = () => {
    form.value.username = ''
  }


  // 滚动页面
  const MoveToEnd = () => {
    // 滚动到页面底部
    window.scrollTo({
      top: document.body.scrollHeight,
      behavior: 'smooth' // 可选，用于平滑滚动
    });
  }

  const getCaptchaSrc = () => {
    if (captchaValue.value == "") {
      generateCaptcha()
    }
    MoveToEnd()
  }
  // 生成验证码
  const generateCaptcha = () => {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const chars = '0123456789';
    let captcha = '';
    canvas.width = 86;
    canvas.height = 30;

    // 生成验证码字符串
    for (let i = 0; i < 4; i++) {
      captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    captchaValue.value = captcha; // 存储验证码值用于验证

    // 绘制背景
    ctx.fillStyle = isDarkMode.value ? '#242424' : '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制噪点
    ctx.fillStyle = isDarkMode.value ? '#FFFFFF' : '#000000';
    for (let i = 0; i < 33; i++) {
      const x = Math.random() * canvas.width;
      const y = Math.random() * canvas.height;
      ctx.beginPath();
      ctx.arc(x, y, 1, 0, Math.PI * 2, false);
      ctx.fill();
    }

    // 绘制验证码
    ctx.font = '24px Arial';
    let xnd = 10;
    for (let i = 0; i < captcha.length; i++) {
      const angle = (Math.random() * 30) - 15; // -10度到+10度

      // 保存当前状态
      ctx.save();

      // 旋转并绘制文字
      ctx.translate(xnd, 20);
      ctx.rotate(angle * Math.PI / 180);
      ctx.fillText(captcha[i], 0, 0);

      // 恢复状态
      ctx.restore();

      // 更新下一个字符的x位置
      xnd += 15 + Math.abs(angle) / 2; // 根据角度调整字符间距
    }

    // 添加5-10条干扰条纹
    ctx.strokeStyle = '#6F4A2F';
    const bug = Math.floor(Math.random() * 6) + 3
    for (let i = 0; i < bug; i++) {
      ctx.beginPath();
      ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.stroke();
    }
    // 将canvas转换为图片URL
    captchaSrc.value = canvas.toDataURL('image/png');
  }
  // 验证验证码
  const verifyCaptcha = (inputValue) => {
    // 验证输入的验证码是否正确
    return inputValue === captchaValue.value;
  }

  // 登录
  const handleSubmit = () => {
    if (isLocked.value || submitDisabled.value) return
    if (!form.value.username) {
      Toast('请输入账号！')
      return
    }
    if (!form.value.password) {
      Toast('请输入密码！')
      return
    }
    if (!form.value.code) {
      Toast('请输入验证码！')
      return
    }
    if (!verifyCaptcha(form.value.code)) {
      Toast('验证码错误！')
      generateCaptcha()
      return
    }

    loading.value = true
    submitDisabled.value = true

    const formdata = {
      username: form.value.username,
      password: form.value.password
    }

    $http.post('Login/Login', formdata)
      .then(rs => {
        //console.log(rs)
        if (rs.data.isok) {
          // 登录成功处理...
          errorAttempts.value = 0
          localStorage.removeItem(ATTEMPTS_STORAGE_KEY)
          localStorage.removeItem(LOCK_STORAGE_KEY)
          // 存储token
          localStorage.setItem('token', rs.data.response.accessToken)
          localStorage.setItem('username', rs.data.response.userName)
          localStorage.setItem('auths', JSON.stringify(rs.data.response.auths))
          localStorage.setItem('login', true)
          localStorage.setItem('uid', rs.data.response.id)

          // 记住账号和密码
          if (form.value.remember) {
            localStorage.setItem('rememberedUsername', form.value.username)
            localStorage.setItem('rememberedPassword', form.value.password)
          } else {
            localStorage.removeItem('rememberedPassword')
          }
          Toast({
            className: 'toast-root--success',
            theme: 'success',
            direction: 'column',
            message: '登录成功，欢迎：' + rs.data.response.userName + '！',
          });
          router.push('/home')
        } else {
          Toast(rs.data.message)
          errorAttempts.value++
          localStorage.setItem(ATTEMPTS_STORAGE_KEY, errorAttempts.value)

          if (errorAttempts.value >= 5) {
            const lockUntil = Date.now() + 3600000
            localStorage.setItem(LOCK_STORAGE_KEY, lockUntil)
            setupUnlockTimer(3600000)
          }
        }

      })
      .catch(error => {
        // 处理错误情况
        console.error(error);
      })
      .finally(() => {
        setTimeout(() => {
          loading.value = false
        }, 300)
        setTimeout(() => {
          submitDisabled.value = false
        }, 30000)
      })
  }

  // 初始化记住的账号和密码
  form.value.username = localStorage.getItem('rememberedUsername') || ''
  form.value.password = localStorage.getItem('rememberedPassword') || ''
  form.value.remember = form.value.username !== '' && form.value.password !== ''


</script>

<style scoped>
  .login-container {
    padding: 16px;
  }
  /* 基础样式 */
  .container {
    min-height: 100vh;
    padding: 40px 16px;
    transition: background-color 0.3s, color 0.3s;
    background-color: var(--bg-color);
    color: var(--text-color);
  }

  .title {
    text-align: center;
    margin-bottom: 40px;
    font-size: 24px;
    color: var(--primary-color);
  }

  .login-container {
    max-width: 400px;
    margin: 0 auto;
    padding: 24px;
    background: var(--card-bg);
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  /* 输入框间距优化 */
  .t-form {
    display: flex;
    margin: 18px 10px 10px 10px;
    flex-direction: column;
    gap: 25px;
  }

  /* 按钮样式优化 */
  .t-button {
    margin-top: 5px;
    height: 40px;
    font-weight: 400;
  }

  .t-checkbox--block {
    padding: 0;
  }
  /* 主题切换按钮 */
  .theme-toggle {
    position: fixed;
    top: 16px;
    right: 16px;
    padding: 8px 16px;
    background: var(--toggle-bg);
    color: var(--toggle-text);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    z-index: 100;
  }

  /* 响应式设计 */
  @media (max-width: 480px) {
    .container {
      padding: 24px 12px;
    }

    .login-container {
      padding: 5px;
      border-radius: 8px;
    }

    .title {
      font-size: 20px;
      margin-bottom: 32px;
    }
  }

  @media (min-width: 768px) {
    .login-container {
      padding: 5px;
      border-radius: 16px;
    }

    .title {
      font-size: 28px;
    }
  }
</style>
