<template>
  <div class="change-password-container">
    <div class="page-header">
      <h1 class="page-title">修改密码</h1>
    </div>

    <div class="password-form card">
      <el-form 
        ref="formRef" 
        :model="passwordForm" 
        :rules="rules" 
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <el-form-item label="当前密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
            maxlength="20"
          />
          <div class="password-tips">
            <p>密码要求：</p>
            <ul>
              <li>长度 8-20 个字符</li>
              <li>至少包含大小写字母、数字中的两种</li>
              <li>不能包含常见的弱密码</li>
            </ul>
          </div>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            maxlength="20"
          />
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit"
            :loading="submitLoading"
            size="large"
          >
            修改密码
          </el-button>
          <el-button @click="handleReset" size="large">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 密码强度指示器 -->
    <div class="password-strength card" v-if="passwordForm.newPassword">
      <h3>密码强度</h3>
      <div class="strength-bar">
        <div 
          class="strength-fill" 
          :class="strengthClass"
          :style="{ width: strengthPercentage + '%' }"
        ></div>
      </div>
      <div class="strength-text">{{ strengthText }}</div>
    </div>

    <!-- 安全提示 -->
    <div class="security-tips card">
      <h3>安全提示</h3>
      <ul>
        <li>定期更换密码，建议每 3-6 个月更换一次</li>
        <li>不要使用与其他网站相同的密码</li>
        <li>不要将密码告诉他人或写在容易被发现的地方</li>
        <li>如发现账号异常，请立即修改密码并联系管理员</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { changePassword } from '@/api/user'

const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const router = useRouter()

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在 8 到 20 个字符', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
})

/**
 * 验证密码强度
 */
function validatePassword(_rule: any, value: string, callback: any) {
  if (!value) {
    callback()
    return
  }
  
  // 检查是否包含至少两种类型的字符
  const hasLower = /[a-z]/.test(value)
  const hasUpper = /[A-Z]/.test(value)
  const hasNumber = /\d/.test(value)
  const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(value)
  
  const typeCount = [hasLower, hasUpper, hasNumber, hasSpecial].filter(Boolean).length
  
  if (typeCount < 2) {
    callback(new Error('密码至少包含大小写字母、数字、特殊字符中的两种'))
    return
  }
  
  // 检查常见弱密码
  const weakPasswords = ['12345678', 'password', 'qwerty', '11111111', '00000000']
  if (weakPasswords.includes(value.toLowerCase())) {
    callback(new Error('不能使用常见的弱密码'))
    return
  }
  
  callback()
}

/**
 * 验证确认密码
 */
function validateConfirmPassword(_rule: any, value: string, callback: any) {
  if (!value) {
    callback()
    return
  }
  
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
    return
  }
  
  callback()
}

/**
 * 密码强度计算
 */
const passwordStrength = computed(() => {
  const password = passwordForm.newPassword
  if (!password) return 0
  
  let score = 0
  
  // 长度分数
  if (password.length >= 8) score += 25
  if (password.length >= 12) score += 25
  
  // 字符类型分数
  if (/[a-z]/.test(password)) score += 10
  if (/[A-Z]/.test(password)) score += 10
  if (/\d/.test(password)) score += 10
  if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) score += 20
  
  return Math.min(score, 100)
})

const strengthPercentage = computed(() => passwordStrength.value)

const strengthClass = computed(() => {
  const strength = passwordStrength.value
  if (strength < 30) return 'weak'
  if (strength < 60) return 'medium'
  if (strength < 80) return 'strong'
  return 'very-strong'
})

const strengthText = computed(() => {
  const strength = passwordStrength.value
  if (strength < 30) return '弱'
  if (strength < 60) return '中等'
  if (strength < 80) return '强'
  return '很强'
})

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      
      try {
        // 调用真实API
        await changePassword({
          old_password: passwordForm.oldPassword,
          new_password: passwordForm.newPassword
        })
        
        ElMessage.success('密码修改成功，请重新登录')
        handleReset()
        
        // 清除token并跳转登录页
        localStorage.removeItem('token')
        router.push('/login')
        
      } catch (error: any) {
        ElMessage.error(error.message || '密码修改失败，请重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

/**
 * 重置表单
 */
const handleReset = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.change-password-container {
  max-width: 600px;
  margin: 0 auto;

  .page-header {
    margin-bottom: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .password-form {
    padding: 32px;
    margin-bottom: 24px;

    .password-tips {
      margin-top: 8px;
      font-size: 12px;
      color: #666;

      p {
        margin: 0 0 4px 0;
        font-weight: 500;
      }

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

        li {
          margin-bottom: 2px;
        }
      }
    }

    .el-button {
      margin-right: 12px;
    }
  }

  .password-strength {
    padding: 24px;
    margin-bottom: 24px;

    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 16px;
    }

    .strength-bar {
      height: 8px;
      background: #f0f0f0;
      border-radius: 4px;
      overflow: hidden;
      margin-bottom: 8px;

      .strength-fill {
        height: 100%;
        transition: width 0.3s, background-color 0.3s;
        border-radius: 4px;

        &.weak {
          background: linear-gradient(90deg, #ff4757, #ff6b7a);
        }

        &.medium {
          background: linear-gradient(90deg, #ffa502, #ff6348);
        }

        &.strong {
          background: linear-gradient(90deg, #2ed573, #7bed9f);
        }

        &.very-strong {
          background: linear-gradient(90deg, #5352ed, #70a1ff);
        }
      }
    }

    .strength-text {
      font-size: 14px;
      font-weight: 500;
      color: #666;
    }
  }

  .security-tips {
    padding: 24px;

    h3 {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 16px;
    }

    ul {
      margin: 0;
      padding-left: 20px;
      color: #666;
      line-height: 1.6;

      li {
        margin-bottom: 8px;
      }
    }
  }
}
</style>