<template>
  <view class="upload">
    <!--  图片预览  -->
    <view class="preview-image-wrap" v-if="showFileList">
      <view class="preview-image-item" v-for="(item, index) in previewImageList" :key="item.hash">
        <image
          mode="heightFix"
          class="preview-image"
          @click="previewMultipleImage(index, previewImageList)"
          :src="imgPath + item.hash"
        ></image>
        <view class="delete-icon" @click="deleteFile(index, 'image')">
          <u-icon name="minus"></u-icon>
        </view>
      </view>
    </view>
    <!--  文件预览  -->
    <view v-if="showFileList">
      <view class="preview-file" v-for="(item, index) in previewFileList" :key="item.hash">
        <text class="delete-text" @click="previewFile(item)">{{ item.note | hideTextCenter(30) }}</text>
        <view class="delete-icon" @click="deleteFile(index, 'file')">
          <u-icon name="minus"></u-icon>
        </view>
      </view>
    </view>
    <!--  图片上传  -->
    <view class="image-upload" v-if="uploadType === 'image'" @click="isUploadDone ? handleUploadFile('image') : null">
      <view v-if="$slots.uploadBtn">
        <slot name="uploadBtn"></slot>
      </view>
      <view v-else>
        <u-loading v-if="!isUploadDone" mode="flower" size="100"></u-loading>
        <u-icon v-else name="photo" :size="100" color="#ddd"></u-icon>
      </view>
    </view>
    <!--  文件上传  -->
    <view class="file-upload" v-if="uploadType === 'file'" @click="isUploadDone ? handleUploadFile('file') : null">
      <view v-if="$slots.uploadBtn">
        <slot name="uploadBtn"></slot>
      </view>
      <view v-else>
        <u-loading v-if="!isUploadDone" mode="flower" size="100"></u-loading>
        <u-icon v-else name="attach" :size="100" color="#ddd"></u-icon>
      </view>
    </view>
    <!--    <u-button
      @click="handleUploadFile('image')"
      :disabled="!isUploadDone"
      :loading="!isUploadDone"
      size="medium"
      :custom-style="{ color: '#aaa', fontSize: '14px', padding: '0 20px' }"
    >
      <u-icon name="plus"></u-icon>图片
    </u-button>-->
  </view>
</template>

<script>
import { Setting } from '../../index';
import previewAnnex from '@/demo/packageDemo/mixins/previewAnnex';

export default {
  name: 'yi-upload',
  mixins: [previewAnnex],
  props: {
    // 上传文件类型 可选: image/file
    uploadType: {
      type: String,
      default: 'image',
    },
    // 是否显示已上传的文件列表
    showFileList: {
      type: Boolean,
      default: true,
    },
  },
  filters: {
    hideTextCenter: function (text, len = 88) {
      let _text = text;
      if (text.length > len) {
        // 用前n个字符+"......"+后m个字符代替
        _text = text.substring(0, 10) + '......' + text.substring(text.length - 10, text.length);
      }
      return _text;
    },
  },
  data() {
    return {
      isUploadDone: true,
      previewImageList: [],
      previewFileList: [],
      progress: 0,
    };
  },
  mounted() {
    console.log('%c [$slots]: ', 'color:#1989fa;', this.$slots);
  },
  methods: {
    /** 上传附件
     * @param fileType 文件类型
     * */
    handleUploadFile(fileType) {
      console.log('%c [handleUploadFile 000]: ', 'color:#1989fa;', fileType);
      const vm = this;
      if (fileType === 'image') {
        wx.chooseImage({
          count: 1, // 可选文件个数
          success(res) {
            console.log('%c [chooseImage res]: ', 'color:#1989fa;', res);
            const filePath = res.tempFilePaths[0];
            vm.uploadFile('image', filePath, null);
          },
        });
      }
      if (fileType === 'file') {
        // 会话中选择文件API
        uni.chooseMessageFile({
          count: 1, // 可选文件个数
          type: 'file', // 文件类型
          success(res) {
            // 选择成功后的回调函数
            console.log('%c [chooseMessageFile]: ', 'color:#1989fa;', res);
            const filePath = res.tempFiles[0].path;
            const fileName = res.tempFiles[0].name;
            vm.uploadFile('file', filePath, fileName);
          },
        });
      }
    },
    /**
     * 将本地资源上传到服务器
     * @param fileType 文件类型
     * @param filePath 文件路径
     * @param fileName  文件名
     */
    uploadFile(fileType, filePath, fileName = null) {
      // console.log('%c [uploadFile 000]: ', 'color:#1989fa;', fileType, filePath);
      uni.hideLoading();
      const vm = this;
      const imageUploadPath = Setting.getImgUploadPath();
      const fileUploadPath = Setting.getFileUploadPath();
      if (fileType === 'image') {
        vm.isUploadDone = false;
      }
      if (fileType === 'file') {
        vm.uploadFileDone = false;
      }
      vm.$emit('beforeUpload');
      const uploadTask = uni.uploadFile({
        url: fileType === 'image' ? imageUploadPath : fileUploadPath,
        filePath,
        name: 'file',
        formData: {
          filename: fileName,
        },
        success(res) {
          console.log('%c [upload success]: ', 'color:#1989fa;', res);
          const uploadRes = JSON.parse(res.data);
          const file = { note: fileName, type: fileType, hash: uploadRes.data.path };
          if (fileType === 'image') {
            vm.isUploadDone = true;
            vm.previewImageList.push(file);
          }
          if (fileType === 'file') {
            vm.uploadFileDone = true;
            vm.previewFileList.push(file);
          }
          vm.$emit('uploadSuccess', { fileType, ...uploadRes });
        },
        fail(error) {
          console.log('%c [upload fail]: ', 'color:#f33;', error);
          if (fileType === 'image') {
            vm.isUploadDone = true;
          }
          if (fileType === 'file') {
            vm.uploadFileDone = true;
          }
          vm.$emit('uploadFail', error);
        },
      });
      uploadTask.onProgressUpdate(function (res) {
        vm.progress = res.progress;
        vm.$emit('onProgressUpdate', res);
      });
    },

    // 删除上传的附件
    deleteFile(index, deleteType) {
      // console.log('%c [删除上传的附件]: ', 'color:#1989fa;', index);
      if (deleteType === 'image') {
        this.previewImageList.splice(index, 1);
      }
      if (deleteType === 'file') {
        this.previewFileList.splice(index, 1);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.upload {
  .preview-image-wrap {
    display: flex;
    flex-wrap: wrap;
    .preview-image-item {
      margin-bottom: 30rpx;
      margin-right: 30rpx;
      position: relative;
      .preview-image {
        height: 100rpx !important;
        width: auto;
      }

      .delete-icon {
        position: absolute;
        top: -20rpx;
        right: -20rpx;
        border-radius: 50%;
        height: 40rpx;
        width: 40rpx;
        color: #fff;
        background-color: #f33;
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
      }
    }
  }

  .preview-file {
    color: #0054a3;
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    line-height: 1.3;
    margin-top: 30rpx;
    .delete-text {
      flex: 1;
    }

    .delete-icon {
      border-radius: 50%;
      height: 40rpx;
      width: 40rpx;
      color: #fff;
      background-color: #f33;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
