class Upload extends AdminBase {
    constructor(file, resolve, reject) {
        super();
        if (!file instanceof File) {
            return AdminBase.warn('文件属性不明');
        }
        this.file = file;
        this.types = ['image', 'zip'];
        this.allowTypes = ['image/jpg', 'image/png', 'image/jpeg', 'image/gif'];
        this.result = {code: -1, msg: '服务器尚未反应'};
        this.resolve = resolve;
        this.reject = reject;
        this.verify() && this.reader();
    }

    verify() {
        if (!this.allowTypes.includes(this.file.type)) {
            return AdminBase.warn('不支持的文件类型');
        }
        if (this.file.size === 0) {
            return AdminBase.warn('文件已破损');
        }
        return true;
    }

    reader() {
        const fileReader = new FileReader();
        let _this = this;
        fileReader.readAsDataURL(this.file);
        fileReader.onload = function (e) {
            let base64_url = e.target.result;
            $.ajax({
                url: '/upload/base64',
                type: 'post',
                data: {image: base64_url},
                headers: {'X-CSRF-TOKEN': AdminBase.csrf_token()},
                success: function (data) {
                    if (data.code === 0) {
                        _this.result = {code: 0, msg: '上传成功', url: data.data.path};
                        _this.resolve({default: _this.result.url, data: data.data});
                    } else {
                        _this.result = {code: data.code, msg: data.msg || '上传失败'};
                        _this.reject(_this.result.url);
                    }
                }
            });
        }
    }
}