<template>
  <div class="w-up-image">
    <el-upload
      class="w-upload-image"
      ref="uploadPhotoEl"
      :action="action"
      :file-list="fileList"
      :limit="4"
      :multiple="true"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-success="onSuccess"
      :on-remove="handleRemove"
      :disabled="disabledVal"
      :before-upload="filelistBeforeUpload"
      accept=".jpg,.jpeg,.png"
    >
      <i slot="default" class="el-icon-plus"></i>
      <div slot="file" slot-scope="{ file }">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!disabled" class="el-upload-list__item-delete" :disabled="disabledVal" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'WUploadPhoto',
  props: {
    picture: String,
    disabledVal: Boolean,
    reflowData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      fileList: [],
      tossUrls: [],
      action: process.env.VUE_APP_BASE_API + '/supportMaterial/uploadImage'
    }
  },
  watch: {
    disabledVal(v, o) {
      this.fileList = this.reflowData.map((e) => ({ name: '', url: e }))

      this.tossUrls = this.reflowData.map((e) => e)
    }
  },

  methods: {
    getTossUrlsString() {
      return this.tossUrls.toString()
    },

    onSuccess(response, file, fileList) {
      this.tossUrls.push(response.data)
      this.$emit('update:picture', this.tossUrls.toString())
    },

    // 上传文件前做限制
    filelistBeforeUpload(file, fileList) {
      const isRightSize = file.size / 1024 / 1024 < 5
      if (!isRightSize) {
        useMessage('error', '文件大小超过 5MB')
      }
      return isRightSize
    },

    handleRemove(file) {
      const files = this.$refs.uploadPhotoEl.uploadFiles
      const item = this.tossUrls.findIndex((e) => e === file.url)
      for (let i = 0; i < files.length; i++) {
        if (files[i]['url'] === file.url) {
          files.splice(i, 1)
        }
      }
      this.tossUrls.splice(item, 1)
      this.$emit('update:picture', this.tossUrls.toString())
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
