<template>
  <el-dialog
    v-model="dialogVisible"
    title="初始密码重置"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="change-password-form">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="form.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">修改</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { updateUserPassword } from '@/api/system/user/profile'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { deleteUserCache } from '@/hooks/web/useCache'
const { push, replace } = useRouter()
defineOptions({ name: 'ChangePasswordDialog' })

const userStore = useUserStore()
const tagsViewStore = useTagsViewStore()
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

const form = reactive({
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        if (value.includes(' ')) {
          callback(new Error('密码不能包含空格'))
          return
        }
        if (value.length < 8) {
          callback(new Error('密码长度不能少于8位'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        if (value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const open = () => {
  dialogVisible.value = true
  form.newPassword = ''
  form.confirmPassword = ''
  loading.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    loading.value = true
    try {
      await updateUserPassword(form.newPassword, form.confirmPassword, '0')
      ElMessage.success('密码修改成功')
      dialogVisible.value = false
      loading.value = false
      await userStore.loginOut()// 登出后清理
      deleteUserCache() // 清空用户缓存
      tagsViewStore.delAllViews()
      replace('/login?redirect=/home/index')
    } catch (error) {
      // ElMessage.error('密码修改失败:' + error)
      loading.value = false
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

defineExpose({ open })
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
