

<script setup>
import {ref, reactive, computed, watch, onMounted} from 'vue'
import {CircleCloseFilled, SuccessFilled} from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";
import API from '@/util/http.js'
import PasswordSuccess from '../PasswordSuccess.vue';
import router from "@/router/index.js";

// 父组件调用
const emit = defineEmits(['confirm'])

const passwdFormRef = ref(null)
const passwd = reactive({
  account: '',
  oldPassword: '',
  newPassword: '',
  againPassword: ''
})
const errorMsg = ref('')
//获取用户信息的account
const getAccount= async function() {
  try {
    const adminData = ref({})
    const result = await API({ url: '/admin/userinfo', data: {} })
    adminData.value = result
    console.log('管理员用户信息', adminData.value)
    passwd.account = adminData.value.account
  } catch (error) {
    console.log('请求失败', error)
  }
}
// 实时密码规则校验
const isLengthValid = computed(() =>
  /^[A-Za-z0-9~!@#$%^&*()_+\-=[\]{}|;:,.<>?/]{8,16}$/.test(passwd.newPassword)
);

const isComplexValid = computed(() => {
  const rules = [/\d/, /[a-z]/, /[A-Z]/, /[^a-zA-Z0-9]/]
  return rules.filter((r) => r.test(passwd.newPassword)).length >= 2
})

watch(() => passwd.newPassword, (val) => {
  if (val && val === passwd.oldPassword) {
    errorMsg.value = '新密码不能与旧密码一致'
  } else {
    errorMsg.value = ''
  }
})
// 提交加载状态
const loading = ref(false)
// 表单校验规则
const rules = reactive({
  oldPassword: [{required: true, message: '请输入原密码', trigger: 'blur'}],
  newPassword: [
    {required: true, message: '新密码不能为空', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (!/^[a-zA-Z0-9!@#$%^&*()-_+={}[\]|\\:;"'<>,.?/~\`]+$/.test(value)) {
          callback(new Error('密码只能包含数字、字母或符号'));
        }  else if (value === passwd.oldPassword) {
          callback(new Error('新密码不能与旧密码一致'))
        } else if (value.length < 8 || value.length > 16) {
          callback(new Error('长度应在 8 到 16 个字符'))
        } else {
          const types = [/\d/, /[a-z]/, /[A-Z]/, /[!@#$%^&*()\-_+={}[\]|\\:;"'<>,.?/~`]/];
          const matchCount = types.filter((r) => r.test(value)).length
          if (matchCount < 2) {
            callback(new Error('密码至少包含两种类型（数字、字母或符号）'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  againPassword: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwd.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 修改密码接口调用方法
const changePassword = async function () {
  try {
    const params = {
      account: passwd.account,
      oldPassword: passwd.oldPassword,
      newPassword: passwd.newPassword,
      againPassword: passwd.againPassword
    }

    const result = await API({url: '/admin/password', data: params})
    console.log('修改密码结果:', result)
    
    if (result.code === 200) {
      // 使用命名路由跳转
      //await router.push({ name: 'PasswordSuccess' });
      ElMessage.success('修改密码成功');
      // 或者使用路径跳转（确保大小写完全匹配）
       //await router.push('/PasswordSuccess');
        emit('confirm')

      // 延迟跳转，确保用户看到成功消息
       setTimeout(() => {
         router.push('/PasswordSuccess'); // push跳转，留下历史记录，replace跳转，不留下历史记录
       }, 1000);
    }else if (result.code === 0){
      ElMessage.error('原密码错误，请重新输入')
      passwd.oldPassword = '';
      
    }else if(result.code === 400){
      // 显示失败弹窗
      console.log('修改密码失败')
      ElMessage.error('修改密码失败')
      //todo 待完善
    }

  } catch (error) {

    console.error('修改密码失败', error)
    ElMessage.error('操作失败')
    // 抛出错误让外层捕获，保持finally正常执行
    throw error
  }
}



// 表单提交与重置
const resetFields = () => {
  if (passwdFormRef.value) {
    passwdFormRef.value.resetFields()
  }
  errorMsg.value = ''
}
// 暴露 resetFields 方法给父组件调用
defineExpose({
  resetFields
})

// 修改提交方法
const onSubmit = () => {
  // 若正在加载中则直接返回，防止重复提交
  if (loading.value) return

  passwdFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true // 开始加载
      try {
        await changePassword() // 调用修改密码接口
      } finally {
        loading.value = false // 无论成功失败都关闭加载态
      }
    } else {
      console.log('表单校验失败')
    }

  })
}

onMounted(() => {
  getAccount()
})

</script>


<template>
  <div class="form-container">
    <el-form
        ref="passwdFormRef"
        :model="passwd"
        :rules="rules"
        label-width="100px"
        class="password-form"
    >
      <h3 class="form-title">修改密码</h3>

      <!-- 原密码 -->
      <el-form-item prop="oldPassword" label="原密码">
        <el-input
            v-model.trim="passwd.oldPassword"
            type="password"
            placeholder="请输入原密码"
            show-password
        />
      </el-form-item>

      <!-- 新密码 -->
      <el-form-item prop="newPassword" label="新密码">
        <el-input
            v-model.trim="passwd.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
        />
      </el-form-item>

      <!-- 重复密码 -->
      <el-form-item prop="againPassword" label="重复密码">
        <el-input
            v-model.trim="passwd.againPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
        />
      </el-form-item>

      <!-- 密码规则提示 -->
      <div class="rule-tips">
        <div :class="isLengthValid ? 'tip pass' : 'tip neutral'">
          <el-icon>
            <!-- 动态组件 -->
            <component :is="isLengthValid ? SuccessFilled : CircleCloseFilled"/>
          </el-icon>
          密码由8-16位数字、字母或符号组成
        </div>
        <div :class="isComplexValid ? 'tip pass' : 'tip neutral'">
          <el-icon>
            <component :is="isComplexValid ? SuccessFilled : CircleCloseFilled"/>
          </el-icon>
          至少含2种以上字符
        </div>
        <div v-if="errorMsg" class="tip fail">
          <el-icon>
            <CircleCloseFilled/>
          </el-icon>
          {{ errorMsg }}
        </div>
      </div>

      <!-- 按钮 -->
      <div class="button-group">
        <el-button
            type="primary"
            @click="onSubmit"
            style="width: 300px"
            :loading="loading"
            :disabled="!isLengthValid || !isComplexValid"
        >
          {{ loading ? '修改中...' : '确定' }}
        </el-button>
      </div>

    </el-form>
  </div>
</template>




<style scoped>
.form-container {
  justify-content: center;
  align-items: center;
}

.password-form {

  border-radius: 8px;
}

.form-title {
  text-align: left;
  margin-bottom: 24px;
  font-size: 20px;
  font-weight: bold;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.rule-tips {
  margin-left: 100px;
  margin-bottom: 12px;
}

.tip {
  font-size: 14px;
  margin: 4px 0;
  display: flex;
  align-items: center;
}

.pass {
  color: #67c23a;
}

.neutral {
  color: #999;
}

.fail {
  color: #f56c6c;
}

.rule-tips .el-icon {
  margin-right: 6px;
}
</style>
