<script>
import UploadList from './upload-list';
import Upload from './upload';
import UploadCard from './upload-card.vue';
import CutDialog from './cut-dialog.vue';
import ElProgress from 'modesign-ui/packages/progress';
import Migrating from 'modesign-ui/src/mixins/migrating';

function noop() {}

export default {
  name: 'ElUpload',

  mixins: [Migrating],

  components: {
    ElProgress,
    UploadList,
    UploadCard,
    Upload,
    CutDialog
  },

  provide() {
    return {
      uploader: this,
      // 零售版会传个配置值过来，但是其他项目可能不会，如果没有provide，就会报错
      commonConfig: {}
    };
  },

  inject: {
    elForm: {
      default: ''
    }
  },

  props: {
    action: {
      type: String,
      required: true
    },
    headers: {
      type: Object,
      default() {
        return {};
      }
    },
    data: Object,
    multiple: Boolean,
    cut: Boolean,
    name: {
      type: String,
      default: 'file'
    },
    drag: Boolean,
    dragger: Boolean,
    withCredentials: Boolean,
    showFileList: {
      type: Boolean,
      default: true
    },
    accept: String,
    type: {
      type: String,
      default: 'select'
    },
    beforeUpload: Function,
    beforeRemove: Function,
    onRemove: {
      type: Function,
      default: noop
    },
    onChange: {
      type: Function,
      default: noop
    },
    onPreview: {
      type: Function
    },
    onSuccess: {
      type: Function,
      default: noop
    },
    onProgress: {
      type: Function,
      default: noop
    },
    onError: {
      type: Function,
      default: noop
    },
    fileList: {
      type: Array,
      default() {
        return [];
      }
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    listType: {
      type: String,
      default: 'text' // text,picture,picture-card
    },
    httpRequest: Function,
    disabled: Boolean,
    readable: Boolean,
    limit: Number,
    onExceed: {
      type: Function,
      default: noop
    },
    // 可读禁用是否可以编辑已回显的图片
    editCallback: {
      type: [Boolean, Function],
      default: false
    },
    // 可读禁用是否可以删除已回显的图片
    delCallback: {
      type: [Boolean, Function],
      default: false
    }
  },

  data() {
    return {
      uploadFiles: [],
      dragOver: false,
      draging: false,
      tempIndex: 1,
      perNum:0
    };
  },

  computed: {
    uploadReadable() {
      return this.readable || (this.elForm || {}).readable
    },

    uploadDisabled() {
      return this.disabled || (this.elForm || {}).disabled || this.uploadReadable;
    }
  },

  watch: {
    listType(type) {
      if (type === 'picture-card' || type === 'picture') {
        this.uploadFiles = this.uploadFiles.map(file => {
          if (!file.url && file.raw) {
            try {
              file.url = URL.createObjectURL(file.raw);
            } catch (err) {
              console.error('[El Error][Upload]', err);
            }
          }
          return file;
        });
      }
    },
    fileList: {
      immediate: true,
      handler(fileList) {
        this.uploadFiles = fileList.map(item => {
          item.uid = item.uid || (Date.now() + this.tempIndex++);
          item.status = item.status || 'success';
          return item;
        });
      }
    }
  },

  methods: {
    handleStart(rawFile, fileIndex, addFile) {
      rawFile.uid = Date.now() + this.tempIndex++;
      let file = {
        status: 'ready',
        name: rawFile.name,
        size: rawFile.size,
        percentage: 0,
        uid: rawFile.uid,
        raw: rawFile
      };

      if (this.listType === 'picture-card' || this.listType === 'picture' || this.listType === 'picture-wall') {
        try {
          file.url = URL.createObjectURL(rawFile);
        } catch (err) {
          console.error('[El Error][Upload]', err);
          return;
        }
      }
      // 如果是新增的，是push，如果是替换的，那么应该用splice插入
      addFile ? this.uploadFiles.push(file) : this.uploadFiles.splice(fileIndex, 0, file);
      this.onChange(file, this.uploadFiles);
    },
    handleProgress(ev, rawFile) {
      const file = this.getFile(rawFile);
      this.onProgress(ev, file, this.uploadFiles);
      file.status = 'uploading';
      file.percentage = ev.percent || 0;
      this.perNum = file.percentage
    },
    handleSuccess(res, rawFile, prevFile, prevIndex) {
      this.perNum = 100
      const file = this.getFile(rawFile);

      if (file) {
        file.status = 'success';
        file.response = res;
        this.onSuccess(res, file, this.uploadFiles, prevFile, prevIndex);
        this.onChange(file, this.uploadFiles);
      }
    },
    handleError(err, rawFile) {
      this.perNum = 100
      const file = this.getFile(rawFile);
      // const fileList = this.uploadFiles;

      file.status = 'fail';

      // fileList.splice(fileList.indexOf(file), 1);

      this.onError(err, file, this.uploadFiles);
      this.onChange(file, this.uploadFiles);
    },
    handleRemove(file, raw) {
      if (raw) {
        file = this.getFile(raw);
      }
      let doRemove = () => {
        this.abort(file);
        let fileList = this.uploadFiles;
        fileList.splice(fileList.indexOf(file), 1);
        this.onRemove(file, fileList);
      };

      if (!this.beforeRemove) {
        doRemove();
      } else if (typeof this.beforeRemove === 'function') {
        const before = this.beforeRemove(file, this.uploadFiles);
        if (before && before.then) {
          before.then(() => {
            doRemove();
          }, noop);
        } else if (before !== false) {
          doRemove();
        }
      }
    },
    getFile(rawFile) {
      let fileList = this.uploadFiles;
      let target;
      fileList.every(item => {
        target = rawFile.uid === item.uid ? item : null;
        return !target;
      });
      return target;
    },
    abort(file) {
      this.$refs['upload-inner'].abort(file);
    },
    clearFiles() {
      this.uploadFiles = [];
    },
    submit() {
      this.uploadFiles
        .filter(file => file.status === 'ready')
        .forEach(file => {
          this.$refs['upload-inner'].upload(file.raw);
        });
    },
    getMigratingConfig() {
      return {
        props: {
          'default-file-list': 'default-file-list is renamed to file-list.',
          'show-upload-list': 'show-upload-list is renamed to show-file-list.',
          // 'thumbnail-mode': 'thumbnail-mode has been deprecated, you can implement the same effect according to this case: http://element.eleme.io/#/zh-CN/component/upload#yong-hu-tou-xiang-shang-chuan'
        }
      };
    }
  },

  beforeDestroy() {
    this.uploadFiles.forEach(file => {
      if (file.url && file.url.indexOf('blob:') === 0) {
        URL.revokeObjectURL(file.url);
      }
    });
  },

  render(h) {
    let uploadList;
    if (this.showFileList) {
      uploadList = (
        <UploadList
          readable={this.uploadReadable}
          disabled={this.uploadDisabled}
          listType={this.listType}
          files={this.uploadFiles}
          autoUpload={this.autoUpload}
          on-remove={this.handleRemove}
          handlePreview={this.onPreview}
          scopedSlots={
            {
              default: (props) => {
                return this.$scopedSlots.file ? this.$scopedSlots.file({
                  file: props.file
                }) : null;
              },
              icon: (props) => {
                return this.$scopedSlots.icon ? this.$scopedSlots.icon({
                  file: props.file
                }) : null;
              }
            }
          }>
        </UploadList>
      );
    }

    const uploadData = {
      props: {
        perNum: this.perNum,
        type: this.type,
        drag: this.drag,
        action: this.action,
        multiple: this.multiple,
        cut: this.cut,
        'before-upload': this.beforeUpload,
        'with-credentials': this.withCredentials,
        headers: this.headers,
        name: this.name,
        data: this.data,
        accept: this.accept,
        fileList: this.uploadFiles,
        autoUpload: this.autoUpload,
        listType: this.listType,
        disabled: this.uploadDisabled,
        readable: this.uploadReadable,
        limit: this.limit,
        'on-exceed': this.onExceed,
        'on-start': this.handleStart,
        'on-progress': this.handleProgress,
        'on-success': this.handleSuccess,
        'on-error': this.handleError,
        'on-preview': this.onPreview,
        'on-remove': this.handleRemove,
        'http-request': this.httpRequest
      },
      ref: 'upload-inner'
    };

    const conatinerNewClass = {
      class: {
        'el-upload-list_max': (this.uploadFiles || []).length === this.limit
      }
    }

    const trigger = this.$slots.trigger || this.$slots.default;
    const tip = this.$slots.tip;
    const uploadComponent = <div><upload {...uploadData}>
      {trigger}
      <template slot="tip">
        {tip}
      </template>
    </upload>
      {this.cut ? (<CutDialog ref="cut-dialog"></CutDialog>) : null}
    </div>;

    if (this.listType === 'picture-card') {
      return (
        <div class="el-upload__picture-card" {...conatinerNewClass}>
          { uploadComponent }
          {
            this.uploadFiles.map((item) => {
              return <UploadCard
                file={item}
                readable={this.uploadReadable}
                disabled={this.uploadDisabled}
                on-remove={this.handleRemove}
                handlePreview={this.onPreview}>
                {
                  (props) => {
                  if (this.$scopedSlots.file) {
                    return this.$scopedSlots.file({
                      file: props.file
                    });
                  }
                }
              }
              </UploadCard>
            })
          }
        </div>
      )
    }

    if (this.listType === 'picture-wall') {
      return (
        <div class="el-upload__picture-wall" {...conatinerNewClass}>
          {
            this.uploadFiles.map((item) => {
              return <UploadCard
                file={item}
                readable={this.uploadReadable}
                disabled={this.uploadDisabled}
                on-remove={this.handleRemove}
                handlePreview={this.onPreview}>
                {
                  (props) => {
                  if (this.$scopedSlots.file) {
                    return this.$scopedSlots.file({
                      file: props.file
                    });
                  }
                }
              }
              </UploadCard>
            })
          }
          { uploadComponent }
        </div>
      )
    }

    return (
    // { this.listType === 'picture-card' ? uploadList : ''}
    <div {...conatinerNewClass}>
      {
        this.$slots.trigger
          ? [uploadComponent, this.$slots.default]
          : uploadComponent
      }
      { uploadList }
      </div>
    );
        // { this.listType !== 'picture-card' ? uploadList : ''}
  }
};
</script>
