<template>
  <dl :class="['x-book',{'x-book--multi': multi}]"
      :style="multi ? '' : `width: ${coverStyle.width}`"
      @click="click(book)">
    <dt class="x-book__coverbox">
      <img v-if="book.cover"
           class="x-book__cover"
           :style="coverStyle"
           :key="book.cover"
           v-lazy="book.cover"
           lazy="loading">
      <img v-else
           :style="coverStyle"
           class="x-book__cover"
           src="https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/book/cover/loading.png">
      <slot name="shadow"></slot>
    </dt>
    <dd v-if="multi"
        class="x-book__text--multi"
        :style="textStyle">
      <slot></slot>
    </dd>
    <dd v-else
        class="x-book__text--normal">{{book.name}}</dd>
  </dl>
</template>
<script>
export default {
  props: {
    book: {
      // {name,cover}
      required: true,
      type: Object
    },
    multi: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: "2rem"
    },
    prevent: {
      type: Boolean,
      default: false
    }
  },
  name: "XBook",
  data() {
    const size = this.width.match(/[\d-.]+/g);
    const unit = this.width.match(/[^\d-.]+/g);
    return {
      coverStyle: {
        width: size + unit,
        height: (size / 3) * 4 + unit
      },
      textStyle: {
        width: `calc(100% - ${size + unit})`,
        height: (size / 3) * 4 + unit
      }
    };
  },
  methods: {
    click(book) {
      if (
        !this.prevent &&
        this.customClick &&
        typeof this.customClick === "function"
      )
        this.customClick(book);
      this.$emit("click", book);
    }
  },
  install(Vue, options) {
    //可以传入click事件
    if (options && typeof options.click === "function") {
      this.methods.customClick = options.click;
    }
    Vue.component(this.name, this);
  }
};
</script>
