<template>
  <div>
    <upload-button ref="uploadButtonRef" :accept="accept" :show-file-list="true" :file-list.sync="localFileList"
      list-type="picture-card" :limit="5" :multiple="true" :class="{ 'disabled-upload': localFileList.length >= 5 }"
      :disabled="localFileList.length >= 5" :before-upload="beforeUpload" :http-request="localUploadImg">
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}" class="image-wrapper">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <div v-show="file.isPrimary">
          <div class="image-tag" />
          <div class="image-tag-tips">主图</div>
        </div>
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePreviewLogo(file)">
            <i class="el-icon-zoom-in" />
          </span>
          <el-tooltip content="设为主图" effect="dark" placement="bottom">
            <span class="el-upload-list__item-delete" @click="handleSetTopLogo(file)">
              <i class="el-icon-magic-stick" />
            </span>
          </el-tooltip>
          <span class="el-upload-list__item-delete" @click="handleRemoveLogo(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </upload-button>
    <span class="form-tip">可上传1~5张图片，默认第一张为主图</span>
  </div>

</template>

<script>
import UploadButton from '@/components/Upload/UploadButton'
import { uploadFile } from '@/api/upload'
import { compressImg, urlToBase64ToFile } from '@/utils'

export default {
  name: 'UploadToyImg',
  components: { UploadButton },
  props: {
    fileList: {
      type: Array,
      default: () => []
    },
    formState: {
      type: Object,
      default: () => ({
        toyCoverUrl: null,
        fileId: null
      })
    },
    uploadFileList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      uploadFile: null,
      accept: '.jpg,.jpeg,.png,.gif'
    }
  },
  computed: {
    localFileList: {
      get() {
        return this.fileList
      },
      set(val) {
        this.$emit('update:fileList', val)
      }
    },
    localFormState: {
      get() {
        return this.formState
      },
      set(val) {
        this.$emit('update:formState', val)
      }
    }
  },
  watch: {
    localFileList(val) {
      this.localFormState.fileId = val && val.length > 0 ? val.map(file => file.id).join(',') : null
      if (!val || val.length === 0) this.localFormState.toyCoverUrl = null
    }
  },
  methods: {
    beforeUpload(file) {
      const accept = this.accept
      const fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
      const fileName = file.name.slice(0, file.name.lastIndexOf('.'))
      if (!accept.split(',').includes(`.${fileExtension.toLowerCase()}`)) {
        this.$message.error('暂不支持上传该格式文件')
        return false
      } else {
        return true
      }
    },
    localUploadImg(value) {
      compressImg(value.file, null, 300).then(res => {
        const formData = new FormData()
        formData.append('file', res.file)
        uploadFile(formData).then(({ data }) => {
          data.name = data.fileName
          data.url = data.fileUrl
          data.isPrimary = false
          data.uploadFile = res.file
          data.uid = res.file.uid
          data.deletable = true
          this.localFileList.push(data)
          if (!this.localFileList.some(file => file.isPrimary)) {
            this.localFileList[0].isPrimary = true
            this.localFormState.toyCoverUrl = this.localFileList[0].url
          }
          this.localFormState.fileId = this.localFileList.map(file => file.id).join(',')
        })
      })
    },
    handlePreviewLogo(file) {
      this.$refs.uploadButtonRef.handleFilePreview(file)
    },
    async handleSetTopLogo(file) {
      this.localFileList.forEach(item => {
        item.isPrimary = item.id === file.id
      })
      this.localFormState.toyCoverUrl = file.url
      this.$message.success('设置成功')
    },
    handleRemoveLogo(file) {
      // 删除主图 默认将 第一张设为主图
      this.$refs.uploadButtonRef.handleFileRemove(file)
      this.$nextTick(async () => {
        if (file.isPrimary) {
          this.localFormState.toyCoverUrl = this.localFileList && this.localFileList.length > 0 ? this.localFileList[0].url : null
          if (this.localFileList && this.localFileList.length > 0) {
            this.localFileList.forEach((item, index) => {
              item.isPrimary = index === 0
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.disabled-upload {
  ::v-deep .el-upload.el-upload--picture-card {
    cursor: not-allowed;
  }
}
</style>

<style lang="scss" scoped>
.disabled-upload {
  ::v-deep .el-upload.el-upload--picture-card {
    cursor: not-allowed;
  }
}

//移除动画
::v-deep .el-upload-list__item {
  transition: none !important;
  -webkit-transition: none !important;
}

::v-deep .el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: none !important;
}

::v-deep .disabled .el-upload--picture-card {
  display: none !important;
}
</style>
