<template>
  <div class="change-password-container">
    <el-card class="change-password-card" shadow="always">
      <!-- 头部 -->
      <div class="change-password-header">
        <el-icon class="header-icon" size="48"><Lock /></el-icon>
        <h1 class="title">修改密码</h1>
        <p class="subtitle">为了您的账户安全，请定期更换密码</p>
      </div>

      <!-- 修改密码表单 -->
      <el-form
        ref="changePasswordFormRef"
        :model="changePasswordForm"
        :rules="changePasswordRules"
        class="change-password-form"
        label-position="top"
      >
        <!-- 当前密码 -->
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="changePasswordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            size="large"
            show-password
            clearable
            :prefix-icon="Lock"
          />
        </el-form-item>

        <!-- 新密码 -->
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="changePasswordForm.newPassword"
            type="password"
            placeholder="8-20位字符，必须包含字母和数字"
            size="large"
            show-password
            clearable
            :prefix-icon="Lock"
            @input="handlePasswordChange"
          />
          <!-- 密码强度指示器 -->
          <div class="password-strength" v-if="changePasswordForm.newPassword">
            <div class="strength-label">密码强度：</div>
            <div class="strength-indicator">
              <div
                class="strength-bar"
                :class="{
                  weak: passwordStrength === 'weak',
                  medium: passwordStrength === 'medium',
                  strong: passwordStrength === 'strong',
                }"
              ></div>
              <span class="strength-text">{{ getStrengthText() }}</span>
            </div>
          </div>
        </el-form-item>

        <!-- 确认新密码 -->
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            size="large"
            show-password
            clearable
            :prefix-icon="Lock"
          />
        </el-form-item>

        <!-- 安全提示 -->
        <el-alert title="安全提示" type="info" :closable="false" show-icon class="security-tips">
          <template #default>
            <ul>
              <li>密码长度应为8-20个字符</li>
              <li>必须同时包含字母和数字</li>
              <li>建议包含特殊字符以提高安全性</li>
              <li>不要使用过于简单的密码</li>
            </ul>
          </template>
        </el-alert>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button size="large" @click="handleCancel">取消</el-button>
          <el-button
            type="primary"
            size="large"
            :loading="changePasswordLoading"
            @click="handleChangePassword"
          >
            {{ changePasswordLoading ? '修改中...' : '确认修改' }}
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const changePasswordFormRef = ref<FormInstance>()
const changePasswordLoading = ref(false)
const passwordStrength = ref<'weak' | 'medium' | 'strong'>('weak')

// 修改密码表单数据
const changePasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 自定义验证函数
const validateNewPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入新密码'))
  } else if (value === changePasswordForm.oldPassword) {
    callback(new Error('新密码不能与当前密码相同'))
  } else if (value.length < 8 || value.length > 20) {
    callback(new Error('密码长度必须在8-20个字符之间'))
  } else if (!/^(?=.*[a-zA-Z])(?=.*\d).*$/.test(value)) {
    callback(new Error('密码必须同时包含字母和数字'))
  } else {
    callback()
  }
}

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请确认新密码'))
  } else if (value !== changePasswordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const changePasswordRules: FormRules = {
  oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }],
  newPassword: [{ required: true, validator: validateNewPassword, trigger: 'blur' }],
  confirmPassword: [{ required: true, validator: validateConfirmPassword, trigger: 'blur' }],
}

// 密码强度检测
const checkPasswordStrength = (password: string): 'weak' | 'medium' | 'strong' => {
  if (!password) return 'weak'

  let score = 0

  // 长度检查
  if (password.length >= 8) score += 1
  if (password.length >= 12) score += 1

  // 字符类型检查
  if (/[a-z]/.test(password)) score += 1
  if (/[A-Z]/.test(password)) score += 1
  if (/\d/.test(password)) score += 1
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) score += 1

  if (score <= 2) return 'weak'
  if (score <= 4) return 'medium'
  return 'strong'
}

// 密码强度文本
const getStrengthText = () => {
  switch (passwordStrength.value) {
    case 'weak':
      return '弱'
    case 'medium':
      return '中'
    case 'strong':
      return '强'
    default:
      return '弱'
  }
}

// 处理密码变化
const handlePasswordChange = () => {
  passwordStrength.value = checkPasswordStrength(changePasswordForm.newPassword)
}

// 处理修改密码
const handleChangePassword = async () => {
  if (!changePasswordFormRef.value) return

  try {
    // 表单验证
    await changePasswordFormRef.value.validate()

    changePasswordLoading.value = true

    // 调用修改密码API
    const result = await authStore.changePassword({
      oldPassword: changePasswordForm.oldPassword,
      newPassword: changePasswordForm.newPassword,
      confirmPassword: changePasswordForm.confirmPassword,
    })

    if (result.success) {
      ElMessage.success(result.message)

      // 提示用户重新登录
      ElMessageBox.confirm('密码修改成功！为了账户安全，需要重新登录。', '密码修改成功', {
        confirmButtonText: '重新登录',
        cancelButtonText: '稍后登录',
        type: 'success',
      })
        .then(() => {
          // 清除认证信息并跳转登录
          authStore.logout()
          router.push('/login')
        })
        .catch(() => {
          // 用户选择稍后登录，返回上一页
          router.back()
        })
    } else {
      ElMessage.error(result.message)
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    changePasswordLoading.value = false
  }
}

// 取消修改
const handleCancel = () => {
  ElMessageBox.confirm('确定要取消修改密码吗？', '确认取消', {
    confirmButtonText: '确定',
    cancelButtonText: '继续修改',
    type: 'warning',
  })
    .then(() => {
      router.back()
    })
    .catch(() => {
      // 用户选择继续修改
    })
}
</script>

<style scoped lang="scss">
.change-password-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.change-password-card {
  width: 100%;
  max-width: 500px;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}

.change-password-header {
  text-align: center;
  margin-bottom: 30px;

  .header-icon {
    color: #409eff;
    margin-bottom: 15px;
  }

  .title {
    margin: 0 0 8px 0;
    font-size: 24px;
    font-weight: 600;
    color: #2c3e50;
  }

  .subtitle {
    margin: 0;
    color: #7f8c8d;
    font-size: 14px;
  }
}

.change-password-form {
  .el-form-item {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      font-weight: 500;
      color: #2c3e50;
      margin-bottom: 5px;
    }
  }

  .password-strength {
    margin-top: 8px;
    display: flex;
    align-items: center;
    font-size: 12px;

    .strength-label {
      color: #666;
      margin-right: 8px;
    }

    .strength-indicator {
      display: flex;
      align-items: center;

      .strength-bar {
        width: 60px;
        height: 4px;
        border-radius: 2px;
        margin-right: 8px;
        background: #e0e0e0;
        position: relative;
        overflow: hidden;

        &::after {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          height: 100%;
          border-radius: 2px;
          transition: all 0.3s ease;
        }

        &.weak::after {
          width: 33%;
          background: #f56c6c;
        }

        &.medium::after {
          width: 66%;
          background: #e6a23c;
        }

        &.strong::after {
          width: 100%;
          background: #67c23a;
        }
      }

      .strength-text {
        font-weight: 500;

        &.weak {
          color: #f56c6c;
        }
        &.medium {
          color: #e6a23c;
        }
        &.strong {
          color: #67c23a;
        }
      }
    }
  }

  .security-tips {
    margin-bottom: 25px;

    ul {
      margin: 0;
      padding-left: 16px;

      li {
        margin-bottom: 4px;
        font-size: 13px;
        color: #666;
      }
    }
  }

  .form-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;

    .el-button {
      min-width: 100px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .change-password-card {
    margin: 20px;
    padding: 16px;
  }

  .change-password-header .title {
    font-size: 20px;
  }

  .form-actions {
    flex-direction: column-reverse;

    .el-button {
      width: 100%;
    }
  }
}
</style>
