package com.sdtool.webcore.rest;

import com.sdtool.common.api.ConfigService;
import com.sdtool.common.base.BaseService;
import com.sdtool.common.datas.ERPHeader;
import com.sdtool.common.datas.HttpCode;
import com.sdtool.common.entity.base.InvokeCallParams;
import com.sdtool.common.entity.base.InvokeCallResult;
import com.sdtool.common.entity.site.ERPTokenUser;
import com.sweetfish.net.http.*;
import com.sweetfish.service.Local;
import com.sweetfish.service.RetResult;
import com.sweetfish.util.AutoLoad;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

@AutoLoad(false)
@Local
@RestService(name = "site", comment = "网站模块")
public class SiteRest extends BaseService {

    @Resource
    ConfigService configService;

    @RestMapping(name = "callSite", sort = 1, comment = "调用网站配置脚本", methods = {"GET", "POST"})
    @WebApiFile(fileName = "siteRest.xml")
    public CompletableFuture<InvokeCallResult> callSite(
            @RestParam(name = "&", comment = "登录用户，无需传入") ERPTokenUser currentUser,
            @RestBody(comment = "提交数据") InvokeCallParams callParams,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode) {
        return CompletableFuture.supplyAsync(
                () -> {
                    RetResult<InvokeCallResult> infoResult = configService.callConfig(callParams, currentUser, dataSourceId, Long.parseLong(supplierCode));
                    if (infoResult.isSuccess()) {
                        return infoResult.getResult();
                    } else {
                        if (infoResult.getRetcode() == HttpCode.FORBIDDEN.value()) {
                            return InvokeCallResult.error(HttpCode.FORBIDDEN.value(), infoResult.getRetinfo());
                        }
                        return InvokeCallResult.error(HttpCode.BAD_REQUEST.value(), infoResult.getRetinfo());
                    }
                }, getExecutor()
        );
    }
}
