<template>
  <Basic :question="question" :index="index" :pIndex="pIndex">
    <ul class="imgage-picker">
      <li v-for="(item, index) in question.choices" :key="item.value" class="imgage-picker-item">
        <div class="container">
          <img :src="item.imageLink" :ref="'img_ref_' + index"/>
          <p :title="item.text" v-if="question.showLabel">{{item.text || item.value}}</p>
        </div>
        <div class="toolbox">
          <el-button type="text" class="el-icon-edit"><input @change="handleEditChoice($event, question.choices, index, 'img_ref_' + index)" type="file" /></el-button>
          <el-button type="text" class="el-icon-delete" @click="handleDeleteChoice(question.choices, index)"></el-button>
        </div>
      </li>
      <li :class="['imgage-picker-item', 'add', {'is-show-label': question.showLabel}]">
        <div type="text" class="el-icon-plus"><input @change="handleEditChoice($event, question.choices, index)" type="file" /></div>
      </li>
    </ul>
    <template v-slot:control>
      <el-button type="success" @click="startEdit('edit')" size="mini" class="event-bubbling">{{ $t('general.btnEdit') }}</el-button>
      <el-button type="info" @click="startEdit('options')" size="mini" class="event-bubbling">{{ $t('general.btnChoose') }}</el-button>
    </template>
  </Basic>
</template>

<script>
import Question from './Question'
import Basic from './Basic'

export default {
  components: {
    Basic
  },
  props: ['question'],
  mixins: [Question],
  data () {
    return {
    }
  },
  methods: {
    /**
     * 删除单个图片
     * @param index 图片索引
     */
    handleDeleteChoice (choices, index) {
      choices.splice(index, 1)
      this.$store.commit('saveQuestion', {question: {
        ...this.question,
        choices
      }, index: this.index})
    },
    /**
     * 编辑单个图片
     * @param event 点击事件
     * @param index 图片索引
     * @param imgRef 图片ref
     */
    handleEditChoice (event, choices, index, imgRef) {
      try {
        const file = event.target.files[0]
        // 文件类型
        const fileType = this.getFileType(file.type)
        // 文件类型校验
        const fileTypeArr = ['jpg', 'gif', 'jpeg', 'png', 'bmp']
        if (fileTypeArr.indexOf(fileType) === -1) {
          this.$message.warning(this.$t('question.imageType'))
          return false
        }
        // 文件大小
        const fileSize = (file.size / 1024).toFixed(2)
        // 文件大小校验，最大200K
        if (fileSize > 200) {
          this.$message.warning(this.$t('question.imageSize200'))
          return false
        }
        // 文件大小校验，超过20K提示用户
        if (fileSize > 20) {
          this.$message(this.$t('question.imageSize20'))
        }

        // 更换图片
        const reader = new FileReader()
        reader.readAsDataURL(file)
        const _this = this
        reader.onload = function (e) {
          const str = e.target.result

          if(!imgRef){
            // 加入新项
            const newItem = {
              value: _this.$store.getters.getDefaultItemValue(choices, 'value', 'item'),
              text: _this.$store.getters.getDefaultItemValue(choices, 'value', 'item'),
              imageLink: str
            }
            choices.push(newItem)
          }else{
            // 显示新图片
            _this.$refs[imgRef][0].setAttribute('src', str)
            // 更新数据
            choices[index].imageLink = str
          }
          _this.$store.commit('saveQuestion', { question: {
            ..._this.question,
            choices
          }, index: _this.index})
        }
      } finally {
        event.target.value = null
      }
    },
    getFileType (filePath) {
      const startIndex = filePath.lastIndexOf('/')
      if (startIndex !== -1) {
        return filePath.substring(startIndex + 1, filePath.length).toLowerCase()
      } else {
        return ''
      }
    }
  }
}
</script>

<style lang="scss">
.imgage-picker{
  list-style: none;
  overflow: hidden;
  margin: 0;
  padding: 0;
  .imgage-picker-item{
    float: left;
    width: 210px;
    margin: 6px;
    border-width: 1px;
    border-style: solid;
    border-color: lightgrey;
    border-radius: 4px;
    padding: 4px;
    box-sizing: border-box;
    position: relative;
    & > .container{
      padding: 0 !important;
      & > img{
        width: 200px;
        height: 150px;
        object-fit: contain;
      }
      & > p{
        font-size: 14px;
        line-height: 20px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        margin: 0;
      }
    }
    &:hover{
      & > .container{
        opacity: 0.7;
      }
    }
    .toolbox{
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      display: inline-block;
      background-color: rgba(255, 255, 255, 0.9);
      border-radius: 2px;
      padding: 0 12px;
      .el-button--text{
        font-size: 20px;
        font-weight: bolder;
        color: #48A736;
        padding: 6px 2px;
        &.el-icon-edit{
          position: relative;
          input[type="file"]{
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            outline: none;
            opacity: 0;
          }
        }
      }
    }
    &.add{
      text-align: center;
      .el-icon-plus{
        width: 100%;
        height: 100%;
        display: inline-block;
        line-height: 154px;
        font-size: 40px;
        color: #48A736;
        padding: 0;
        position: relative;
        & > input{
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          outline: none;
          opacity: 0;
        }
      }
      &.is-show-label{
        .el-icon-plus{
          line-height: 174px;
        }
      }
    }
  }
}
</style>
