<template>
  <div>
    <van-uploader
      ref="pictureUpload"
      :disabled="disabled"
      :readonly="uploadDisabled"
      :deletable="!uploadDisabled"
      :show-upload="!uploadDisabled"
      :data="uploadImg.postData"
      :before-delete="handleRemove"
      v-model="uploadImg.fileList"
      :after-read="onUploadChanged"
      max-count="1"
    >
<!--      :accept="uploadImg.accept"-->
    </van-uploader>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";
import request from "@/utils/request";
import {Notify} from "vant";

export default {
  name: "MultiImageUploadComp",
  props: ["uploadDisabled", 'value', 'tableId', 'tableName', 'bizPath', 'fileType', 'resultType', 'attach', 'disabled'],
  watch: {
    value: {
      handler: function (newVal, oldVal) {
        console.info(newVal);
        if(newVal == this.internalValue)
          return;
        this.reset();
        this.uploadImg.fileList = this.makeUploadFileList(newVal);
        this.internalValue = newVal;
      },
      immediate: true,
    },
  },
  created() {
  },
  data() {
    return {
      uploadImg: {
        //上传图片配置
        attachImgUrl: "/common/attach",
        uploadImgUrl: "/common/upload",
        removeImgUrl: "/system/attachment/remove",
        uploadImgHeaders: {
          Authorization: "Bearer " + getToken(),
        },
        accept: '.jpg,.png,.gif,.jpeg',
        fileList: [],
        postData: {
          tableId: this.tableId || '',
          tableName: this.tableName || '',
          bizPath: this.bizPath || 'upload',
          fileType: this.fileType || '',
        },
      },
      internalValue: null,
    }
  },
  methods: {
    reset() {
    },
    onUploadChanged(file, detail) {
      console.log(file, detail);
      this.setFileStatus(file, 'uploading', '文件上传中...');
      this.updateFile(file).then((resp) => {
        this.setFileStatus(file, 'done', '文件上传成功');
        if(this.attach)
        {
          file.id = resp.id;
          file.path = resp.fileUrl;
        }
        else {
          file.path = resp.fileName;
        }
        file.fileList = this.uploadImg.fileList;
        this.$emit('fileChanged', this.uploadImg.fileList);
        this.updateValue();
        console.log('新增', this.uploadImg.fileList);
      }).catch((e) => {
        this.setFileStatus(file, 'fail', '文件上传失败');
      })
      return true;
    },
    setFileStatus(file, status, message) {
      file.status = status;
      file.message = message;
    },
    notify(message, type) {
      Notify.clear();
      Notify({ type: type || 'primary', message: message });
    },
    handleRemove(file, detail) {
      console.log(file, detail);
      if(file.id) // new upload
      {
        this.setFileStatus(file, 'uploading', '文件删除中...');
        this.removeFile(file.id).then((resp) => {
        }).finally(() => {
          let index = this.uploadImg.fileList.indexOf(file);
          console.log(index);
          if(index !== -1)
            this.uploadImg.fileList.splice(index, 1);
          console.log(this.uploadImg.fileList);
          this.$emit('fileChanged', this.uploadImg.fileList);
          this.updateValue();
          console.log('删除', this.uploadImg.fileList);
        })
      }
      else // from server
      {
        let index = this.uploadImg.fileList.indexOf(file);
        if(index !== -1)
          this.uploadImg.fileList.splice(index, 1);
        this.$emit('fileChanged', this.uploadImg.fileList);
        this.updateValue();
      }
      return true;
    },
    // 图片上传尺寸大小检验
    beforeUpload(file) {
      const isLt50M = file.size / 1024 / 1024 < 30;
      if (!isLt50M) {
        this.$message({
          message: "上传文件大小不能超过 30MB!",
          type: "error",
        });
        return false;
      } else if (file.name.length > 100) {
        // 图片上传文件名长度检验(配合后台上传方法的验证,否则上传不成功但是前台无提示)
        this.$message({
          message: "上传文件的文件名长度不能超过 100个字符!",
          type: "error",
        });
        return false;
      }
      return isLt50M;
    },
    getFileName(path) {
      let index = path.lastIndexOf('/');
      return index !== -1 && index !== path.length - 1 ? path.substr(index + 1) : path;
    },
    makeUploadFileList(joinStr) {
      if(!joinStr) return [];
      const Host = '/api'; //this.$store.getters.baseRoutingUrl;
      let fileList = Array.isArray(joinStr) ? joinStr : joinStr.split(',');
      let res = [];
      fileList.forEach((x) => {
        let item = {
          name: this.getFileName(x),
          url: Host + x,
          path: x,
          fileList: res,
        };
        res.push(item);
      });
      return res;
    },
    updateFile(file) {
      // 自动上传
      let formData = new FormData;
      formData.append('file', file.file);
      return request({
        url: this.attach ? this.uploadImg.attachImgUrl : this.uploadImg.uploadImgUrl,
        method: "post",
        params: this.uploadImg.postData,
        data: formData,
      });
    },
    removeFile(id) {
      return request({
        url: this.uploadImg.removeImgUrl + `/${id}`,
        method: "get",
      });
    },
    updateValue() {
      let arr = this.uploadImg.fileList.map((x) => x.path);
      if(this.resultType === 'array')
        this.internalValue = arr;
      else
        this.internalValue = arr.join(',');
      this.$emit('fileUpdate', this.internalValue);
      this.$emit('input', this.internalValue);
    },
  }
}
</script>

<style scoped>

</style>
