<template>
  <div class="reset-password-page-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h1 class="main-title">找回密码</h1>
        <p class="subtitle">重置您的登录密码</p>
      </div>
    </div>

    <!-- 找回密码表单 -->
    <div class="reset-password-form-container">
      <form @submit.prevent="handleResetPassword" class="reset-password-form">
        <!-- 手机号 -->
        <div class="form-group">
          <el-input
            v-model="formData.phone"
            type="tel"
            placeholder="请输入手机号"
            prefix-icon="Iphone"
            size="large"
            maxlength="11"
            @input="validatePhoneInput"
            @blur="validatePhoneOnBlur"
            clearable
          />
          <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">
          <el-input
            v-model="formData.code"
            placeholder="请输入验证码"
            prefix-icon="Key"
            size="large"
            maxlength="6"
          >
            <template #append>
              <el-button
                type="primary"
                :disabled="codeBtnDisabled"
                @click="sendVerificationCode"
              >
                {{ codeButtonText }}
              </el-button>
            </template>
          </el-input>
          <div v-if="errors.code" class="error-text">{{ errors.code }}</div>
        </div>

        <!-- 新密码 -->
        <div class="form-group">
          <el-input
            v-model="formData.newPassword"
            placeholder="请输入新密码"
            prefix-icon="Lock"
            size="large"
            :type="showNewPassword ? 'text' : 'password'"
            :show-password="true"
            autocomplete="new-password"
          />
          <div v-if="errors.newPassword" class="error-text">{{ errors.newPassword }}</div>
        </div>

        <!-- 确认新密码 -->
        <div class="form-group">
          <el-input
            v-model="formData.confirmPassword"
            placeholder="请再次输入新密码"
            prefix-icon="Lock"
            size="large"
            :type="showConfirmPassword ? 'text' : 'password'"
            :show-password="true"
            autocomplete="new-password"
          />
          <div v-if="errors.confirmPassword" class="error-text">{{ errors.confirmPassword }}</div>
        </div>

        <!-- 重置密码按钮 -->
        <el-button
          type="primary"
          native-type="submit"
          :loading="loading"
          class="reset-password-btn"
          size="large"
        >
          {{ loading ? '重置中...' : '重置密码' }}
        </el-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'
import { ElInput, ElButton } from 'element-plus'
import { Lock, Iphone, Key } from '@element-plus/icons-vue'

export default {
  name: 'ResetPassword',
  components: {
    ElInput,
    ElButton,
    Lock,
    Iphone,
    Key
  },
  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: #f0f2f5;
  padding: 20px 20px 8px 20px;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #ff6b6b, #ee5a52);
  color: white;
  padding: 35px 20px 25px;
  text-align: center;
  position: relative;
  margin-bottom: 15px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(238, 90, 82, 0.3);
}

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

.main-title {
  font-size: 32px;
  margin: 0 auto 4px;
  font-weight: 700;
  color: white;
  text-shadow: 0 2px 8px rgba(0,0,0,0.5), 0 0 20px rgba(0,0,0,0.3);
  letter-spacing: 1px;
  text-align: center;
  width: 100%;
}

.subtitle {
  font-size: 16px;
  margin: 0;
  color: white;
  opacity: 0.95;
  text-shadow: 0 2px 4px rgba(0,0,0,0.4);
  text-align: center;
  width: 100%;
  font-weight: 400;
}

.reset-password-form-container {
  padding: 0;
  background: white;
  margin: 0 0 20px 0;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.reset-password-form {
  background: white;
  border-radius: 0;
  padding: 32px 24px 24px;
  box-shadow: none;
}

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

/* Element UI 组件自定义样式 */
:deep(.el-input__wrapper) {
  padding: 6px 16px;
  box-shadow: none !important;
  background-color: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  transition: all 0.3s ease;
}

/* 带有 append 按钮的输入框样式优化 */
:deep(.el-input-group .el-input__wrapper) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
}

:deep(.el-input-group__append) {
  border-top-right-radius: 12px;
  border-bottom-right-radius: 12px;
  padding: 0;
  border: none;
  background: transparent;
}

:deep(.el-input__wrapper.is-focus) {
  background-color: #fff;
  border-color: #e53e3e;
  box-shadow: 0 0 0 4px rgba(229, 62, 62, 0.1);
}

/* 带有 append 按钮的输入框聚焦时的样式 */
:deep(.el-input-group .el-input__wrapper.is-focus) {
  border-color: #e53e3e;
  box-shadow: 0 0 0 4px rgba(229, 62, 62, 0.1);
}

:deep(.el-input-group.is-focus .el-input-group__append .el-button) {
  border-color: #e53e3e;
  box-shadow: 0 0 0 4px rgba(229, 62, 62, 0.1);
}

:deep(.el-input__prefix) {
  margin-right: 12px;
  color: #999;
}

:deep(.el-input__inner) {
  height: 44px;
  font-size: 15px;
  color: #333;
}

:deep(.el-input-group__append .el-button) {
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  border: 2px solid #e53e3e;
  border-left: none;
  margin: 0;
  height: 100%;
  border-radius: 0 12px 12px 0;
  padding: 0 16px;
  font-size: 13px;
  font-weight: 500;
  color: white;
  min-width: 100px;
  box-shadow: none;
  transition: all 0.3s ease;
}

:deep(.el-input-group__append .el-button:hover) {
  background: linear-gradient(135deg, #d43030, #ff5a5a);
  border-color: #d43030;
  color: white;
  transform: none;
}

:deep(.el-input-group__append .el-button.is-disabled) {
  background: #cccccc;
  border-color: #cccccc;
  color: #888;
  transform: none;
}

/* 提示文本 */
.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;
}

/* 重置密码按钮 */
.reset-password-btn {
  width: 100%;
  margin: 32px 0 28px 0;
  padding: 14px;
  font-size: 16px;
  font-weight: 600;
  height: 52px;
  background: linear-gradient(135deg, #e53e3e, #ff6b6b);
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(229, 62, 62, 0.25);
  transition: all 0.3s ease;
}

.reset-password-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 6px 30px rgba(229, 62, 62, 0.35);
  background: linear-gradient(135deg, #d43030, #ff5a5a);
  border: none;
}

.reset-password-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 10px rgba(229, 62, 62, 0.3);
}

:deep(.el-button.is-disabled) {
  background: #cccccc;
  border-color: #cccccc;
}

/* 返回登录链接 */
.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 (min-width: 1024px) {
  .page-header {
    padding: 30px 20px 25px;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reset-password-page-container {
    padding: 10px 10px 5px 10px;
  }
  
  .reset-password-form {
    padding: 25px 20px;
  }
  
  :deep(.el-input-group__append .el-button) {
    font-size: 12px;
    min-width: 90px;
    padding: 0 10px;
  }
}

@media (max-width: 480px) {
  .reset-password-page-container {
    padding: 5px 5px 3px 5px;
  }
  
  .page-header {
    padding: 30px 20px 25px;
    margin-bottom: 12px;
  }
  
  .page-title {
    margin: 0;
  }
  
  .main-title {
    font-size: 28px;
    margin-bottom: 3px;
    letter-spacing: 0.5px;
  }
  
  .subtitle {
    font-size: 14px;
  }
  
  .reset-password-form {
    padding: 28px 20px 20px;
  }
  
  :deep(.el-input__inner) {
    height: 42px;
    font-size: 14px;
  }
  
  .reset-password-btn {
    height: 48px;
    font-size: 15px;
    margin: 28px 0 24px 0;
  }
  
  :deep(.el-input-group__append .el-button) {
    font-size: 12px;
    min-width: 90px;
    padding: 0 12px;
  }
}
</style>