<template>
  <el-dialog class="dialog-common" v-bind="$attrs" :title="title"
             :modal-append-to-body="modalAppendToBody"
             :append-to-body="appendToBody"
             :destroy-on-close="destoryOnClose"
             :close-on-click-modal="closeOnClickModal"
             :visible.sync="visible" @closed="clear" :width="maxWidth"  >
    <div v-if="visible" v-loading="loading">
      <slot name="default" />
    </div>
    <slot name="footer">
      <div slot="footer" >
        <el-button v-show="this.action" :disabled="loading" icon="el-icon-circle-check"  v-if="showConfirm" :loading="submiting" type="primary" @click="handleConfirm">确认</el-button>
        <el-button @click="close" icon="el-icon-remove-outline">取消</el-button>
      </div>
    </slot>
  </el-dialog>
</template>

<script>
/**
 * 模态框
 */

export default {
  name: 'DialogPage',
  props:{
    modalAppendToBody:{
      type: Boolean,
      default: true
    },
    appendToBody:{
      type: Boolean,
      default: false
    },
    destoryOnClose:{
      type: Boolean,
      default: true
    },
    closeOnClickModal:{
      type: Boolean,
      default: false
    },

    showConfirm:{
      type: Boolean,
      default: true
    },
    maxWidth:{
      type: String,
      default: '1100px'
    },
    title:{
      type: String,
    },
    submitCheckFunction:{
      type: Function,
    }
  },
  data() {
    return {
      action: null,
      visible: false,
      loading: false,
      submiting: false,
    }
  },
  methods: {
    async open(action) {
      this.visible = true
      this.action = action
    },
    close() {
      this.visible = false
      this.$emit('close')
    },
    clear() {
      this.action = null
      this.loading = false
      this.submiting = false
      this.close()
    },
    async handleConfirm() {
      if(this.submitCheckFunction){
        await this.submitCheckFunction()
      }
      if(typeof(this.action) == 'boolean' && this.action){
        this.close()
        this.$emit('confirm')
        return;
      }else{
        if(this.action){
          this.$message.success('保存成功')
          this.close()
          this.$emit('confirm')
          return;
        }
      }
      try {
        // await this.$refs.form.validate()
        this.submiting = true
        const { code, msg } = await this.action()
        if (code === 200) {
          this.$message.success('保存成功')
          this.close()
          this.$emit('success')
        } else {
          this.submiting = false
          this.$message.error(msg)
        }
      } catch (error) {
        this.submiting = false
        console.log(error)
      }
    },
  },
}
</script>

<style scoped>
.dialog-common .card-container {
  min-height: 700px;
}
</style>
