<template>
  <div class="dialog-container">
    <ElDialog
      v-el-drag-dialog
      :visible="show"
      :close-on-click-modal="false"
      title="修改密码"
      width="40%"
      @close="onCancel"
    >
      <ChangePasswordForm
        ref="passwordForm"
        :data="data"
        :loading="submitLoading"
      />
      <div
        slot="footer"
        class="footer-container"
      >
        <ElButton @click="onCancel">
          取 消
        </ElButton>
        <ElButton
          type="primary"
          :loading="submitLoading"
          @click="onSubmit"
        >
          保 存
        </ElButton>
      </div>
    </ElDialog>
  </div>
</template>

<script>
import ElDragDialog from '@/directives/el-drag-dialog'
import ChangePasswordForm from '../form/ChangePasswordForm'
import consumerApi from '@/api/consumer'

export default {
  components: {
    ChangePasswordForm
  },
  directives: {
    ElDragDialog
  },
  data() {
    return {
      show: false,
      data: null,
      submitLoading: false
    }
  },
  methods: {
    open(data) {
      this.show = true
      this.data = data
    },
    onCancel() {
      this.show = false
      this.$refs.passwordForm.reset()
    },
    async onSubmit() {
      try {
        let data = {}
        const valid = await this.$refs.passwordForm.onSubmit()
        if (valid) {
          data = this.$refs.passwordForm.form
        } else {
          return false
        }
        this.submitLoading = true
        await consumerApi.updatePassword(data.userid, data)
        this.$message.success('修改成功')
        this.$refs.passwordForm.reset()
        this.show = false
      } catch (error) {
        return error?.response?.data
      } finally {
        this.submitLoading = false
      }
    }
  }
}
</script>

<style
  scoped
  lang="scss"
>
.footer-container {
  text-align: center;
}
</style>
