<template>
  <p-modal
    :draggable='true'
    title='密码重置'
    :visible='visible'
    @ok='handleOk'
    @cancel='handleCancel'
  >
    <p-form-model ref='formTarget' :label-col='{ span: 4 }' :model='form' :rules='rules' :wrapper-col='{ span: 20 }'
                  class='plg-grid-from'>
      <p-form-model-item label='新密码' prop='newPassword'>
        <p-input-password v-model='form.newPassword' placeholder='请输入新密码' allowClear />
      </p-form-model-item>
      <p-form-model-item label='确认密码' prop='surePassword'>
        <p-input-password v-model='form.surePassword' placeholder='请输入确认密码' allowClear />
      </p-form-model-item>
    </p-form-model>
  </p-modal>
</template>

<script>
import { resetPwd } from '../api'

export default {
  model: {
    prop: 'visible',
    event: 'change'
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const validateNewPassword = (rule, value, callback) => {
      if (value && this.form.surePassword && value !== this.form.surePassword) {
        callback(new Error('两次密码输入不一致'))
      } else {
        if (this.form.surePassword) {
          this.$refs.formTarget.validateField('surePassword')
        }
        callback()
      }
    }
    const validateSurePassword = (rule, value, callback) => {
      if (this.form.newPassword && value && value !== this.form.newPassword) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      rules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'change' },
          { validator: validateNewPassword, trigger: 'blur' }
        ],
        surePassword: [
          { required: true, message: '请输入确认密码', trigger: 'change' },
          { validator: validateSurePassword, trigger: 'blur' }
        ]
      },
      form: {
        newPassword: '',
        surePassword: ''
      }
    }
  },
  watch: {
    visible() {
      this.form = {
        newPassword: '',
        surePassword: ''
      }
    }
  },
  methods: {
    handleOk() {
      this.$refs.formTarget.validate(flag => {
        if (!flag) return
        this.resetPwd()
      })
    },
    handleCancel() {
      this.$emit('change', false)
    },
    resetPwd() {
      const { id } = this.editData
      resetPwd({ ...this.form, id }).then(res => {
        if (res.success) {
          this.handleCancel()
          this.$message.success('修改成功')
        } else {
          this.$message.error(res.message)
        }
      }).catch(err => {
        this.$message.error(err.message)
      })
    }
  }
}
</script>

<style scoped>

</style>