import { h } from "@stencil/core";
export class Upload {
    /** 上传地址。设置后启用自动上传；未设置时文件以 ready 状态抛出，由消费方自行上传 */
    action;
    /** 多选 */
    multiple = false;
    /** 接受的文件类型 */
    accept;
    /** 是否禁用 */
    disabled = false;
    /** 最大上传数量 */
    limit;
    /** 是否拖拽上传 */
    drag = false;
    /** 上传字段名 */
    name = 'file';
    /** 额外的请求头 */
    headers;
    /** 额外的表单数据 */
    data;
    /** 是否携带凭证（cookie） */
    withCredentials = false;
    /** 上传前钩子，返回 false / Promise<false> 则取消上传 */
    beforeUpload;
    fileList = [];
    isDragover = false;
    hbChange;
    hbSuccess;
    hbError;
    inputRef;
    handleClick = () => {
        if (!this.disabled)
            this.inputRef?.click();
    };
    handleChange = (e) => {
        const target = e.target;
        if (target.files)
            this.handleFiles(target.files);
        target.value = '';
    };
    handleFiles = async (files) => {
        for (let i = 0; i < files.length; i++) {
            if (this.limit && this.fileList.length >= this.limit)
                break;
            const file = files[i];
            if (this.beforeUpload) {
                try {
                    const ok = await this.beforeUpload(file);
                    if (!ok)
                        continue;
                }
                catch {
                    continue;
                }
            }
            const uf = {
                name: file.name,
                size: file.size,
                type: file.type,
                status: this.action ? 'uploading' : 'ready',
                progress: 0,
            };
            this.fileList = [...this.fileList, uf];
            this.hbChange.emit(this.fileList);
            if (this.action) {
                this.realUpload(file, uf);
            }
        }
    };
    /** 真实上传：FormData + XHR，带进度回调 */
    realUpload = (file, uf) => {
        const xhr = new XMLHttpRequest();
        const formData = new FormData();
        formData.append(this.name, file);
        if (this.data) {
            Object.entries(this.data).forEach(([k, v]) => formData.append(k, v));
        }
        xhr.upload.onprogress = (e) => {
            if (e.lengthComputable) {
                uf.progress = Math.round((e.loaded / e.total) * 100);
                this.fileList = [...this.fileList];
            }
        };
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                uf.status = 'success';
                uf.response = this.parseResponse(xhr.response);
                this.fileList = [...this.fileList];
                this.hbSuccess.emit(uf);
            }
            else {
                uf.status = 'error';
                this.fileList = [...this.fileList];
                this.hbError.emit(uf);
            }
        };
        xhr.onerror = () => {
            uf.status = 'error';
            this.fileList = [...this.fileList];
            this.hbError.emit(uf);
        };
        xhr.open('POST', this.action, true);
        xhr.withCredentials = this.withCredentials;
        if (this.headers) {
            Object.entries(this.headers).forEach(([k, v]) => xhr.setRequestHeader(k, v));
        }
        xhr.send(formData);
    };
    parseResponse(raw) {
        if (typeof raw !== 'string')
            return raw;
        try {
            return JSON.parse(raw);
        }
        catch {
            return raw;
        }
    }
    handleRemove = (index) => {
        const next = [...this.fileList];
        next.splice(index, 1);
        this.fileList = next;
        this.hbChange.emit(next);
    };
    handleDrop = (e) => {
        e.preventDefault();
        this.isDragover = false;
        if (e.dataTransfer?.files)
            this.handleFiles(e.dataTransfer.files);
    };
    handleDragOver = (e) => {
        e.preventDefault();
        this.isDragover = true;
    };
    handleDragLeave = () => {
        this.isDragover = false;
    };
    formatSize(bytes) {
        if (bytes < 1024)
            return bytes + ' B';
        if (bytes < 1024 * 1024)
            return (bytes / 1024).toFixed(1) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
    }
    renderStatus(file) {
        if (file.status === 'uploading') {
            return h("span", { class: "hb-upload__item-progress" }, typeof file.progress === 'number' ? `${file.progress}%` : '');
        }
        if (file.status === 'success')
            return h("span", { class: "hb-upload__item-status hb-upload__item-status--success" }, "\u2713");
        if (file.status === 'error')
            return h("span", { class: "hb-upload__item-status hb-upload__item-status--error" }, "\u2715");
        return null;
    }
    render() {
        return (h("div", { key: 'a83f9b8d0fd3a0cc618ff33bea2fd35d96b32071', class: "hb-upload" }, h("div", { key: '42f8ae299086ace94524529980d2acdff0abeb16', class: {
                'hb-upload__trigger': true,
                'hb-upload__trigger--drag': this.drag,
                'hb-upload__trigger--dragover': this.isDragover,
                'hb-upload__trigger--disabled': this.disabled,
            }, onClick: this.handleClick, onDrop: this.drag ? this.handleDrop : undefined, onDragOver: this.drag ? this.handleDragOver : undefined, onDragLeave: this.drag ? this.handleDragLeave : undefined }, this.drag ? h("span", null, "\u5C06\u6587\u4EF6\u62D6\u5230\u6B64\u5904\uFF0C\u6216\u70B9\u51FB\u4E0A\u4F20") : h("slot", null, h("button", { type: "button", class: "hb-upload__btn" }, "\u70B9\u51FB\u4E0A\u4F20"))), h("input", { key: '65a98112cda506b0244451b6ca7b00a200306e00', type: "file", ref: (el) => {
                this.inputRef = el;
            }, multiple: this.multiple, accept: this.accept, disabled: this.disabled, style: { display: 'none' }, onChange: this.handleChange }), this.fileList.length > 0 && (h("ul", { key: 'e8f768dc92d273dc81a7a62f08eefd1c3f185251', class: "hb-upload__list" }, this.fileList.map((file, i) => (h("li", { class: { 'hb-upload__item': true, [`hb-upload__item--${file.status}`]: true } }, h("span", { class: "hb-upload__item-name" }, file.name), h("span", { class: "hb-upload__item-size" }, this.formatSize(file.size)), this.renderStatus(file), h("span", { class: "hb-upload__item-remove", onClick: () => this.handleRemove(i) }, "\u00D7"))))))));
    }
    static get is() { return "hb-upload"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() {
        return {
            "$": ["upload.css"]
        };
    }
    static get styleUrls() {
        return {
            "$": ["upload.css"]
        };
    }
    static get properties() {
        return {
            "action": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u4E0A\u4F20\u5730\u5740\u3002\u8BBE\u7F6E\u540E\u542F\u7528\u81EA\u52A8\u4E0A\u4F20\uFF1B\u672A\u8BBE\u7F6E\u65F6\u6587\u4EF6\u4EE5 ready \u72B6\u6001\u629B\u51FA\uFF0C\u7531\u6D88\u8D39\u65B9\u81EA\u884C\u4E0A\u4F20"
                },
                "getter": false,
                "setter": false,
                "attribute": "action",
                "reflect": false
            },
            "multiple": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u591A\u9009"
                },
                "getter": false,
                "setter": false,
                "attribute": "multiple",
                "reflect": false,
                "defaultValue": "false"
            },
            "accept": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u63A5\u53D7\u7684\u6587\u4EF6\u7C7B\u578B"
                },
                "getter": false,
                "setter": false,
                "attribute": "accept",
                "reflect": false
            },
            "disabled": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u662F\u5426\u7981\u7528"
                },
                "getter": false,
                "setter": false,
                "attribute": "disabled",
                "reflect": false,
                "defaultValue": "false"
            },
            "limit": {
                "type": "number",
                "mutable": false,
                "complexType": {
                    "original": "number",
                    "resolved": "number",
                    "references": {}
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u6700\u5927\u4E0A\u4F20\u6570\u91CF"
                },
                "getter": false,
                "setter": false,
                "attribute": "limit",
                "reflect": false
            },
            "drag": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u662F\u5426\u62D6\u62FD\u4E0A\u4F20"
                },
                "getter": false,
                "setter": false,
                "attribute": "drag",
                "reflect": false,
                "defaultValue": "false"
            },
            "name": {
                "type": "string",
                "mutable": false,
                "complexType": {
                    "original": "string",
                    "resolved": "string",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u4E0A\u4F20\u5B57\u6BB5\u540D"
                },
                "getter": false,
                "setter": false,
                "attribute": "name",
                "reflect": false,
                "defaultValue": "'file'"
            },
            "headers": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "Record<string, string>",
                    "resolved": "{ [x: string]: string; }",
                    "references": {
                        "Record": {
                            "location": "global",
                            "id": "global::Record"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u989D\u5916\u7684\u8BF7\u6C42\u5934"
                },
                "getter": false,
                "setter": false
            },
            "data": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "Record<string, string>",
                    "resolved": "{ [x: string]: string; }",
                    "references": {
                        "Record": {
                            "location": "global",
                            "id": "global::Record"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u989D\u5916\u7684\u8868\u5355\u6570\u636E"
                },
                "getter": false,
                "setter": false
            },
            "withCredentials": {
                "type": "boolean",
                "mutable": false,
                "complexType": {
                    "original": "boolean",
                    "resolved": "boolean",
                    "references": {}
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": "\u662F\u5426\u643A\u5E26\u51ED\u8BC1\uFF08cookie\uFF09"
                },
                "getter": false,
                "setter": false,
                "attribute": "with-credentials",
                "reflect": false,
                "defaultValue": "false"
            },
            "beforeUpload": {
                "type": "unknown",
                "mutable": false,
                "complexType": {
                    "original": "(file: File) => boolean | Promise<boolean>",
                    "resolved": "(file: File) => boolean | Promise<boolean>",
                    "references": {
                        "File": {
                            "location": "global",
                            "id": "global::File"
                        },
                        "Promise": {
                            "location": "global",
                            "id": "global::Promise"
                        }
                    }
                },
                "required": false,
                "optional": true,
                "docs": {
                    "tags": [],
                    "text": "\u4E0A\u4F20\u524D\u94A9\u5B50\uFF0C\u8FD4\u56DE false / Promise<false> \u5219\u53D6\u6D88\u4E0A\u4F20"
                },
                "getter": false,
                "setter": false
            },
            "fileList": {
                "type": "unknown",
                "mutable": true,
                "complexType": {
                    "original": "UploadFile[]",
                    "resolved": "UploadFile[]",
                    "references": {
                        "UploadFile": {
                            "location": "local",
                            "path": "/Users/vscoderwhy/Desktop/product/web-common/huibo-ui/src/components/Upload/Upload.tsx",
                            "id": "src/components/Upload/Upload.tsx::UploadFile"
                        }
                    }
                },
                "required": false,
                "optional": false,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "getter": false,
                "setter": false,
                "defaultValue": "[]"
            }
        };
    }
    static get states() {
        return {
            "isDragover": {}
        };
    }
    static get events() {
        return [{
                "method": "hbChange",
                "name": "hbChange",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "UploadFile[]",
                    "resolved": "UploadFile[]",
                    "references": {
                        "UploadFile": {
                            "location": "local",
                            "path": "/Users/vscoderwhy/Desktop/product/web-common/huibo-ui/src/components/Upload/Upload.tsx",
                            "id": "src/components/Upload/Upload.tsx::UploadFile"
                        }
                    }
                }
            }, {
                "method": "hbSuccess",
                "name": "hbSuccess",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "UploadFile",
                    "resolved": "UploadFile",
                    "references": {
                        "UploadFile": {
                            "location": "local",
                            "path": "/Users/vscoderwhy/Desktop/product/web-common/huibo-ui/src/components/Upload/Upload.tsx",
                            "id": "src/components/Upload/Upload.tsx::UploadFile"
                        }
                    }
                }
            }, {
                "method": "hbError",
                "name": "hbError",
                "bubbles": true,
                "cancelable": true,
                "composed": true,
                "docs": {
                    "tags": [],
                    "text": ""
                },
                "complexType": {
                    "original": "UploadFile",
                    "resolved": "UploadFile",
                    "references": {
                        "UploadFile": {
                            "location": "local",
                            "path": "/Users/vscoderwhy/Desktop/product/web-common/huibo-ui/src/components/Upload/Upload.tsx",
                            "id": "src/components/Upload/Upload.tsx::UploadFile"
                        }
                    }
                }
            }];
    }
}
//# sourceMappingURL=Upload.js.map
