<template>
  <div>
    <!-- 正常弹窗 -->
    <el-dialog
      v-show="!minimized"
      :visible.sync="visibleSync"
      :title="title"
      v-bind="$attrs"
      v-on="$listeners"
    >
      <template #title>
        <span>{{ title }}</span>
        <i
          class="el-icon-minus"
          style="cursor:pointer;float:right;margin-right:35px;"
          @click.stop="minimize"
        ></i>
      </template>
      <slot />
      <template #footer>
        <slot name="footer" />
      </template>
    </el-dialog>

    <!-- 最小化悬浮卡片 -->
    <div
      v-show="minimized"
      class="minimized-dialog"
      ref="minCard"
      @click="restore"
    >
      <i :class="minIcon"></i>
      <span>{{ minTitle || title }}</span>
    </div>
  </div>
</template>

<script>
export default {
  name: "MinimizableDialog",
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: ""
    },
    minTitle: {
      type: String,
      default: ""
    },
    minIcon: {
      type: String,
      default: "el-icon-files"
    }
  },
  data() {
    return {
      minimized: false,
      visibleSync: this.visible
    };
  },
  watch: {
    visible(val) {
      this.visibleSync = val;
      if (val) this.minimized = false;
    },
    visibleSync(val) {
      this.$emit("update:visible", val);
    }
  },
  mounted() {
    this.moveMinCardToBody();
  },
  beforeDestroy() {
    this.removeMinCardFromBody();
  },
  methods: {
    moveMinCardToBody() {
      if (this.$refs.minCard && typeof window !== 'undefined') {
        document.body.appendChild(this.$refs.minCard);
      }
    },
    removeMinCardFromBody() {
      if (this.$refs.minCard && this.$refs.minCard.parentNode) {
        this.$refs.minCard.parentNode.removeChild(this.$refs.minCard);
      }
    },
    minimize() {
      this.minimized = true;
      this.visibleSync = false;
      this.$emit("minimize");
    },
    restore() {
      this.minimized = false;
      this.visibleSync = true;
      this.$emit("restore");
    },
  }
};
</script>

<style scoped>
.minimized-dialog {
  position: fixed;
  right: 30px;
  bottom: 30px;
  background: #409EFF;
  color: #fff;
  padding: 10px 18px;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
  cursor: pointer;
  z-index: 1000;
  display: flex;
  align-items: center;
  font-size: 15px;
}
.minimized-dialog:hover {
  box-shadow: 0 4px 16px rgba(0,0,0,0.25);
}
.minimized-dialog i {
  margin-right: 8px;
  font-size: 18px;
}
</style>
