<template>
  <div>
    <div class="alert alert-info" v-for="x, i in items" :key="i">
      <h5>
        项目 {{ i + 1 }}
      </h5>
      <hr>
      <MediaSelector type="image" v-model="x.url">
        <div class="alert alert-info">
          建议分辨率： 500x100 或相似比例
        </div>
      </MediaSelector>
      <hr>
      <div>
        链接:
      </div>
      <ArticleSelector v-model="x.link" />
      <hr>
      <div class="controls">
        <button class="btn btn-secondary" @click="move(i, -1)">上移</button>
        <button class="btn btn-secondary" @click="move(i, 1)">下移</button>
        <button class="btn btn-secondary" @click="del(i)">删除</button>
      </div>
    </div>
    <hr>
    <button class="btn btn-success my-1" @click="show_add">添加新项</button>
    <Modal ref="new_item_modal" @close="add">
      <hr>
      <MediaSelector :-model="new_item.url" ref="new_image_selector" type="image">
        <div class="alert alert-info">
          建议分辨率： 500x100 或相似比例
        </div>
      </MediaSelector>
      <hr>
      链接
      <ArticleSelector v-model="new_item.link" />
      <hr>
    </Modal>
  </div>
</template>

<script>
import MediaSelector from '../components/media-selector';
import ArticleSelector from '../components/article-selector';
export default {
  name: 'ImageLinks',
  props: ['items'],
  components: {
    MediaSelector,
    ArticleSelector,
  },
  data: function () {
    return {
      new_item: {},
    };
  },
  computed: {
  },
  methods: {
    show_add: function() {
      this.$refs.new_item_modal.show();
    },
    select_new_article: function(id) {
      this.new_item.link = id;
    },
    change_link(index, link) {
      var items = this.items;
      items[index].link = link;
      this.$emit("update", items);
    },
    emit_change: function(items) {
      this.$emit("update", items);
    },
    add: function(ok) {
      if (!ok) return;
      var items = this.items.concat([this.new_item]);

      this.new_item = {};
      this.$refs.new_image_selector.clear();
      this.emit_change(items);
    },
    move: function(index, offs) {
      var items = this.items;
      var ni = index + offs;
      if (ni < 0 || ni >= items.length) return;
      var tmp = items[index + offs];
      items[index + offs] = items[index];
      items[index] = tmp;

      this.emit_change(items);
    },
    del: function(index) {
      var items = this.items;
      items.splice(index, 1);

      this.emit_change(items);
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
div.controls {
  margin: 1rem 0;
}
div.controls button {
  margin-right: 1rem;
}
</style>

