<!--
 * @Author: zhangbo
 * @Date: 2021-03-03 19:50:46
 * @E-mail: zhangbo@geovis.com.cn
 * @LastModifiedBy: zhangbo
 * @LastEditTime: 2021-03-08 09:28:27
 * @Desc: 
-->
<script>
export default {
  name: "base-earth-plugins",
  props: {
    viewerId: {
      type: String,
      editor: {
        ignore: true,
      },
    },
  },
  mounted() {
    if (this.Bus) {
      //创建球后刷新earthList
      // this.Bus.$off("earth-list-update-l");
      this.Bus.$on("earth-list-update-l", (vs) => {
        console.log('update earth',vs)
        if (this.viewerId&&!this.viewer) {
          this.viewer = this.getViewer(this.viewerId);
          this.init();
        } else if (
          !this.viewerId &&
          vs.length === 1 &&
          this.viewer !== vs[0].obj
        ) {
          this.viewer = vs[0].obj;
          this.init();
        }
      });
    }
    this.viewer = this.getViewer(this.viewerId);
    // console.log('base component init')
  },
  methods: {
    getViewer(id) {
      if (this.$store) {
        const vs = this.$store.state.DataHub.earthList;
        if (!vs) {
          return;
        }
        if (vs && vs.length === 1&&!id) {
          return vs[0].obj;
        }
        for (let v of vs) {
          if (v.id === id) {
            return v.obj;
          }
        }
      }
    },
  },
  watch: {
    viewerId(n, o) {
      const v = this.getViewer(n);
      if (v) {
        //球的id变了，但是球没变
        if (v === this.viewer) {
          return;
        }
        //viewer未定义，即组件尚未初始化
        if (!this.viewer) {
          this.viewer = v;
          this.init();
          return;
        }
        //组件已经初始化，但是要将组件绑定到另一个球
        //移除原来球上的数据并重新初始化
        this.destroy();
        this.viewer = v;
        this.init();
      } else {
        this.$message.warning("无效的球组件");
      }
    },
  },
  beforeDestroy() {
    if (this.Bus) {
      this.Bus.$off("viewer-destroy");
      this.Bus.$on("viewer-destroy", (id) => {
        if (id === this.viewerId) {
          //删除组件数据并销毁本组件
          this.destroy();
        }
      });
    }
  },
};
</script>