<template>
  <div class="verify-code-page">
    <!-- 顶部标题 -->
    <div class="page-header">
      <div class="header-content">
        <div class="back-btn" @click="goBack">
          <van-icon name="arrow-left" size="20" />
        </div>
        <div class="logo-wrapper">
          <div class="logo-container">
            <!-- <img src="@/assets/images/logo.png" alt="告白语音" class="logo-image" /> -->
          </div>
        </div>
        <div class="header-placeholder"></div>
      </div>
    </div>

    <!-- 验证码输入 -->
    <div class="verify-container">
      <div class="logo">
        <img src="@/assets/images/logo-l.png" alt="告白语音" class="logo-image" />
      </div>
      <div class="verify-card">
        <div class="verify-title">输入验证码</div>

        <div class="phone-info">
          <span class="phone-label">验证码已发送至：</span>
          <span class="phone-number">{{ formatPhone(phoneNumber) }}</span>
        </div>

        <div class="tip-info">
          <span>为确保您本人操作，请输入验证码以验证身份</span>
        </div>

        <!-- 验证码输入框 -->
        <div class="code-input-container">
          <div class="code-inputs">
            <input v-for="(digit, index) in verifyCode" :key="index" :ref="'input' + index" v-model="verifyCode[index]"
              type="tel" maxlength="1" class="code-input" @input="onCodeInput(index, $event)"
              @keydown="onKeyDown(index, $event)" @focus="onInputFocus(index)" />
          </div>
        </div>

        <!-- 重新发送 -->
        <div class="resend-container">
          <div v-if="isCountingDown" class="countdown-text">
            {{ countDown }}s后可重新发送
          </div>
          <div v-else class="resend-btn" @click="resendCode">
            重新发送验证码
          </div>
        </div>

        <!-- 确认按钮 -->
        <div class="confirm-btn-container">
          <van-button type="primary" block round :disabled="!isCodeComplete" @click="confirmVerifyCode"
            class="confirm-btn">
            确认
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { smsCodeLoginAccount } from '@/api/user'

export default {
  name: "VerifyCodePage",
  data() {
    return {
      phoneNumber: "",
      verifyCode: ["", "", "", "", "", ""],
      isCountingDown: true,
      countDown: 60,
      timer: null,
    };
  },
  computed: {
    // 验证码是否输入完整
    isCodeComplete() {
      return this.verifyCode.every((digit) => digit !== "");
    },

    // 完整验证码
    fullVerifyCode() {
      return this.verifyCode.join("");
    },
  },
  created() {
    // 获取手机号
    this.phoneNumber = this.$route.query.phone || "";

    // 开始倒计时
    this.startCountDown();
  },
  beforeDestroy() {
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 格式化手机号显示
    formatPhone(phone) {
      if (!phone) return "";
      return phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3");
    },

    // 验证码输入处理
    onCodeInput(index, event) {
      const value = event.target.value;

      // 只允许数字
      if (!/^\d*$/.test(value)) {
        this.verifyCode[index] = "";
        return;
      }

      this.verifyCode[index] = value;

      // 自动跳转到下一个输入框
      if (value && index < 5) {
        this.$nextTick(() => {
          const nextInput = this.$refs["input" + (index + 1)];
          if (nextInput && nextInput[0]) {
            nextInput[0].focus();
          }
        });
      }

      // 如果输入完整，自动验证
      if (this.isCodeComplete) {
        this.$nextTick(() => {
          this.confirmVerifyCode();
        });
      }
    },

    // 键盘事件处理
    onKeyDown(index, event) {
      // 退格键处理
      if (event.key === "Backspace" && !this.verifyCode[index] && index > 0) {
        const prevInput = this.$refs["input" + (index - 1)];
        if (prevInput && prevInput[0]) {
          prevInput[0].focus();
        }
      }
    },

    // 输入框获得焦点
    onInputFocus(index) {
      // 选中当前输入框的内容
      this.$nextTick(() => {
        const input = this.$refs["input" + index];
        if (input && input[0]) {
          input[0].select();
        }
      });
    },

    // 开始倒计时
    startCountDown() {
      this.isCountingDown = true;
      this.countDown = 60;

      this.timer = setInterval(() => {
        this.countDown--;
        if (this.countDown <= 0) {
          clearInterval(this.timer);
          this.isCountingDown = false;
          this.countDown = 60;
        }
      }, 1000);
    },

    // 重新发送验证码
    async resendCode() {
      try {
        this.$toast.loading({
          message: "发送中...",
          forbidClick: true,
          duration: 0,
        });

        // 这里调用重新发送验证码的API
        // await sendVerifyCode(this.phoneNumber)

        this.$toast.clear();
        this.$toast.success("验证码已重新发送");

        // 重新开始倒计时
        this.startCountDown();

        // 清空验证码输入
        this.verifyCode = ["", "", "", "", "", ""];

        // 聚焦第一个输入框
        this.$nextTick(() => {
          const firstInput = this.$refs["input0"];
          if (firstInput && firstInput[0]) {
            firstInput[0].focus();
          }
        });
      } catch (error) {
        this.$toast.clear();
        this.$toast.fail("发送失败，请重试");
        console.error("重新发送验证码失败:", error);
      }
    },

    // 确认验证码
    async confirmVerifyCode() {
      if (!this.isCodeComplete) {
        this.$toast("请输入完整的验证码");
        return;
      }

      try {
        this.$toast.loading({
          message: "验证中...",
          forbidClick: true,
          duration: 0,
        });

        // 调用短信验证码登录API
        const res = await smsCodeLoginAccount(this.phoneNumber, this.fullVerifyCode)

        this.$toast.clear();
        this.$toast.success("登录成功");

        // 将用户数据存储到localStorage
        if (res.data) {
          localStorage.setItem('userId', res.data.userId)
          localStorage.setItem('userName', res.data.userName)
          localStorage.setItem('avatar', res.data.avatar || '')
          localStorage.setItem('integral', res.data.integral || '0')
          localStorage.setItem('token', res.data.token)
          localStorage.setItem('canExchange', String(res.data.canExchange || 'false'))
        }

        // 验证成功后跳转到充值页面，传递用户信息
        this.$router.replace({
          path: '/recharge',
          query: {
            id: res.data.userId,
            nickname: res.data.userName,
            avatar: res.data.avatar || ''
          }
        });
      } catch (error) {
        this.$toast.clear();
        this.$toast.fail("验证码错误，请重新输入");

        // 清空验证码输入
        this.verifyCode = ["", "", "", "", "", ""];

        // 聚焦第一个输入框
        this.$nextTick(() => {
          const firstInput = this.$refs["input0"];
          if (firstInput && firstInput[0]) {
            firstInput[0].focus();
          }
        });

        console.error("验证码验证失败:", error);
      }
    },
  },
};
</script>

<style scoped>
.verify-code-page {
  min-height: 100vh;
  background-color: var(--background-color);
}

/* 页面头部 */
.page-header {
  padding: 10px 16px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: var(--text-color);
}

.logo-wrapper {
  display: flex;
  justify-content: center;
  flex: 1;
}

.logo-container {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.header-placeholder {
  width: 40px;
}

/* 验证码容器 */
.verify-container {
  padding: 0px 10px 0;
}

/* Logo样式 */
.logo {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0 10px;
}

.logo .logo-image {
  width: 100px;
  /* height: 60px; */
  object-fit: contain;

  transition: transform 0.3s ease;
}

.logo .logo-image:hover {
  transform: scale(1.05);
}

.verify-card {
  background: var(--card-background);
  border-radius: 16px;
  padding: 32px 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

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

/* 手机号信息 */
.phone-info {
  text-align: left;
  margin-bottom: 4px;
}

.phone-label {
  font-size: 14px;
  color: var(--text-lighter-color);
}

.phone-number {
  font-size: 16px;
  color: var(--text-color);
  font-weight: 500;
}

.tip-info {
  margin-bottom: 30px;
}

.tip-info span {
  font-size: 14px;
  color: var(--text-lighter-color);
}

/* 验证码输入 */
.code-input-container {
  margin-bottom: 32px;
}

.code-inputs {
  display: flex;
  justify-content: space-between;
  /* gap: 10px; */
}

.code-input {
  width: 46px;
  height: 46px;
  border: 2px solid var(--border-color);
  border-radius: 8px;
  text-align: center;
  font-size: 24px;
  font-weight: 600;
  color: var(--text-color);
  background: var(--card-background);
  outline: none;
  transition: all 0.3s;
}

.code-input:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(182, 111, 255, 0.1);
}

.code-input:not(:placeholder-shown) {
  border-color: var(--primary-color);
}

/* 重新发送 */
.resend-container {
  text-align: center;
  margin-bottom: 32px;
}

.countdown-text {
  font-size: 14px;
  color: var(--text-lighter-color);
}

.resend-btn {
  font-size: 14px;
  color: var(--primary-color);
  cursor: pointer;
  text-decoration: underline;
}

.resend-btn:hover {
  opacity: 0.8;
}

/* 确认按钮 */
.confirm-btn-container {
  margin-bottom: 16px;
}

.confirm-btn {
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: var(--primary-color);
  border: none;
}

.confirm-btn:disabled {
  background: var(--text-lighter-color);
  opacity: 0.6;
}

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

  .logo {
    margin-bottom: 24px;
    padding: 16px 0;
  }

  .logo .logo-image {
    width: 100px;
    height: 50px;
  }

  .verify-card {
    padding: 24px 16px;
    border-radius: 12px;
  }

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

  .code-inputs {
    gap: 6px;
  }

  .code-input {
    width: 38px;
    height: 48px;
    font-size: 18px;
  }

  .confirm-btn {
    height: 44px;
    font-size: 15px;
  }
}
</style>
