<template>
  <el-dialog v-bind="$attrs" :visible="show" :title="title" :width="width" class="zy-dialog" append-to-body
             :close-on-click-modal="false" :close-on-press-escape="false" @close="close">
    <slot name="before"></slot>
    <div v-loading="formLoading" style="padding: 0 15px;">
      <zy-form ref="form" v-bind="$attrs" :items="items" :label-width="labelWidth" :searchable="searchable"
               :cols="cols" :mode="mode">
      </zy-form>
    </div>
    <slot name="after"></slot>
    <div slot="footer" v-if="mode === '_view'">
      <el-button @click="close">关 闭</el-button>
    </div>
    <div slot="footer" v-else>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>

  export default {
    name: 'ZyDialog',
    props: {
      show: {type: Boolean, default: false},
      title: {type: String, default: '新增'},
      width: {type: String, default: '600px'},
      mode: {type: String, default: '_create'},
      formLoading: {type: Boolean, default: false},
      items: {type: Array, default: () => []},
      labelWidth: {type: String, default: '100px'},
      cols: {type: Number, default: 1},
      searchable: {type: Boolean, default: false}
    },
    components: {},
    data() {
      return {}
    },
    created() {
    },
    mounted() {
    },
    watch: {
      show: {
        handler: function (nv) {
          if (!nv) {
            this.$refs['form'].resetFields();
          } else {
            if (this.$refs['form']) {
              this.$refs['form'].initFormData();
            }
          }
        }
      }
    },
    computed: {},
    methods: {
      close() {
        this.$emit('close');
      },
      submit(evt) {
        let target = evt.target;
        if (target.nodeName == "SPAN") {
          target = evt.target.parentNode;
        }
        target.blur();
        this.$refs['form'].validateForm(valid => {
          if (valid) {
            let data = _.cloneDeep(this.$refs['form'].formData);
            this.items.forEach(item => {
              if (item.type === 'cascader' && item.leafValue) {
                data[item.key] = _.last(data[item.key]);
              }
            });
            this.$emit('submit', data);
          }
        })
      }
    },
  }
</script>
<style lang="scss">
  .zy-dialog {
    .el-dialog {
      max-height: 70vh;
    }

    .el-dialog__body {
      max-height: calc(70vh - 95px);
      overflow-y: auto;
    }
  }
</style>
