<template>
  <el-dialog v-bind="$attrs" :visible.sync="visible" @closed="clear" :width="width" :close-on-click-modal="false"
    :destroy-on-close="true">
    <slot name="otherForm" />
    <Form v-bind="$attrs" v-if="showForm" ref="form" v-model="form" :disabled="this.type === 'detail'"
      v-loading="loading">
      <slot name="default" :type="type" :form="form" :visible="visible" :disabled="this.type === 'detail'" />
    </Form>
    <slot name="footer">
      <div slot="footer">
        <el-button v-show="this.action" :disabled="loading" :loading="submiting" type="primary"
          @click="handleConfirm">保存</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </slot>
  </el-dialog>
</template>

<script>

export default {
  name: 'DialogPage',
  props: {
    width: {
      type: String,
      default: '710px'
    },
    needClose:{
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      form: {},
      action: null,
      visible: false,
      showForm: false, // 解决组件未销毁导致的显示异常
      loading: false,
      submiting: false,
      type: 'create',
    }
  },
  methods: {
    async open(action, get) {
      this.visible = true
      this.showForm = true
      this.action = action
      this.type = 'create'
      if (!get) return
      if (typeof get === 'function') {
        this.loading = true
        const { result } = await get()
        this.loading = false
        this.type = action ? 'modify' : 'detail'
        this.$nextTick(() => {
          this.form = JSON.parse(JSON.stringify(result || {}))
        })
      } else {
        this.$nextTick(() => {
          this.form = { ...this.form, ...JSON.parse(JSON.stringify(get)) }
        })
      }
    },
    close() {
      this.visible = false
    },
    clear() {
      this.form = {}
      this.action = null
      this.showForm = false
      this.loading = false
      this.submiting = false
    },
    async handleConfirm() {
      try {
        await this.$refs.form.validate()
        this.submiting = true
        const { code, msg } = await this.action(this.form)
        if (code === 200 || code === 0) {
          this.$message.success('保存成功')
          if(this.needClose){
            this.close()
          }else {
            this.submiting = false
          }
          this.$emit('success')
        } else {
          this.submiting = false
          this.$message.warning(msg)
        }
      } catch (error) {
        this.submiting = false
        console.log(error)
      }
    },
  },
}
</script>
