<template>
  <el-dialog
    v-model="open"
    title="修改初始密码"
    width="500px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="pwdRef" :model="passwordForm" :rules="passwordRules" label-width="80px">
      <el-form-item label="新密码" prop="newPassword">
        <el-input
          v-model="passwordForm.newPassword"
          placeholder="请输入新密码"
          type="password"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="passwordForm.confirmPassword"
          placeholder="请确认新密码"
          type="password"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit" :loading="submitLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { initPassword } from "@/api/login"
import { ElMessage } from 'element-plus'

const open = ref(false)
const pwdRef = ref(null)
const submitLoading = ref(false)

// 登录信息
const loginInfo = reactive({
  username: '',
  password: '',
  code: '',
  uuid: ''
})

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

const passwordRules = reactive({
  newPassword: [
    { required: true, message: "新密码不能为空", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirmPassword: [
    { required: true, message: "确认密码不能为空", trigger: "blur" },
    { validator: checkConfirmPassword, trigger: "blur" }
  ]
})

function checkConfirmPassword(rule, value, callback) {
  if (value !== passwordForm.newPassword) {
    callback(new Error("两次输入的密码不一致"))
  } else {
    callback()
  }
}

function show(loginData) {
  open.value = true
  reset()
  // 保存登录信息
  loginInfo.username = loginData.username
  loginInfo.password = loginData.password
  loginInfo.code = loginData.code
  loginInfo.uuid = loginData.uuid
}

function hide() {
  open.value = false
}

function reset() {
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  if (pwdRef.value) {
    pwdRef.value.resetFields()
  }
}

function submit() {
  pwdRef.value.validate(valid => {
    if (valid) {
      submitLoading.value = true
      // 使用初始密码修改接口
      initPassword(loginInfo.username, passwordForm.newPassword, loginInfo.code, loginInfo.uuid).then(response => {
        submitLoading.value = false
        ElMessage.success("密码修改成功，请重新登录")
        hide()
        // 通知父组件密码修改成功
        emits('passwordChanged')
      }).catch(() => {
        submitLoading.value = false
      })
    }
  })
}

defineExpose({
  show,
  hide
})

const emits = defineEmits(['passwordChanged'])
</script>