<template>
  <el-dialog
    class="es-dialog"
    :title="titles"
    :visible.sync="show"
    :width="_width"
    :height="_height"
    :close-on-click-modal="shadeClose"
    :showScale="showScale"
    :drag="drag"
    :modal-append-to-body="modalAppendToBody"
    v-bind="$attrs"
    v-on="{ ...$listeners, close: handleClosed, scale: handleScale }"
    :class="{
      'es-dialog-plus': mode == 'plus',
      'is-middle': middle,
      'es-title-hide': !titles
    }"
    :append-to-body="appendToBody"
    :id="wujieName"
    :ref="wujieName"
  >
    <slot></slot>
    <template v-if="contents">
      <template v-if="Array.isArray(contents)">
        <template v-for="(item, index) in contents">
          <es-form
            v-if="item.type === 'form'"
            :key="index"
            v-bind="
              handleExclAttribute({
                data: item,
                attrs: ['events', 'visible', 'type', 'model']
              })
            "
            :model.sync="item.model"
            v-on="{ ...item.events }"
          ></es-form>
          <es-data-table
            v-if="item.type === 'data-table' || item.type === 'dataTable'"
            :key="index"
            v-bind="
              handleExclAttribute({
                data: item,
                attrs: ['events', 'visible', 'type']
              })
            "
            v-on="item.events"
          >
            <template v-if="item.dialog" slot="dialog">
              <template v-if="Array.isArray(item.dialog)">
                <es-dialog
                  v-for="(ele, ids) in item.dialog"
                  :isReload="true"
                  v-bind="
                    handleExclAttribute({
                      data: ele,
                      attrs: ['visible']
                    })
                  "
                  :key="ids"
                  :visible.sync="ele.visible"
                  v-on="{ ...ele.events }"
                >
                </es-dialog>
              </template>
              <es-dialog
                v-else
                :isReload="true"
                v-bind="
                  handleExclAttribute({
                    data: item.dialog,
                    attrs: ['visible']
                  })
                "
                :visible.sync="item.dialog.visible"
                v-on="{ ...item.dialog.events }"
              >
              </es-dialog>
            </template>
          </es-data-table>
          <es-tree-group
            v-if="item.type === 'data-table' || item.type === 'dataTable'"
            :key="index"
            v-bind="
              handleExclAttribute({
                data: item,
                attrs: ['events', 'visible', 'type']
              })
            "
            v-on="{ ...item.events }"
          ></es-tree-group>
          <es-flow-group
            v-if="item.type === 'flow-group' || item.type === 'flowGroup'"
            :key="index"
            v-bind="
              handleExclAttribute({
                data: item,
                attrs: ['events', 'visible', 'type']
              })
            "
            v-on="{ ...item.events }"
          ></es-flow-group>
          <es-tabs
            v-if="item.type === 'tabs'"
            :key="index"
            :full="true"
            v-bind="
              handleExclAttribute({
                data: item,
                attrs: ['events', 'visible', 'type']
              })
            "
            v-on="{ ...item.events }"
          ></es-tabs>
          <es-dialog
            v-if="item.type === 'dialog'"
            :isReload="true"
            v-bind="
              handleExclAttribute({
                data: items,
                attrs: ['events', 'visible', 'type']
              })
            "
            :key="index"
            :visible.sync="item.visible"
            v-on="{ ...item.events }"
          ></es-dialog>
          <iframe
            v-if="item.type === 'iframe' && show"
            frameborder="0"
            width="100%"
            height="100%"
            :key="index"
            :id="item.name || contents.id"
            :name="item.name || item.id"
            :src="getUrl(item)"
          ></iframe>
          <es-wujie
            v-else-if="item.type === 'wujie' && show"
            :key="index"
            :show="show"
            :dialog="true"
            :appendTopBody="appendToBody === 'top'"
            v-bind="
              handleExclAttribute({
                data: item,
                attrs: ['events', 'visible', 'type']
              })
            "
            :name="wujieName"
          ></es-wujie>
        </template>
      </template>
      <template v-else>
        <es-form
          v-if="contents.type === 'form'"
          v-bind="
            handleExclAttribute({
              data: contents,
              attrs: ['events', 'visible', 'type', 'model']
            })
          "
          :model.sync="contents.model"
          v-on="{ ...contents.events }"
        ></es-form>
        <es-data-table
          v-if="contents.type === 'data-table' || contents.type === 'dataTable'"
          v-bind="
            handleExclAttribute({
              data: contents,
              attrs: ['events', 'visible', 'type']
            })
          "
          v-on="contents.events"
        >
          <template v-if="contents.dialog" slot="dialog">
            <template v-if="Array.isArray(contents.dialog)">
              <es-dialog
                v-for="(ele, ids) in contents.dialog"
                :isReload="true"
                v-bind="
                  handleExclAttribute({
                    data: ele,
                    attrs: ['visible']
                  })
                "
                :key="ids"
                :visible.sync="ele.visible"
                v-on="{ ...ele.events }"
              >
              </es-dialog>
            </template>
            <es-dialog
              v-else
              :isReload="true"
              v-bind="
                handleExclAttribute({
                  data: contents.dialog,
                  attrs: ['visible']
                })
              "
              :visible.sync="contents.dialog.visible"
              v-on="{ ...contents.dialog.events }"
            >
            </es-dialog>
          </template>
        </es-data-table>
        <es-tree-group
          v-if="contents.type === 'data-table' || contents.type === 'dataTable'"
          v-bind="
            handleExclAttribute({
              data: contents,
              attrs: ['events', 'visible', 'type']
            })
          "
          v-on="{ ...contents.events }"
        ></es-tree-group>
        <es-flow-group
          v-if="contents.type === 'flow-group' || contents.type === 'flowGroup'"
          v-bind="
            handleExclAttribute({
              data: contents,
              attrs: ['events', 'visible', 'type']
            })
          "
          v-on="{ ...contents.events }"
        ></es-flow-group>
        <es-tabs
          v-if="contents.type === 'tabs'"
          :full="true"
          v-bind="
            handleExclAttribute({
              data: contents,
              attrs: ['events', 'visible', 'type']
            })
          "
          v-on="{ ...contents.events }"
        ></es-tabs>
        <iframe
          v-if="contents.type === 'iframe' && show"
          :id="contents.name || contents.id || name"
          :name="contents.name || contents.id || name"
          frameborder="0"
          width="100%"
          height="100%"
          :src="getUrl(contents)"
        ></iframe>
        <es-wujie
          v-else-if="contents.type === 'wujie' && show"
          :show="show"
          :dialog="true"
          :appendTopBody="appendToBody === 'top'"
          v-bind="
            handleExclAttribute({
              data: contents,
              attrs: ['events', 'visible', 'type']
            })
          "
          :name="wujieName"
        ></es-wujie>
      </template>
    </template>
  </el-dialog>
</template>
<script>
import WujieVue from 'wujie-vue2';
import util from 'eoss-ui/src/utils/util';
let availWidth = 0;
let availHeight = 0;
const wind = util.getWinTop();
availWidth = wind.document.body.offsetWidth - 260;
availHeight = wind.document.body.offsetHeight - 60;
const systemMode = wind.systemMode || util.win.systemMode || 'default';
export default {
  name: 'EsDialog',
  inheritAttrs: false,
  provide() {
    return {
      esDialog: this,
      scale: this.scales
    };
  },
  inject: {
    esPage: {
      default: ''
    },
    tableReload: {
      default: ''
    },
    esDialog: {
      default: ''
    }
  },
  props: {
    mode: {
      type: String,
      default: systemMode
    },
    title: String,
    busEvent: String,
    contents: [Array, Object],
    visible: {
      type: Boolean,
      default: false
    },
    visibleKey: String,
    fullscreen: {
      type: Boolean,
      default: false
    },
    name: String,
    iframe: String,
    wujie: String,
    param: {
      type: Object,
      default() {
        return {};
      }
    },
    width: [String, Number],
    height: [String, Number],
    middle: {
      type: Boolean,
      default: true
    },
    modalAppendToBody: {
      type: Boolean,
      default: true
    },
    appendToBody: {
      type: [Boolean, String],
      default: true
    },
    shadeClose: {
      type: Boolean,
      default: false
    },
    isReload: Boolean,
    firstPage: Boolean,
    tree: Boolean,
    size: {
      type: String,
      default: 'md'
    },
    drag: {
      type: Boolean,
      default: true
    },
    closeParent: Boolean,
    showScale: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    wujieName() {
      return this.name ? this.name : util.uuid(16);
    },
    _width() {
      return this.width ? this.width : this.sizes[this.size]['width'];
    },
    _height() {
      return this.height ? this.height : this.sizes[this.size]['height'];
    }
  },
  watch: {
    show(val) {
      this.$emit('update:visible', val);
    },
    visible(val) {
      this.show = val;
    },
    title(val) {
      this.titles = val;
    }
  },
  data() {
    return {
      titles: this.title,
      full: false,
      method: 'router',
      sizes: {
        mini: { width: '800px', height: '400px' },
        sm: { width: '960px', height: '500px' },
        md: { width: '1060px', height: '600px' },
        lg: { width: '1200px', height: availHeight < 800 ? '560px' : '800px' },
        max: { width: `${availWidth}px`, height: `${availHeight}px` },
        full: { width: '100%', height: '100%' }
      },
      show: this.visible,
      defaultProps: {},
      zoom: 1,
      scales: { zoom: 1 }
    };
  },
  created() {
    if (this.busEvent) {
      const bus = this.bus || this.$root.Bus;
      bus &&
        bus.$on(this.busEvent, async (res) => {
          this.titles = res.title;
          this.handler && (await this.handler(res, this));
          this.handleShow();
        });
    }
  },
  mounted() {
    WujieVue.bus.$on('dialogClose', (res, dialog) => {
      let _dialog = this.$refs[dialog._dialogId];
      if (_dialog) {
        _dialog.hide();
        if (this.isReload) {
          for (let i = 0; i < this.$parent.$children.length; i++) {
            let item = this.$parent.$children[i];
            if (item.reload) {
              item.reload(this.param, this.firstPage, this.tree);
              break;
            }
          }
        }
      }
    });
  },
  methods: {
    async setAttrs(res) {
      this.titles = res.title;
      this.handler && (await this.handler(res, this));
      this.handleShow();
    },
    getUrl(res) {
      let params = util.extend(true, this.param, res.param || {});
      return util.urlJoinParams({
        url: res.url,
        param: params
      });
    },
    handleExclAttribute({ data, attrs }) {
      return {
        ...util.exclAttribute({
          data: data,
          attrs: attrs
        }),
        ...this.param
      };
    },
    handleShow() {
      this.show = true;
    },
    handleClosed(res) {
      this.show = false;
      this.$emit('close', res, this);
      if (this.closeParent && this.esDialog) {
        this.esDialog.handleClosed(res);
      }
    },
    handleClose(reload = true) {
      this.$refs[this.wujieName] && this.$refs[this.wujieName].hide();
      if (this.isReload !== false && reload !== 0 && reload !== false) {
        for (let i = 0; i < this.$parent.$children.length; i++) {
          let item = this.$parent.$children[i];
          if (item.reload) {
            item.reload(this.param, this.firstPage, this.tree);
            break;
          }
        }
      }
    },
    handleScale(res) {
      this.zoom = res;
      this.$set(this.scales, 'zoom', res);
      this.$emit('scale', res);
    },
    getDialog() {
      return this.$refs[this.wujieName].$refs['dialog'];
    }
  },
  beforeDestroy() {
    WujieVue.bus.$off('dialogClose');
    const bus = this.bus || this.$root.Bus;
    this.busEvent && bus && Bus.$off(this.busEvent);
  }
};
</script>
