<template>
  <div>
    <m-card title="重置密码">
      <div class="d-flex justify-center flex-column pa-3 align-center">
        <m-form style="width: 500px;" ref="form" :items="formItems"></m-form>
        <v-btn class="buttons" rounded color="primary" @click="handleClick">提交</v-btn>
      </div>
    </m-card>
  </div>
</template>

<script>
import MCard from '@/components/MCard'
import MForm from '@/components/Form/list'
import { resetPassword } from '@/api/user'
export default {
  name: 'reset-password',
  components: {
    MCard,
    MForm
  },
  data () {
    return {
      formItems: {
        options: [
          {
            type: 'text',
            key: 'sourcrPwd',
            value: null,
            label: '请输入旧密码 *',
            outlined: true,
            dense: true,
            rules: [v => !!v || '请输入密码']
          },
          {
            type: 'text',
            key: 'newPwd',
            value: null,
            label: '请输入新密码 *',
            outlined: true,
            dense: true,
            rules: [v => !!v || '请输入新密码']
          },
          {
            type: 'text',
            key: 'renewPwd',
            value: null,
            label: '请再次输入新密码 *',
            outlined: true,
            dense: true,
            rules: [this.validatePwd]
          }
        ]
      }
    }
  },
  methods: {
    validatePwd (v) {
      if (!v) {
        return '请输入新密码'
      }
      if (this.formItems.options.find(e => e.key === 'newPwd').value !== v) {
        return '两次输入的密码不一致'
      }
      return true
    },
    async handleClick () {
      if (!this.$refs.form.validate()) {
        return
      }
      const { renewPwd, ...obj } = this.formItems.options.reduce((res, item) => {
        res[item.key] = item.value
        return res
      }, {})
      Object.assign(obj, {
        type: 2
      })
      try {
        await resetPassword(obj)
        this.$snackbar.success('重置密码成功')
        setTimeout(() => {
          this.$store.dispatch('user/userLogout')
        }, 1000)
      } catch (error) {
        this.$snackbar.error(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
