<template>
  <MDialog
    :visible="visible"
    title="驳回订单"
    widthType="2"
    @update:visible="handleVisibleChange"
    @submit="handleSubmit"
  >
    <MForm ref="form" :items="formItems" v-model="form"></MForm>
  </MDialog>
</template>

<script>
import MDialog from '@/components/Dialog'
import MForm from '@/components/MForm'
import { api } from '@/api/dataOrder'

export default {
  name: 'RejectOrderDialog',
  components: {
    MDialog,
    MForm
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    orderId: {
      type: Number,
      default: null
    }
  },
  data () {
    return {
      form: {
        reason: ''
      }
    }
  },
  computed: {
    formItems () {
      return [
        {
          type: 'textarea',
          key: 'reason',
          label: '驳回原因 *',
          rules: [
            v => !!v || '请输入驳回原因 *'
          ],
          outlined: true
        }
      ]
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.resetForm()
      }
    }
  },
  methods: {
    handleVisibleChange (val) {
      this.$emit('update:visible', val)
    },
    resetForm () {
      this.form.reason = ''
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetValidation()
        }
      })
    },
    async handleSubmit () {
      if (!this.$refs.form.validate()) {
        return
      }
      if (!this.orderId) {
        this.$snackbar.error('订单ID不能为空')
        return
      }
      try {
        await api.rejectOrder(this.orderId, this.form.reason)
        this.$snackbar.success('订单已驳回')
        this.$emit('update:visible', false)
        this.$emit('success')
      } catch (error) {
        this.$snackbar.error(error)
      }
    }
  }
}
</script>
