import http from "@ohos:net.http";
import { HttpConfig } from "@normalized:N&&&@yic/http/src/main/ets/core/HttpConfig&1.0.1";
import { RequestBody } from "@normalized:N&&&@yic/http/src/main/ets/requestbody/RequestBody&1.0.1";
/**
 * @ProjectName : HarmonyUtilSdk
 * @FileName : DefaultRequestBody
 * @Author : yic
 * @Time : 2024/6/20 16:36
 * @Description : 文件描述
 */
export class DefaultRequestBody extends RequestBody {
    protected call(): Promise<http.HttpResponse> {
        return new Promise<http.HttpResponse>((resolve, reject) => {
            let url = this.getUrl();
            let param = '';
            Object.keys(this.getParam()).forEach((key) => {
                if (param.length > 0) {
                    param += "&";
                }
                param += `${key}=${this.getParam()[key]}`;
            });
            if (param.length > 0) {
                url += `?${param}`;
            }
            if (!this.getHeader()['Content-Type']) {
                this.setHeader('Content-Type', 'application/x-www-form-urlencoded');
            }
            http.createHttp().request(url, {
                method: this.getMethod(),
                header: { ...this.getHeader() },
                connectTimeout: HttpConfig.getInstance().getConnectTimeout(),
                readTimeout: HttpConfig.getInstance().getReadTimeout()
            }).then((httpResponse) => {
                if (this.isCancel()) {
                    console.info('canceled', this.getUrlWithParam());
                    HttpConfig.getInstance().getTaskDispatch().done(this);
                    return;
                }
                let response: http.HttpResponse = httpResponse;
                if (this.getMethod() === http.RequestMethod.GET ||
                    this.getMethod() === http.RequestMethod.POST) {
                    response = httpResponse;
                }
                else if (httpResponse.responseCode >= 200 && httpResponse.responseCode <= 299) {
                    response = {
                        result: httpResponse.result,
                        resultType: http.HttpDataType.OBJECT,
                        responseCode: httpResponse.responseCode,
                        header: httpResponse.header,
                        cookies: httpResponse.cookies
                    };
                }
                else {
                    response = httpResponse;
                }
                resolve(response);
            }).catch((err) => {
                reject(err);
            });
        });
    }
}
