<template>
  <div>
    <CAccordionItem>
      <CAccordionHeader>
      {{ title }}
      </CAccordionHeader>
      <CAccordionBody>
        <strong>
          {{ hint }}
        </strong>
        <ul class="list-group">
          <li class="list-group-item" v-for="(x, i) in items" :key="i">
            <div class="border p-1">
              <div>
                <img class="content" v-if="is_image" :src="x.url" />
                <video class="content" v-if="is_video" :src="x.url" />
                <IconControl v-if="type == 'icon'" :item="x" @updated="$emit('updated')" />
              </div>
              <div v-if="!fixed_items">
                <CButton color="danger" @click="$emit('del', x.id)" class="h-100">
                  <font-awesome-icon icon="trash-can" />
                </CButton>
              </div>
            </div>
          </li>
        </ul>
        <div class="my-3" v-if="!fixed_items">
          <div>
            <img :src="selected_file" class="upload-preview" v-if="selected_file" alt=""/>
          </div>
          <input class="form-control my-1" type="file" ref="fileinput" @change="file_selected"/>
          <label>链接目标:</label>
          <input class="form-control my-1" type="text" v-model="link" />
          <CButton class="mt-2" @click="add" color="success">添加</CButton>
        </div>
      </CAccordionBody>
    </CAccordionItem>
  </div>
</template>

<script>
import IconControl from './icon-control';

export default {
  name: 'ContentAccordionItem',
  props: ['title', 'hint', 'type', 'items', 'fixed_items'],
  components: {
    IconControl,
  },
  data: function () {
    return {
      link: '',
      selected_file: null,
    };
  },
  computed: {
    is_image: function() {
      return this.type == 'carousel' || this.type == 'static';
    },
    is_video: function() {
      return this.type == 'video';
    },
  },
  methods: {
    file_selected: function() {
      var fi = this.$refs.fileinput;
      if (fi && fi.files && fi.files.length > 0) {
        this.selected_file = URL.createObjectURL(fi.files[0]);
      }
    },
    add: function() {
      var fs = this.$refs.fileinput.files;
      if (!fs.length) return;
      var f = fs[0];
      var properties = {
        type: this.type,
        link: this.link,
      };
      var options = {
        file: f,
        filename: f.name,
        properties: properties,
      };
      this.$emit('add', options);
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
.content {
  width: 100%;
  height: 100%;
}
img.upload-preview {
  max-width: 100%;
}
</style>
