<template>
  <div class="component-upload-image">
    <el-upload
      v-if="uploadType === 'base64'"
      action=""
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :on-remove="handleDelete2"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList2"
      :on-preview="handlePictureCardPreview"
      :class="{ hide: this.fileList2.length >= this.limit }"
      :http-request="httpRequest"
    >
      <div
        style="
          heigh: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
        "
      >
        <i class="el-icon-plus"></i>
        <span class="titlespan">{{ titlecomputon }}</span>
      </div>
    </el-upload>
    <el-upload
      v-if="uploadType != 'base64'"
      multiple
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      ref="imageUpload"
      :on-remove="handleDelete"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :class="{ hide: this.fileList.length >= this.limit }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <!-- 上传提示 -->
    <div class="el-upload__tip" slot="tip" v-if="showTip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
import { UPLOAD_TYPE_MAP, UPDALOD_API_MAP } from '@/utils/constants';
import { getToken } from '@/utils/auth';
import { assign, last, isArray, startsWith } from 'lodash-es';

export default {
  // props:['message'],//接收psMsg值
  props: {
    value: [String, Object, Array],
    // 图片数量限制
    limit: {
      type: Number,
      default: 5
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ['png', 'jpg', 'jpeg']
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    uploadType: {
      type: String,
      default: UPLOAD_TYPE_MAP.COMMON
    },
    title: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_RESOURCE_PREFIX,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileList: [],
      fileList2: [],
      UPDALOD_API_MAP
    };
  },
  watch: {
    value: {
      handler(val) {
        if (val) {
          if (typeof val === 'string') {
            return;
          }

          // 首先将值转为数组
          const list = Array.isArray(val) ? val : [val];

          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            let data = assign({}, item);
            if (
              item.url &&
              !startsWith(item.url, 'http') &&
              !startsWith(item.url, this.baseUrl)
            ) {
              data = {
                name: this.baseUrl + item.url,
                url: this.baseUrl + item.url,
                resId: item.resId || item.resIds || ''
              };
            } else {
              data = {
                name: item.url,
                url: item.url,
                resId: item.resId || item.resIds || ''
              };
            }

            return data;
          });
        } else {
          this.fileList = [];
          return [];
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    uploadImgUrl() {
      return process.env.VUE_APP_BASE_API + UPDALOD_API_MAP[this.uploadType];
    },
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
    titlecomputon() {
      if (this.title == false) {
        return '上传背景图';
      } else {
        return '上传logo';
      }
    }
  },
  methods: {
    httpRequest(res) {
      //专门处理返回结果要base64的情况 就是获取了个base64值 别的啥也没干
      // console.log(res)
      const file = res.file;
      const reader = new FileReader();
      reader.readAsDataURL(file);
      const _this = this;
      reader.onload = function (e) {
        _this.fileList2.push({
          name: file.name,
          url: e.target.result
        });
        _this.$modal.closeLoading();
        _this.$emit('input', e.target.result);
        _this.$emit('getBase64Success', e.target.result);
      };
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = '';
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf('image') > -1;
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join('/')}图片格式文件!`
        );
        return false;
      }
      if (file.size / 1024 / 1024 > this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading('正在上传图片，请稍候...');
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功回调
    handleUploadSuccess(res, file, fileList) {
      const { resUrl, url, resId, resCreatorname, resOssUrl } = res.data;
      if (res.code === '000000') {
        this.uploadList.push({
          resId: resId,
          name: url || resCreatorname,
          url: resOssUrl || resUrl
        });

        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDelete(file) {
      const findex = this.fileList.map((f) => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit(
          'input',
          isArray(this.value) ? this.fileList : last(this.fileList)
        );
      }
    },
    handleDelete2(file) {
      const findex = this.fileList2.map((f) => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList2.splice(findex, 1);
        this.$emit(
          'input',
          isArray(this.value) ? this.fileList2 : last(this.fileList2)
        );
      }
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError('上传图片失败，请重试');
      this.$modal.closeLoading();
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit(
          'input',
          isArray(this.value) ? this.fileList : last(this.fileList)
        );
        this.$modal.closeLoading();
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = '';
      separator = separator || ',';
      for (const i in list) {
        if (list[i].url) {
          strs += list[i].url.replace(this.baseUrl, '') + separator;
        }
      }
      return strs != '' ? strs.substr(0, strs.length - 1) : '';
    }
  }
};
</script>
<style scoped lang="scss">
.component-upload-image {
  div:first-child {
    display: flex;
  }
}
.titlespan {
  line-height: 28px;
  margin-top: 5px;
}
.el-icon-plus {
  font-size: 30px;
}
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
</style>

<style lang="css" scoped>
/deep/ .el-upload--picture-card {
  /* height: 200px;
  width: 300px; */
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
