<template>
  <div class="reset-password-page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h1>找回密码</h1>
      </div>
    </div>

    <!-- 找回密码表单 -->
    <div class="reset-password-form-container">
      <form @submit.prevent="handleResetPassword" class="reset-password-form">
        <!-- 手机号 -->
        <div class="form-group">
          <div class="input-wrapper" :class="{ error: errors.phone }">
            <div class="input-icon">
              <img src="@/assets/icon/login/shouji.png" alt="手机号" class="icon-img" />
            </div>
            <input
              v-model="formData.phone"
              type="tel"
              class="form-input"
              placeholder="请输入手机号"
              maxlength="11"
              @input="validatePhoneInput"
              @blur="validatePhoneOnBlur"
            />
          </div>
          <div v-if="errors.phone" class="error-text">{{ errors.phone }}</div>
          <div v-else-if="formData.phone && formData.phone.length > 0 && formData.phone.length < 11" class="tip-text">请输入11位手机号码</div>
        </div>

        <!-- 验证码 -->
        <div class="form-group">
          <div class="input-wrapper code-input-wrapper" :class="{ error: errors.code }">
            <div class="input-icon">
              <img src="@/assets/icon/login/mima.png" alt="验证码" class="icon-img" />
            </div>
            <input
              v-model="formData.code"
              type="text"
              class="form-input"
              placeholder="请输入验证码"
            />
            <button
              type="button"
              class="send-code-btn"
              @click="sendVerificationCode"
              :disabled="codeBtnDisabled"
            >
              {{ codeButtonText }}
            </button>
          </div>
          <div v-if="errors.code" class="error-text">{{ errors.code }}</div>
        </div>

        <!-- 新密码 -->
        <div class="form-group">
          <div class="input-wrapper" :class="{ error: errors.newPassword }">
            <div class="input-icon">
              <img src="@/assets/icon/login/mima.png" alt="新密码" class="icon-img" />
            </div>
            <input
              v-model="formData.newPassword"
              :type="showNewPassword ? 'text' : 'password'"
              class="form-input"
              placeholder="请输入新密码"
              autocomplete="new-password"
            />
            <div class="password-toggle" @click="showNewPassword = !showNewPassword">
              <img
                v-if="showNewPassword"
                src="@/assets/icon/login/zhanshi.png"
                alt="隐藏密码"
                class="toggle-icon-img"
              />
              <img
                v-else
                src="@/assets/icon/login/yingcang.png"
                alt="显示密码"
                class="toggle-icon-img"
              />
            </div>
          </div>
          <div v-if="errors.newPassword" class="error-text">{{ errors.newPassword }}</div>
        </div>

        <!-- 确认新密码 -->
        <div class="form-group">
          <div class="input-wrapper" :class="{ error: errors.confirmPassword }">
            <div class="input-icon">
              <img src="@/assets/icon/login/mima.png" alt="确认新密码" class="icon-img" />
            </div>
            <input
              v-model="formData.confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              class="form-input"
              placeholder="请再次输入新密码"
              autocomplete="new-password"
            />
            <div class="password-toggle" @click="showConfirmPassword = !showConfirmPassword">
              <img
                v-if="showConfirmPassword"
                src="@/assets/icon/login/zhanshi.png"
                alt="隐藏密码"
                class="toggle-icon-img"
              />
              <img
                v-else
                src="@/assets/icon/login/yingcang.png"
                alt="显示密码"
                class="toggle-icon-img"
              />
            </div>
          </div>
          <div v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</div>
        </div>

        <!-- 重置密码按钮 -->
        <button
          type="submit"
          class="reset-password-btn"
          :disabled="loading"
        >
          {{ loading ? '重置中...' : '重置密码' }}
        </button>

        <!-- 返回登录链接 -->
        <div class="login-link">
          <span><router-link to="/login" class="link">返回登录</router-link></span>
        </div>
      </form>
    </div>

    <!-- 成功/错误弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" :class="{ 'success-modal': isSuccess, 'error-modal': !isSuccess }" @click.stop>
        <div v-if="!isSuccess" class="error-icon">❌</div>
        <h3>{{ modalTitle }}</h3>
        <p>{{ modalMessage }}</p>
        <button class="modal-btn" :class="{ 'error-btn': !isSuccess }" @click="closeModal">确定</button>
      </div>
    </div>
  </div>
</template>

<script>
import { lotteryApi } from '../api/index.js'
import { useToast } from 'vue-toastification'
import { useRouter } from 'vue-router'

export default {
  name: 'ResetPassword',
  setup() {
    const toast = useToast()
    const router = useRouter()
    return { toast, router }
  },
  data() {
    return {
      loading: false,
      showNewPassword: false,
      showConfirmPassword: false,
      codeCountdown: 0,
      timer: null,
      phoneValid: false,
      showModal: false,
      isSuccess: false,
      modalTitle: '',
      modalMessage: '',

      formData: {
        phone: '',
        code: '',
        newPassword: '',
        confirmPassword: '',
      },

      errors: {}
    }
  },
  computed: {
    codeButtonText() {
      return this.codeCountdown > 0 ? `${this.codeCountdown}秒后重试` : '获取验证码';
    },
    codeBtnDisabled() {
      return this.codeCountdown > 0 || !this.isValidPhone(this.formData.phone);
    }
  },
  methods: {
    // 手机号格式验证
    isValidPhone(phone) {
      return /^1[3-9]\d{9}$/.test(phone);
    },

    // 手机号输入时验证
    validatePhoneInput() {
      this.errors.phone = '';
      this.phoneValid = false;

      const phone = this.formData.phone;

      if (!/^\d*$/.test(phone)) {
        this.formData.phone = phone.replace(/\D/g, '');
      }

      if (phone.length === 11) {
        if (this.isValidPhone(phone)) {
          this.phoneValid = true;
        } else {
          this.errors.phone = '手机号格式不正确';
        }
      }
    },

    // 手机号失焦时验证
    validatePhoneOnBlur() {
      const phone = this.formData.phone;

      if (phone && phone.length > 0) {
        if (phone.length !== 11) {
          this.errors.phone = '手机号应为11位数字';
          this.phoneValid = false;
        } else if (!this.isValidPhone(phone)) {
          this.errors.phone = '请输入正确的手机号码';
          this.phoneValid = false;
        } else {
          this.phoneValid = true;
        }
      }
    },

    // 发送验证码
    async sendVerificationCode() {
      if (!this.formData.phone) {
        this.errors.phone = '请输入手机号';
        return;
      }

      if (!this.isValidPhone(this.formData.phone)) {
        this.errors.phone = '请输入正确的手机号码';
        return;
      }

      this.phoneValid = true;

      try {
        this.codeCountdown = 60;
        this.startCodeCountdown();

        const response = await lotteryApi.sendSmsCode(this.formData.phone);

        if (response.success) {
          this.toast.success('验证码已发送，请注意查收');
        } else {
          this.codeCountdown = 0;
          clearInterval(this.timer);
          this.toast.error(response.message || '发送验证码失败，请稍后重试');
        }
      } catch (error) {
        this.codeCountdown = 0;
        clearInterval(this.timer);
        console.error('发送验证码失败:', error);
        this.toast.error('发送验证码失败，请稍后重试');
      }
    },

    // 开始倒计时
    startCodeCountdown() {
      if (this.timer) {
        clearInterval(this.timer);
      }

      this.timer = setInterval(() => {
        if (this.codeCountdown > 0) {
          this.codeCountdown--;
        } else {
          clearInterval(this.timer);
          this.timer = null;
        }
      }, 1000);
    },

    // 表单验证
    validateForm() {
      this.errors = {};

      if (!this.formData.phone) {
        this.errors.phone = '请输入手机号';
      } else if (!this.isValidPhone(this.formData.phone)) {
        this.errors.phone = '请输入正确的手机号码';
      }

      if (!this.formData.code) {
        this.errors.code = '请输入验证码';
      } else if (this.formData.code.length !== 6 && this.formData.code.length !== 4) {
        this.errors.code = '验证码格式不正确';
      }

      if (!this.formData.newPassword) {
        this.errors.newPassword = '请输入新密码';
      } else if (this.formData.newPassword.length < 6 || this.formData.newPassword.length > 20) {
        this.errors.newPassword = '密码长度在 6 到 20 个字符';
      }

      if (!this.formData.confirmPassword) {
        this.errors.confirmPassword = '请再次输入新密码';
      } else if (this.formData.newPassword !== this.formData.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致';
      }

      return Object.keys(this.errors).length === 0;
    },

    // 处理重置密码
    async handleResetPassword() {
      if (!this.validateForm()) {
        return;
      }

      this.loading = true;

      try {
        const response = await lotteryApi.resetPassword(
          this.formData.phone,
          this.formData.code,
          this.formData.newPassword,
          this.formData.confirmPassword
        );

        if (response.success === true) {
          this.showModal = true;
          this.isSuccess = true;
          this.modalTitle = '密码重置成功';
          this.modalMessage = '您的密码已成功重置，请返回登录页面。';
          // 重置表单
          this.formData.phone = '';
          this.formData.code = '';
          this.formData.newPassword = '';
          this.formData.confirmPassword = '';
          this.errors = {};
        } else {
          this.showModal = true;
          this.isSuccess = false;
          this.modalTitle = '密码重置失败';
          this.modalMessage = response.message || '重置密码失败，请重试。';
        }
      } catch (error) {
        console.error('重置密码失败:', error);
        this.showModal = true;
        this.isSuccess = false;
        this.modalTitle = '操作失败';
        this.modalMessage = error.response?.data?.message || '网络错误或服务器异常，请稍后重试。';
      } finally {
        this.loading = false;
      }
    },

    // 关闭弹窗
    closeModal() {
      this.showModal = false;
      if (this.isSuccess) {
        this.router.push('/login');
      }
      this.modalTitle = '';
      this.modalMessage = '';
    }
  },
  // 组件销毁时清除定时器
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }
}
</script>

<style scoped>
/* 页面容器 */
.reset-password-page-container {
  min-height: calc(100vh - 70px);
  background: #f8f9fa;
  padding: 0;
}

/* 页面头部 */
.page-header {
  background: url('@/assets/banner/backend1.png') center/cover no-repeat, linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  padding: 50px 20px 40px;
  text-align: center;
  position: relative;
}

.page-title {
  margin: 0 0 8px 0;
  text-align: center;
}

.page-title h1 {
  font-size: 36px;
  margin: 0;
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}

.reset-password-form-container {
  padding: 0;
  background: white;
  margin: 0 20px;
}

.reset-password-form {
  background: white;
  border-radius: 0;
  padding: 30px 25px;
  box-shadow: none;
  min-height: calc(100vh - 320px);
}

/* 表单组 */
.form-group {
  margin-bottom: 24px;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  background: #f8f9fa;
  transition: all 0.3s ease;
  min-height: 56px;
  overflow: hidden;
}

.input-wrapper:focus-within {
  border-color: #e9ecef;
  background: white;
  box-shadow: none;
  outline: none;
}

input:focus {
  outline: none;
  box-shadow: none;
}

.input-wrapper.error {
  border-color: #dc3545;
  background: #fff5f5;
}

.input-wrapper.success {
  border-color: #4caf50;
  background: #f8fff8;
}

.input-icon {
  padding: 12px 25px;
  color: #6c757d;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
}

.icon-img {
  width: 22px;
  height: 22px;
  object-fit: contain;
}

.form-input {
  flex: 1;
  padding: 16px 8px;
  border: none;
  outline: none;
  font-size: 16px;
  background: transparent;
  color: #212529;
  box-shadow: none;
  -webkit-appearance: none;
}

.form-input:focus {
  outline: none;
  border: none;
  box-shadow: none;
}

/* 控制浏览器自动填充的样式 */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
  -webkit-box-shadow: 0 0 0 30px white inset !important;
  -webkit-text-fill-color: #212529 !important;
  transition: background-color 5000s ease-in-out 0s;
  border: none !important;
  outline: none !important;
}

/* 发送验证码按钮 */
.send-code-btn {
  height: 32px;
  margin-right: 5px;
  padding: 0 10px;
  border: none;
  color: white;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  border-radius: 4px;
  white-space: nowrap;
  min-width: 85px;
  transition: all 0.3s;
  background: #e53e3e;
  align-self: center;
}

.code-input-wrapper {
  padding-right: 5px;
  border: 2px solid #e9ecef;
  border-radius: 6px;
  overflow: hidden;
}

.code-input-wrapper:focus-within {
  border-color: #e9ecef;
  box-shadow: none;
}

.send-code-btn:disabled {
  background: #cccccc;
  cursor: not-allowed;
}

.send-code-btn:hover:not(:disabled) {
  background: #d43030;
}

/* 提示文本 */
.error-text {
  color: #ff4444;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 8px;
}

.tip-text {
  color: #888888;
  font-size: 12px;
  margin-top: 5px;
  margin-left: 8px;
}

/* 隐藏浏览器自带的密码控件 */
input::-ms-reveal,
input::-ms-clear {
  display: none;
}

input::-webkit-credentials-auto-fill-button {
  visibility: hidden;
  position: absolute;
  right: 0;
}

.form-input::placeholder {
  color: #9ca3af;
}

.password-toggle {
  padding: 0 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toggle-icon-img {
  width: 22px;
  height: 22px;
  object-fit: contain;
}

/* 重置密码按钮 */
.reset-password-btn {
  width: 100%;
  padding: 18px;
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 30px 0 25px 0;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(229, 62, 62, 0.3);
}

.reset-password-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.5s;
}

.reset-password-btn:hover:not(:disabled)::before {
  left: 100%;
}

.reset-password-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(229, 62, 62, 0.4);
}

.reset-password-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
  box-shadow: 0 4px 15px rgba(229, 62, 62, 0.2);
}

/* 返回登录链接 */
.login-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.login-link .link {
  color: #e53e3e;
  text-decoration: none;
  margin-left: 0px;
}

.login-link .link:hover {
  text-decoration: underline;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 20px;
  padding: 40px 30px;
  text-align: center;
  max-width: 350px;
  width: 100%;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-30px) scale(0.9);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.success-modal h3 {
  margin-bottom: 15px;
  color: #4caf50;
  font-size: 22px;
  font-weight: bold;
}

.success-modal p {
  margin-bottom: 25px;
  color: #666;
  line-height: 1.5;
  font-size: 16px;
}

.modal-btn {
  background: linear-gradient(135deg, #4caf50, #66bb6a);
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 120px;
}

.modal-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(76, 175, 80, 0.3);
}

.modal-btn:active {
  transform: translateY(0);
}

.error-icon {
  font-size: 48px;
  margin-bottom: 20px;
  animation: shake 0.6s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
  20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.error-modal h3 {
  margin-bottom: 15px;
  color: #f44336;
  font-size: 22px;
  font-weight: bold;
}

.error-modal p {
  margin-bottom: 25px;
  color: #666;
  line-height: 1.5;
  font-size: 16px;
}

.error-btn {
  background: linear-gradient(135deg, #f44336, #e57373) !important;
}

.error-btn:hover {
  box-shadow: 0 8px 25px rgba(244, 67, 54, 0.3) !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    padding: 45px 15px 35px;
  }

  .page-title {
    margin: 0 0 8px 0;
  }

  .page-title h1 {
    font-size: 30px;
  }

  .reset-password-form {
    padding: 25px 20px;
  }

  .send-code-btn {
    font-size: 12px;
    min-width: 90px;
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .page-header {
    padding: 40px 12px 30px;
  }

  .page-title {
    margin: 0 0 6px 0;
  }

  .page-title h1 {
    font-size: 26px;
  }

  .reset-password-form {
    padding: 20px 15px;
  }

  .input-icon {
    padding: 12px 25px;
  }

  .icon-img {
    width: 22px;
    height: 22px;
  }

  .toggle-icon-img {
    width: 20px;
    height: 20px;
  }

  .password-toggle {
    padding: 0 12px;
  }

  .send-code-btn {
    font-size: 12px;
    min-width: 85px;
    padding: 0 8px;
  }
}

/* 桌面端样式 */
@media (min-width: 1024px) {
  .page-header {
    padding: 45px 20px 35px;
  }

  .page-title h1 {
    font-size: 40px;
  }

  .page-subtitle {
    font-size: 14px;
  }

  .send-code-btn {
    height: 40px;
    font-size: 14px;
    min-width: 120px;
    padding: 0 15px;
  }
}
</style> 