package com.sdtool.webcore.rest;

import com.dySweetFishPlugin.sql.RMapUtils;
import com.sdtool.common.api.mall.DesignService;
import com.sdtool.common.base.BaseService;
import com.sdtool.common.datas.ERPHeader;
import com.sdtool.common.datas.HttpCode;
import com.sdtool.common.entity.design.DesignFont;
import com.sdtool.common.entity.design.DesignOrder;
import com.sdtool.common.entity.design.DesignTemplate;
import com.sdtool.common.entity.design.invoke.QueryBody;
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.source.PageFlipper;
import com.sweetfish.util.AutoLoad;
import org.apache.commons.lang3.StringUtils;
import org.rex.RMap;

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

@AutoLoad(false)
@Local
@RestService(name = "invoke", moduleid = 99, comment = "外部调用模块")
public class InvokeRest extends BaseService {
    @Resource
    private DesignService designService;

    @Resource(name = "property.invoke.whiteList")
    private String ipWhiteList;

    private boolean canAccessServer(String clientIp) {
        return Arrays.asList(ipWhiteList.split(";")).contains(clientIp);
    }

    private boolean canAccessClient(String cookie) {
        //当前仅判断存不存在...
        return StringUtils.isNotBlank(cookie);
    }

    @RestMapping(name = "queryDesignTemplates", auth = false, sort = 1, comment = "获取设计模板", methods = {"POST"})
    @WebApiBean(result = true, type = DesignTemplate.class)
    public CompletableFuture<RMap> queryDesignTemplates(
//            @RestParam(name = "params", comment = "搜索内容", required = false) RMap searchData,
//            @RestParam(name = "page", comment = "分页信息", required = false) PageFlipper pageFlipper,
//            @RestParam(name = "orderBy", comment = "排序", required = false) String orderBy,
            @RestBody(comment = "支持body传入") QueryBody queryBody,
            @RestParam(name = "&", comment = "登录用户，无需传入") ERPTokenUser currentUser,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode,
            @RestAddress(comment = "用户ip地址，不需传入") String clientIp) {
        return CompletableFuture.supplyAsync(
                () -> {
                    if (!canAccessServer(clientIp)) {
                        logger.info("invoke拒绝访问:" + clientIp);
                        return RMapUtils.error(HttpCode.BAD_REQUEST.value(), "无权限访问");
                    }

                    PageFlipper pageFlipper = queryBody.getPages();
                    RMap searchData = queryBody.getParams();
                    RMap params = new RMap();
                    if (searchData != null) {
                        params.putAll(searchData);
                    }
                    params.set("voidFlag", 0);

                    RetResult<List<DesignTemplate>> result = designService.queryDesignTemplates(params, pageFlipper, dataSourceId, Long.parseLong(supplierCode));
                    if (result.isSuccess())
                        return RMapUtils.successV2(result.getResult(), null, result.getPageFlipper());
                    else return RMapUtils.error(HttpCode.BAD_REQUEST.value(), result.getRetinfo());
                }, getExecutor()
        );
    }

    @RestMapping(name = "getDesignTemplate", auth = false, sort = 2, comment = "获取设计模板", methods = {"POST"})
    @WebApiBean(result = true, type = DesignTemplate.class)
    public CompletableFuture<RMap> getDesignTemplate(
            @RestParam(name = "id", comment = "id") long id,
            @RestParam(name = "&", comment = "登录用户，无需传入") ERPTokenUser currentUser,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode,
            @RestAddress(comment = "用户ip地址，不需传入") String clientIp) {
        return CompletableFuture.supplyAsync(
                () -> {
                    if (!canAccessServer(clientIp)) {
                        logger.info("invoke拒绝访问:" + clientIp);
                        return RMapUtils.error(HttpCode.BAD_REQUEST.value(), "无权限访问");
                    }
                    RetResult<DesignTemplate> result = designService.getDesignTemplateEdit(id, new RMap(), dataSourceId, Long.parseLong(supplierCode));
                    if (result.isSuccess())
                        return RMapUtils.successV2(result.getResult(), null, result.getPageFlipper());
                    else return RMapUtils.error(HttpCode.BAD_REQUEST.value(), result.getRetinfo());
                }, getExecutor()
        );
    }

    //仅有此接口完全无限制访问了
    //原因在于后台设计器和前台客户都用到这个借口了,然后又偷懒不想区分
    //算了,这个接口也没啥敏感数据
    @RestMapping(name = "getDesignFonts", auth = false, sort = 3, comment = "获取设计字体", methods = {"POST"})
    @WebApiBean(result = true, type = DesignFont.class)
    public CompletableFuture<RMap> getDesignFonts(
            @RestParam(name = "params", comment = "搜索内容", required = false) RMap searchData,
            @RestParam(name = "orderBy", comment = "排序", required = false) String orderBy,
            @RestParam(name = "&", comment = "登录用户，无需传入") ERPTokenUser currentUser,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode) {
        return CompletableFuture.supplyAsync(
                () -> {
                    RetResult<List<DesignFont>> result = designService.getDesignFonts(searchData, dataSourceId, Long.parseLong(supplierCode));
                    if (result.isSuccess())
                        return RMapUtils.successV2(result.getResult(), null, result.getPageFlipper());
                    else return RMapUtils.error(HttpCode.BAD_REQUEST.value(), result.getRetinfo());
                }, getExecutor()
        );
    }

    @RestMapping(name = "getPreViewTemplate", auth = false, sort = 20, comment = "传参获取设计模板,供前端预览", methods = {"POST"})
    @WebApiBean(result = true, type = DesignTemplate.class)
    public CompletableFuture<RMap> getPreViewTemplate(
            @RestParam(name = "id", comment = "id") long id,
            @RestParam(name = "params", comment = "可变参数", required = false) RMap params,
            @RestParam(name = "outerSessionId", comment = "外部网站的sessionId") String outerSessionId,
            @RestParam(name = "&", comment = "登录用户，无需传入") ERPTokenUser currentUser,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode,
            @RestCookie(name = "ow") String clientCookie) {
        return CompletableFuture.supplyAsync(
                () -> {
                    //25-02-06 他们不限制了
//                    if (!canAccessClient(clientCookie)) {
//                        return RMapUtils.error(HttpCode.BAD_REQUEST.value(), "无权限访问");
//                    }
                    RetResult<DesignTemplate> result = designService.getDesignTemplateEdit(id, params, outerSessionId, dataSourceId, Long.parseLong(supplierCode));
                    if (result.isSuccess())
                        return RMapUtils.successV2(result.getResult(), null, result.getPageFlipper());
                    else return RMapUtils.error(HttpCode.BAD_REQUEST.value(), result.getRetinfo());
                }, getExecutor()
        );
    }

    @RestMapping(name = "newDesignOrder", auth = false, sort = 21, comment = "生成设计订单", methods = {"POST"})
    @WebApiBean(result = true, type = DesignOrder.class)
    public CompletableFuture<RMap> newDesignOrder(
            @RestParam(name = "outerSessionId", comment = "外部网站的sessionId") String outerSessionId,
            @RestBody(comment = "前端处理过的svg") String svgContent,
            @RestParam(name = "&", comment = "登录用户，无需传入") ERPTokenUser currentUser,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode,
            @RestCookie(name = "ow") String clientCookie) {
        return CompletableFuture.supplyAsync(
                () -> {
                    //25-02-06 他们不限制了
//                    if (!canAccessClient(clientCookie)) {
//                        return RMapUtils.error(HttpCode.BAD_REQUEST.value(), "无权限访问");
//                    }
                    RetResult<DesignOrder> result = designService.newDesignOrder(outerSessionId, svgContent, dataSourceId, Long.parseLong(supplierCode), currentUser);
                    if (result.isSuccess())
                        return RMapUtils.successV2(result.getResult(), null, result.getPageFlipper());
                    else return RMapUtils.error(HttpCode.BAD_REQUEST.value(), result.getRetinfo());
                }, getExecutor()
        );
    }


    @RestMapping(name = "downloadDesignPDF", auth = false, sort = 22, comment = "下载设计订单文件", methods = {"POST"})
    @WebApiBean(result = true, type = DesignOrder.class)
    public CompletableFuture<RMap> downloadDesignPDF(
            @RestParam(name = "outerSessionId", comment = "外部网站的sessionId") String outerSessionId,
            @RestHeader(name = ERPHeader.HTTPHEADER_DATASOURCE) String dataSourceId,
            @RestHeader(name = ERPHeader.HTTPHEADER_SUPPLIER) String supplierCode,
            @RestCookie(name = "ow") String clientCookie) {
        return CompletableFuture.supplyAsync(
                () -> {
                    //25-02-06 他们不限制了
//                    if (!canAccessClient(clientCookie)) {
//                        return RMapUtils.error(HttpCode.BAD_REQUEST.value(), "无权限访问");
//                    }
                    RetResult<DesignOrder> result = designService.downloadDesignPDF(outerSessionId, dataSourceId, Long.parseLong(supplierCode));
                    if (result.isSuccess())
                        return RMapUtils.successV2(result.getResult().getPdfDownloadUrl(), null, null);
                    else if (result.getRetcode() == 201) {
                        //生成中
                        return RMapUtils.error(201, result.getRetinfo());
                    } else {
                        return RMapUtils.error(HttpCode.BAD_REQUEST.value(), result.getRetinfo());
                    }
                }, getExecutor()
        );
    }
}
