<template>
  <Modal
    :options="getModalOptions"
    :on-positive-click="handleConfirm"
    :on-negative-click="handleClose"
    :on-close="handleClose"
  >
    <template #Context>
      <n-form
        ref="formRef"
        :model="form"
        label-placement="left"
        :rules="rules"
        :on-positive-click="handleConfirm"
        :on-negative-click="handleClose"
      >
        <n-form-item
          label="旧密码:"
          path="oldPassword"
        >
          <n-input
            v-model:value="form.oldPassword"
            type="password"
            :maxlength="20"
            placeholder="请输入旧密码"
          />
        </n-form-item>
        <n-form-item
          label="新密码:"
          path="newPassword"
        >
          <n-input
            v-model:value="form.newPassword"
            type="password"
            :maxlength="20"
            placeholder="请输入新密码"
          />
        </n-form-item>
        <n-form-item
          label="确认密码:"
          path="configmPassword"
        >
          <n-input
            v-model:value="form.configmPassword"
            type="password"
            :maxlength="20"
            placeholder="请再次输入新密码"
          />
        </n-form-item>
      </n-form>
    </template>
  </Modal>
</template>
<script>
import Modal from '@/components/Modal/index.vue'
import { updatePwd } from '@/api/home/index.js'
import { reactive, toRefs } from '@vue/reactivity'
export default {
  name: 'UpdateModal',
  components: { Modal },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: {
    'update:visible': null
  },
  setup(props, { emit }) {
    const data = reactive({
      form: {
        oldPassword: '',
        newPassword: '',
        configmPassword: ''
      },
      rules: {
        oldPassword: {
          required: true,
          trigger: ['blur', 'input'],
          message: '请输入旧密码'
        },
        newPassword: {
          required: true,
          trigger: ['blur', 'input'],
          message: '请输入新密码'
        },
        configmPassword: {
          required: true,
          trigger: ['blur', 'input'],
          message: '请再次输入新密码'
        }

      }
    })

    /* 关闭弹窗 */
    const handleClose = () => {
      emit('update:visible', false)
    }
    return {
      ...toRefs(data),
      handleClose
    }
  },
  methods: {
    handleConfirm() {
      this.$refs.formRef.validate((errors) => {
        if (!errors) {
          updatePwd(this.form).then(res => {
            if (res.code === 0) {
              this.handleClose()
              $message.success(res.msg)
            } else {
              $message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</script>
