<style scoped>
  .waterfall-flow-item__wrapper {
    list-style: none;
    display: inline-block;
    position: absolute;
    background-color: #fff;
    border-radius: 6px;
    /*border: 1px solid #ECEDEF;*/
    /*box-shadow: 0 1px 1px rgba(99,99,99,.05);*/
  }
  .waterfall-flow-item__wrapper.selected .panel-card {
    border-color: #28B06E;
    box-shadow: 0px 2px 16px 0px rgba(92 , 153 , 122, 0.2);
  }
  .waterfall-flow-item__wrapper.selected .panel-card:before,
  .waterfall-flow-item__wrapper.selected .panel-card:after {
    position: absolute;
    right: -3px;
    top: -2px;
    color: #28B06E;
    font-size: 27px;
    line-height: 1;
    font-family: monospace;
    content: '◥';
    z-index: 1;
  }

  .waterfall-flow-item__wrapper.selected .panel-card:after {
    font-size: 12px;
    font-weight: 600;
    right: 0px;
    top: 0px;
    color: #fff;
    content: '√';
    font-family: cursive;
  }
</style>

<template>
  <li class="waterfall-flow-item__wrapper" @click.stop="handleItemClick" :class="{ selected: isSelected }">

    <slot></slot>
  </li>
</template>

<script>
import emitter from '@src/mixins/emitter.js'

function imageLoad(imagePath) {
  let path = ''
  if (typeof imagePath === 'object' && imagePath.src) {
    path = imagePath.src
  }

  if (typeof imagePath === 'string') {
    path = imagePath
  }

  let img = new Image()

  img.crossOrigin = 'anonymous'
  img.src = path

  return new Promise((resolve, reject) => {
    img.onload = () => resolve(img)

    img.onerror = resolve
  })
}

export default {
  name: 'WaterfallFlowItem',
  componentName: 'WaterfallFlowItem',
  mixins: [emitter],
  props: {
    item: {
      type: Object,
      required: true
    },
    selected: {
      type: Array,
      default () {
        return []
      }
    }
  },
  data () {
    return {}
  },
  computed: {
    isSelected () {
      return this.selected.includes(this.item)
    }
  },
  methods: {
    handleItemClick (e) {
      // console.log(this.item)
      this.dispatch('WaterfallFlowList', 'click-item', this.item)
    }
  },
  created () {
    this.$on('ask-complete', () => {
      //  console.log('ask' this.$el)
      const images = this.$el.querySelectorAll('img')
      if (images.length === 0) {
        this.dispatch('WaterfallFlow', 'complete')
        return
      }
      let promises = []
      for (let i = 0; i < images.length; i++) {
        // console.log('image')
        promises.push(imageLoad(images[i]))
      }

      Promise.all(promises).then(() => {
        this.dispatch('WaterfallFlow', 'complete')
      })
    })
  }
}
</script>
