<template>
  <div class="pc-register-container">
    <img src="@/assets/image/logo.png" class="top-left-logo" alt="logo" />

    <div class="lang-selector-wrapper">
      <selectLang />
    </div>

    <div class="bg-glow glow-top-left"></div>
    <div class="bg-glow glow-bottom-right"></div>

    <div class="register-card">
      <div class="mclaren-header">
        <img src="@/assets/image/login/mclaren.png" class="mclaren-img-logo" alt="mclaren logo" />
        <div class="main-title">迈凯伦</div>
        <div class="sub-partner">官方合作伙伴</div>
      </div>

      <el-tabs v-model="activeRegisterType" class="custom-tabs" stretch @tab-change="resetForm">
        <el-tab-pane :label="t('账号注册')" name="account"></el-tab-pane>
        <el-tab-pane :label="t('邮箱注册')" name="email"></el-tab-pane>
      </el-tabs>

      <div class="form-wrapper">
        <el-input v-if="activeRegisterType === 'email'" v-model="formData.account" :placeholder="t('请输入邮箱地址')" clearable size="large" class="custom-input">
          <template #prefix>
            <img src="@/assets/image/login/account.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>

        <el-input v-else v-model="formData.account" :placeholder="t('请输入账号')" clearable size="large" class="custom-input">
          <template #prefix>
            <img src="@/assets/image/login/account.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>

        <el-input v-model="formData.password" :placeholder="t('请输入6-20位密码')" type="password" show-password clearable size="large" class="custom-input">
          <template #prefix>
            <img src="@/assets/image/login/lock.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>

        <el-input v-model="formData.confirmPassword" :placeholder="t('请再次确认密码')" type="password" show-password clearable size="large" class="custom-input">
          <template #prefix>
            <img src="@/assets/image/login/lock.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>

        <el-input v-model="formData.user_code" :placeholder="t('请输入邀请码')" clearable size="large" class="custom-input">
          <template #prefix>
            <img src="@/assets/image/login/user.png" class="input-icon" alt="icon"/>
          </template>
        </el-input>
      </div>

      <div class="agreement-row">
        <el-checkbox v-model="agreed" class="custom-checkbox">{{ t('我已阅读并同意') }}</el-checkbox>
        <span class="agreement-link" @click="onAgreementClick">《{{ t('产品服务协议') }}》</span>
      </div>

      <el-button type="primary" class="submit-btn" size="large" @click="onRegisterClick">
        {{ t('立即注册') }}
      </el-button>

      <div class="bottom-action-group">
        <div class="action-item" @click="router.push('/login')">
          <img src="@/assets/image/login/user.png" class="action-icon" alt="login" />
          <span>{{ t('去登录') }}</span>
        </div>
        <div class="action-item" @click="onLineService">
          <img src="@/assets/image/login/kefu.png" class="action-icon" alt="service" />
          <span>{{ t('在线客服') }}</span>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="showCaptchaDialog"
      :title="t('安全验证')"
      width="360px"
      :close-on-click-modal="false"
      class="custom-captcha-dialog"
    >
      <div class="captcha-container" v-show="captchaData.bg">
        <div class="bg-container">
          <img :src="captchaData.bg" class="bg-img" alt="captcha-bg">
          <img :src="captchaData.slider" class="slider-img"
               :style="{ top: captchaData.y + 'px', left: sliderMoveX + 'px', display: isSliderVerified ? 'none' : 'block' }"
               alt="captcha-slider">
          <div class="success-overlay" v-show="isSliderVerified">
            <el-icon class="success-icon"><Ticket /></el-icon>
            <span>{{ t('验证通过') }}</span>
          </div>
        </div>
        <div class="track">
          <div class="track-bg" :style="{ width: sliderMoveX + 20 + 'px' }"></div>
          <div class="drag-btn"
               :class="{ 'is-success': isSliderVerified }"
               :style="{ left: sliderMoveX + 'px' }"
               @mousedown="onDragStart">
               <el-icon v-if="!isSliderVerified"><Key /></el-icon>
               <el-icon v-else><Ticket /></el-icon>
          </div>
          <div class="track-text">{{ isSliderVerified ? t('验证成功') : t('向右滑动完成验证') }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Message, Lock, Iphone, Key, Ticket } from '@element-plus/icons-vue';

import { appName } from '@/settings/index.mjs';
import selectLang from '@/components/selectLang/index.vue';
import {postUserRegister, postUserCaptcha, userGuestRegister} from "@/request/api";

const router = useRouter();
const route = useRoute();
const { t } = useI18n();

const agreed = ref(false);
const activeRegisterType = ref('account');

const formData = reactive({ account: '', password: '', confirmPassword: '', user_code: '', captcha: '' });

setUserCode()

// === 滑块验证相关状态 ===
const showCaptchaDialog = ref(false);
const captchaData = reactive({ bg: '', slider: '', y: 0 });
const isSliderVerified = ref(false);
const sliderMoveX = ref(0);
const isDragging = ref(false);
let startX = 0;
const MAX_MOVE = 260;

function setUserCode() {
  if(route.query.invitationCode) {
    localStorage.setItem('vip_invitationCode', route.query.invitationCode);
    formData.user_code = route.query.invitationCode
  } else {
    let vip_invitationCode = localStorage.getItem('vip_invitationCode')
    if(vip_invitationCode) {
      formData.user_code = vip_invitationCode
    }
  }
}

// === 滑块验证相关方法 ===
function initCaptcha() {
  postUserCaptcha().then(res => {
    if (res && res.code === 1) {
      captchaData.bg = res.data.bg;
      captchaData.slider = res.data.slider;
      captchaData.y = res.data.y;
      captchaData.captcha = res.data.captcha

      sliderMoveX.value = 0;
      isSliderVerified.value = false;
    }
  }).catch(err => {
    console.error('验证码接口报错:', err);
  });
}

function onDragStart(e) {
  if (isSliderVerified.value) return;
  isDragging.value = true;
  startX = e.clientX;
  document.addEventListener('mousemove', onDragging);
  document.addEventListener('mouseup', onDragEnd);
}

function onDragging(e) {
  if (!isDragging.value) return;
  let deltaX = e.clientX - startX;
  if (deltaX < 0) deltaX = 0;
  if (deltaX > MAX_MOVE) deltaX = MAX_MOVE;
  sliderMoveX.value = deltaX;
}

function onDragEnd() {
  if (!isDragging.value) return;
  isDragging.value = false;
  document.removeEventListener('mousemove', onDragging);
  document.removeEventListener('mouseup', onDragEnd);

  // 滑动结束后，直接调用注册接口进行校验+注册
  doRegister();
}

onUnmounted(() => {
  document.removeEventListener('mousemove', onDragging);
  document.removeEventListener('mouseup', onDragEnd);
});

// === 业务逻辑 ===
function resetForm() {
  formData.account = '';
  formData.password = '';
  formData.confirmPassword = '';
  formData.user_code = '';
  setUserCode()
}

function onAgreementClick() {
  ElMessageBox.alert(
      `<div style="line-height: 1.6; color: #333; text-align: left;"><h3 style="margin-bottom: 16px;">平台服务协议</h3><p>1. 注册本平台需提供真实有效的身份信息...</p></div>`,
      t('产品服务协议'),
      { dangerouslyUseHTMLString: true, confirmButtonText: t('确定'), customClass: 'agreement-msgbox' }
  );
}

function validateForm() {
  if (!formData.account) {
    ElMessage.warning(activeRegisterType.value === 'email' ? t('请输入邮箱地址') : t('请输入账号'));
    return false;
  }
  if (!formData.password) { ElMessage.warning(t('请输入密码')); return false; }
  if (formData.password.length < 6 || formData.password.length > 20) { ElMessage.warning(t('密码长度需在6-20个字符之间')); return false; }
  if (formData.password !== formData.confirmPassword) { ElMessage.warning(t('两次输入的密码不一致')); return false; }
  return true;
}

function onRegisterClick() {
  if (!agreed.value) return ElMessage.warning(t('请先阅读并同意产品服务协议'));
  if (!validateForm()) return;

  // 表单校验通过，呼出滑块验证弹窗并请求接口获取图片
  showCaptchaDialog.value = true;
  initCaptcha();
}

// 实际发送注册请求的逻辑
function doRegister() {
  postUserRegister({
    account: formData.account,
    password: formData.password,
    user_code: formData.user_code,
    register_type: activeRegisterType.value,
    type: activeRegisterType.value,
    moveX: sliderMoveX.value,
    captcha: captchaData.captcha
  }).then((res) => {
    if(res.data.check_captcha === 0) {
      ElMessage.error(res.msg)
      initCaptcha();
      return
    }

    if (res && res.code === 1) {
      // 接口返回成功，展示滑块成功状态
      isSliderVerified.value = true;
      localStorage.setItem('token', res.data.token);
      ElMessage.success(res.msg)
      setTimeout(() => {
        showCaptchaDialog.value = false;
        router.push('/');
      }, 500);
    } else {
      // 其他失败情况（如账号重复等），正常自动关闭弹窗
      showCaptchaDialog.value = false;
    }
  }).catch((err) => {
    // 接口异常报错时，正常自动关闭弹窗
    showCaptchaDialog.value = false;
  });
}

function onLineService() {
  if(!localStorage.getItem('youke_token')){
    userGuestRegister().then((res) => {
      localStorage.setItem('youke_token', res.data.token);
      router.push({
        name: 'CustomerService',
        query: { GuestMode: 1 }
      });
    })
  } else {
    router.push({
      name: 'CustomerService',
      query: { GuestMode: 1 }
    });
  }
}
</script>

<style scoped lang="scss">
$mclaren-orange: #f8b932;
$btn-orange: #f8b932;
$text-light: rgba(255, 255, 255, 0.8);

.pc-register-container {
  position: relative; min-height: 100vh; width: 100vw;
  background-image: url('@/assets/image/login/bg-login-pc.png');
  background-size: cover;
  background-position: center;
  display: flex; justify-content: center; align-items: center; overflow: hidden;

  .top-left-logo { position: absolute; top: 30px; left: 40px; height: 32px; z-index: 10; }
  .lang-selector-wrapper { position: absolute; top: 24px; right: 32px; z-index: 10; }

  .bg-glow { position: absolute; border-radius: 50%; filter: blur(120px); opacity: 0.1; z-index: 1; }
  .glow-top-left { top: -10%; left: 10%; width: 400px; height: 400px; background-color: $mclaren-orange; }
  .glow-bottom-right { bottom: -10%; right: 10%; width: 300px; height: 300px; background-color: #fff; }

  .register-card {
    min-width: 480px; width: 30%;
    position: relative; z-index: 2; padding: 30px;
    background-color: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(20px);
    border-radius: 24px;
    box-shadow: 0 15px 50px rgba(0, 0, 0, 0.6);
    border: 1px solid rgba(255, 255, 255, 0.2);

    .mclaren-header {
      border-radius: 12px;
      padding: 22px 10px;
      text-align: center;
      margin-bottom: 25px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .mclaren-img-logo { height: 34px; margin-bottom: 2px; }
      .racing-text {
        color: #fff; font-size: 12px; letter-spacing: 7px;
        margin-left: 7px; font-weight: bold; transform: scale(0.8);
      }
      .main-title {
        color: #fff; font-size: 20px; font-weight: 800; letter-spacing: 5px; line-height: 1;
        margin-top: 15px;
      }
      .sub-partner {
        color: rgba(255, 255, 255, 0.85); font-size: 12px;
        letter-spacing: 1px; margin-top: 4px;
      }
    }

    .custom-tabs {
      margin-bottom: 20px;
      :deep(.el-tabs__nav-wrap::after) { display: none; }
      :deep(.el-tabs__active-bar) { display: none; }
      :deep(.el-tabs__nav) { width: 100%; display: flex; gap: 12px; }
      :deep(.el-tabs__item) {
        flex: 1; height: 46px; line-height: 46px; padding: 0 !important;
        color: #ccc; font-size: 15px; text-align: center;
        background: rgba(255, 255, 255, 0.12); border-radius: 8px;
        &.is-active { background: rgba(255, 255, 255, 0.25); color: #fff; font-weight: bold; }
      }
    }

    .form-wrapper { display: flex; flex-direction: column; gap: 12px; }

    .custom-input {
      :deep(.el-input__wrapper) {
        background-color: rgba(255, 255, 255, 0.2);
        box-shadow: none; height: 48px; border-radius: 10px;
        &:hover, &.is-focus { box-shadow: 0 0 0 1px $mclaren-orange inset; }
      }
      :deep(.el-input__inner) { color: #fff; &::placeholder { color: #bbb; } }
      .input-icon { width: 20px; height: 20px; opacity: 0.8; margin-right: 5px; }
    }

    .agreement-row {
      display: flex; align-items: center; justify-content: center;
      font-size: 13px; margin: 20px 0 15px;
      .agreement-link { cursor: pointer; color: #fff; margin-left: 5px; text-decoration: underline; }
    }

    .custom-checkbox {
      :deep(.el-checkbox__label) { color: #bbb; font-size: 13px; }
      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) { background-color: $btn-orange; border-color: $btn-orange; }
      :deep(.el-checkbox__inner) { background-color: rgba(255, 255, 255, 0.1); border-color: rgba(255,255,255,0.4); }
    }

    .submit-btn {
      width: 100%; height: 50px; font-size: 18px; font-weight: bold; color: #fff;
      background-color: $btn-orange; border-color: $btn-orange; border-radius: 10px;
      letter-spacing: 4px; margin-bottom: 20px;
    }

    .bottom-action-group {
      display: flex; justify-content: center; gap: 15px; margin-top: 10px;
      .action-item {
        flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
        background: rgba(255, 255, 255, 0.15); border-radius: 10px; padding: 10px 0; cursor: pointer;
        transition: all 0.3s;
        &:hover { background: rgba(255, 255, 255, 0.25); }
        .action-icon { width: 22px; height: 22px; margin-bottom: 4px; }
        span { font-size: 12px; color: #ddd; }
      }
    }
  }

  /* === 滑块验证及弹窗样式 开始 === */
  :deep(.custom-captcha-dialog) {
    background-color: rgba(40, 40, 40, 0.95);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 16px;

    .el-dialog__title { color: #fff; font-weight: bold; }
    .el-dialog__body { padding-top: 10px; }
    .el-dialog__headerbtn .el-dialog__close { color: #aaa; }
  }

  .captcha-container {
    width: 100%;
    user-select: none;

    .bg-container {
      position: relative;
      width: 300px;
      height: 150px;
      margin: 0 auto 15px auto;
      background: rgba(0, 0, 0, 0.2);
      border-radius: 8px;
      overflow: hidden;

      .bg-img { width: 100%; height: 100%; object-fit: cover; }

      .slider-img {
        position: absolute;
        width: 40px; height: 40px;
        box-shadow: 0 0 5px rgba(255, 255, 255, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.8);
        border-radius: 4px;
      }

      .success-overlay {
        position: absolute; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(2px);
        display: flex; flex-direction: column; align-items: center; justify-content: center;
        color: #67c23a; font-size: 16px; font-weight: bold;
        .success-icon { font-size: 30px; margin-bottom: 8px; }
      }
    }

    .track {
      position: relative; width: 300px; height: 40px; margin: 0 auto;
      background-color: rgba(255, 255, 255, 0.1); border-radius: 20px;
      border: 1px solid rgba(255, 255, 255, 0.2); overflow: hidden;

      .track-bg {
        position: absolute; height: 100%;
        background: rgba($mclaren-orange, 0.3); border-radius: 20px 0 0 20px;
      }

      .drag-btn {
        position: absolute; top: 0; left: 0; width: 40px; height: 40px;
        background: #fff; border-radius: 50%; box-shadow: 0 0 10px rgba(0,0,0,0.3);
        cursor: pointer; display: flex; align-items: center; justify-content: center;
        color: #666; font-size: 18px; transition: background 0.3s; z-index: 2;

        &.is-success { background: #67c23a; color: #fff; cursor: default; }
      }

      .track-text {
        position: absolute; width: 100%; line-height: 40px; text-align: center;
        font-size: 13px; color: #bbb; pointer-events: none;
      }
    }
  }
  /* === 滑块验证及弹窗样式 结束 === */

  :deep(.el-popper) {
    background-color: rgba(40, 40, 40, 0.95) !important;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1) !important;
    .el-select-dropdown__item {
      color: #eee;
      &.is-hovering, &:hover { background-color: rgba(255, 255, 255, 0.1); }
      &.is-selected { color: $mclaren-orange; font-weight: bold; }
    }
  }
}
</style>
