<template>
  <div class="change-pwd">
    <el-dialog v-bind="$attrs" title="修改密码" width="30%" :before-close="handleClose" :append-to-body="true" :destroy-on-close="true" :close-on-click-modal="false" :close-on-press-escape="false" :lock-scroll="false" class="changepwd-dialog">
      <el-form ref="changepwdRef" :model="state.form" :rules="state.rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="原密码" prop="pwdo">
              <el-input v-model="state.form.pwdo" type="password" placeholder="请输入原密码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="新密码" prop="pwd1">
              <el-input v-model="state.form.pwd1" type="password" placeholder="请输入新密码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="确认密码" prop="pwd2">
              <el-input v-model="state.form.pwd2" type="password" placeholder="请输入确认密码" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDialog">确 定</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import useUserStore from '@/store/modules/user'
import md5 from 'js-md5'
const { proxy } = getCurrentInstance()
const mitter = proxy.mitter
const changepwdRef = ref(null)
const userStore = useUserStore()

const validatePwd = (rule, value, callback) => {
  if (state.form.pwd1 && state.form.pwd2 && state.form.pwd1 !== state.form.pwd2) {
    callback(new Error('两次输入密码不一致'))
  } else {
    changepwdRef.value.clearValidate()
    callback()
  }
}

const state = reactive({
  form: {
    pwdo: '',
    pwd1: '',
    pwd2: '',
  },
  rules: {
    pwdo: [{ required: true, message: '旧密码不能为空', trigger: 'blur' }],
    pwd1: [
      { required: true, message: '新密码不能为空', trigger: 'blur' },
      { validator: validatePwd, trigger: 'blur' },
    ],
    pwd2: [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      { validator: validatePwd, trigger: 'blur' },
    ],
  },
})

const handleClose = () => {
  changepwdRef.value.resetFields()
  mitter.emit('onCloseChangePwd', false)
}

const submitDialog = () => {
  changepwdRef.value.validate(async (valid) => {
    if (valid) {
      await userStore.resetPwd({ oPwd: md5(state.form.pwdo), nPwd: md5(state.form.pwd1) })
      proxy.$modal.msgSuccess('修改成功！')
      handleClose()
    }
  })
}
</script>

<style lang="scss" scoped></style>
