package com.ichangzuo.system.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ichangzuo.common.result.AjaxResult;
import com.ichangzuo.common.result.Result;

import com.ichangzuo.config.AlipayConfig;
import com.ichangzuo.config.WxpayConfig;
import com.ichangzuo.system.model.entity.Account;
import com.ichangzuo.system.model.entity.Order;
import com.ichangzuo.system.model.entity.User;
import com.ichangzuo.system.service.impl.OrderServiceImpl;

import com.ichangzuo.system.service.impl.StatisticsServiceImpl;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.app.AppServiceExtension;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.h5.H5Service;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;

import static com.ichangzuo.common.result.ResultCode.SUCCESS;

//@Setter
@Service
@RequiredArgsConstructor
public class PayService {
    private static final Logger log = LoggerFactory.getLogger(PayService.class);
    private final UserService userService;
    private final OrderServiceImpl orderService;
    private final StatisticsServiceImpl statisticsService;

    private static HttpClientConnectionManager getHttpClientConnectionManager() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        return PoolingHttpClientConnectionManagerBuilder.create()
                .setSSLSocketFactory(getSslConnectionSocketFactory())
                .build();
    }

    /**
     * 支持SSL
     *
     * @return SSLConnectionSocketFactory
     */
    private static SSLConnectionSocketFactory getSslConnectionSocketFactory() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, s) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    }

//    @Test
    public void httpClient5SslConnect() {
        //创建post请求对象
        String url = "https://buy.itunes.apple.com/verifyReceipt";
        HttpPost httpPost = new HttpPost(url);
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        try (CloseableHttpClient httpClient = httpClientBuilder.setConnectionManager(getHttpClientConnectionManager()).build()) {
            httpPost.setEntity(new StringEntity("{[\"receipt-data\":\"\"]}", StandardCharsets.UTF_8));
            //使用CloseableHttpClient发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
//            System.out.println(jsonObject);
//            log.info(body);
            // TODO 获取页面内容实现
        } catch (IOException | ParseException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        }
    }

    public JSONObject appleOrderFinis(String receipt, String isSandbox,
                                  String user,String password, String order) {
        JSONObject json = new JSONObject();

        AjaxResult result = verifyAppleReceipt(receipt, isSandbox.equals("1"));
        Integer code = (Integer) result.get(AjaxResult.CODE_TAG);
        if (code != 200) {
            String msg = (String) result.get(AjaxResult.MSG_TAG);
            if (msg.equals("couldn't connect to host"))
                json.put("result", -2);
            else
                json.put("result", 0);

            json.put("errMsg", msg);
            return json;
        }

        User u = userService.verifyUser(user, password);
        if (u == null) {
            json.put("result", -1);
            return json;
        }

        Integer coin = orderFinished(order, 5.0 / 6);
        if (coin < 0) {
            json.put("result", 0);
            return json;
        }

        json.put("result", 1);
        json.put("coin", coin);

        return json;
    }

    public AjaxResult verifyAppleReceipt(String receipt, boolean isSanbox) {
        String url = isSanbox ? "https://sandbox.itunes.apple.com/verifyReceipt"
                            : "https://buy.itunes.apple.com/verifyReceipt";
        HttpPost httpPost = new HttpPost(url);
        String errMsg = null;
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        try (CloseableHttpClient httpClient = httpClientBuilder.setConnectionManager(getHttpClientConnectionManager()).build()) {
            JSONObject pack = new JSONObject();
            pack.put("receipt-data", receipt);

            httpPost.setEntity(new StringEntity(pack.toJSONString(), StandardCharsets.UTF_8));
            //使用CloseableHttpClient发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String sBody = EntityUtils.toString(entity, "UTF-8");
            JSONObject jsonObject = JSON.parseObject(sBody);

            log.info(jsonObject.toJSONString());

            if(jsonObject.containsKey("status")){
                int status = jsonObject.getIntValue("status");

                if(status==21007){
                    return verifyAppleReceipt(receipt, true);
                }
                else if(status==0){
                    return AjaxResult.success(jsonObject);
                }
                else{
                    errMsg = String.valueOf(status);
                }
            }
        } catch (IOException | ParseException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
            errMsg = e.getMessage();
        }

        return AjaxResult.error(errMsg);
    }

    public String getAliPayAppInfo(String money, String order) {
        int num = (int) (Double.parseDouble(money) * 100);

        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("支付" + money + "元兑换" + num + "唱作音符");
        model.setSubject("唱作音符充值兑换");
        model.setOutTradeNo(order);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(money);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notifyUrl());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = AlipayConfig.getClient(AlipayConfig.APP).sdkExecute(request);// .getAlipayAppClient().sdkExecute(request);
            log.info(response.getBody()); //就是orderString 可以直接给客户端请求，无需再做处理。
            return response.getBody();
        }
        catch (AlipayApiException e){
            e.printStackTrace();
        }

        return null;
    }

    public Result<?> getAliPayPageInfo(String money, String order) {
        int num = (int) (Double.parseDouble(money) * 100);

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();

        model.setBody("支付" + money + "元兑换" + num + "唱作音符");
        // 设置订单标题
        model.setSubject("唱作音符充值兑换");
        // 设置商户订单号
        model.setOutTradeNo(order);
        // 设置订单总金额
        model.setTotalAmount(money);
        // 设置产品码
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        // 设置PC扫码支付的方式
        model.setQrPayMode("2");
        // 设置商户自定义二维码宽度
//        model.setQrcodeWidth(100L);
        // 设置请求后页面的集成方式
        model.setIntegrationType("PCWEB");
        // 设置页面超时
        model.setTimeoutExpress("30m");

        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notifyUrl());
        request.setReturnUrl(AlipayConfig.returnUrl());

        try {
            AlipayTradePagePayResponse response = AlipayConfig.getClient(AlipayConfig.WEB).pageExecute(request, "POST");
//            String pageRedirectionData = response.getBody();
//            System.out.println(pageRedirectionData);

            return Result.success(response.getBody());
        }
        catch (AlipayApiException e){
            e.printStackTrace();
        }

        return Result.failed("支付调用失败");
    }

    public Result<?> getAliPayWapInfo(String money, String order) {
        int num = (int) (Double.parseDouble(money) * 100);

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();

        model.setBody("支付" + money + "元兑换" + num + "唱作音符");
        // 设置订单标题
        model.setSubject("唱作音符充值兑换");
        // 设置商户订单号
        model.setOutTradeNo(order);
        // 设置订单总金额
        model.setTotalAmount(money);
        // 设置产品码
        model.setProductCode("QUICK_WAP_WAY");
        // 设置PC扫码支付的方式
//        model.setQrPayMode("2");
        // 设置商户自定义二维码宽度
//        model.setQrcodeWidth(100L);
        // 设置请求后页面的集成方式
//        model.setIntegrationType("PCWEB");
        // 设置页面超时
        model.setTimeoutExpress("30m");

        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notifyUrl());
        request.setReturnUrl(AlipayConfig.returnUrl());
        try {
            AlipayTradeWapPayResponse response = AlipayConfig.getClient(AlipayConfig.WEB).pageExecute(request, "POST");// .getAlipayWebClient().pageExecute(request, "POST");
            String pageRedirectionData = response.getBody();
            System.out.println(pageRedirectionData);

            return Result.success(response.getBody());
        }
        catch (AlipayApiException e){
            e.printStackTrace();
        }

        return Result.failed("支付调用失败");
    }

    public AjaxResult handleAlipayAppNotify(HttpServletRequest request) {
        String errMsg = null;

        try {
            //将异步通知中收到的待验证所有参数都存放到map中
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();

            for (String name : requestParams.keySet()) {
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用。
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

//            System.out.println(params);

            //调用SDK验证签名
            boolean  signVerified = AlipayConfig.checkSignature(params);
            if(signVerified){
                String status = params.get("trade_status");
                if(Objects.equals(status, "TRADE_FINISHED") || Objects.equals(status, "TRADE_SUCCESS")) {
                    String out_trade_no = params.get("out_trade_no");
                    log.info("alipayNotify: " + out_trade_no);
                    return AjaxResult.success("操作成功", out_trade_no);
                }
                else{
                    errMsg = status;
                }
            }
            else{
                errMsg = "验签失败";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            errMsg = e.getMessage();
        }

        log.error(errMsg);
        return AjaxResult.error(errMsg);
    }

    public String getWxPayAppInfo(String money, String order) {

        int num = (int) (Double.parseDouble(money) * 100);
        String errMsg = null;
        AppServiceExtension service = new AppServiceExtension.Builder().config(WxpayConfig.getWxpayConfig(WxpayConfig.WX_APP)).build();

        // 跟之前下单示例一样，填充预下单参数
        com.wechat.pay.java.service.payments.app.model.PrepayRequest request = new com.wechat.pay.java.service.payments.app.model.PrepayRequest();
        com.wechat.pay.java.service.payments.app.model.Amount amount = new com.wechat.pay.java.service.payments.app.model.Amount();
        amount.setTotal(num);
        request.setAmount(amount);
        request.setAppid(WxpayConfig.appAppId);
        request.setMchid(WxpayConfig.appMerchantId);

        request.setDescription("支付" + money + "元购买" + num + "唱作音符");
        request.setNotifyUrl(WxpayConfig.notifyUrl(WxpayConfig.WX_APP));
        request.setOutTradeNo(order);
        // response包含了调起支付所需的所有参数，可直接用于前端调起支付
        com.wechat.pay.java.service.payments.app.model.PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
//        PrepayResponse response = service.prepay(request);
        return JSON.toJSONString(response);
    }

    public Result<?> getWxPayPageInfo(String money, String order) {
        int num = (int) (Double.parseDouble(money) * 100);
        String errMsg = null;
        NativePayService service = new NativePayService.Builder().config(WxpayConfig.getWxpayConfig(WxpayConfig.WX_WEB)).build();

        // 跟之前下单示例一样，填充预下单参数
        com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest request = new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
        com.wechat.pay.java.service.payments.nativepay.model.Amount amount = new com.wechat.pay.java.service.payments.nativepay.model.Amount();
        amount.setTotal(num);
        request.setAmount(amount);
        request.setAppid(WxpayConfig.webAppId);
        request.setMchid(WxpayConfig.webMerchantId);
        request.setDescription("支付" + money + "元购买" + num + "唱作音符");
        request.setNotifyUrl(WxpayConfig.notifyUrl(WxpayConfig.WX_WEB));
        request.setOutTradeNo(order);
        try {
            // response包含了调起支付所需的所有参数，可直接用于前端调起支付
            com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse response = service.prepay(request);
//            System.out.println(response.getCodeUrl());
            return Result.success(response.getCodeUrl());
        }
        catch (Exception e){
            e.printStackTrace();
        }

        return Result.failed("支付调用失败");
    }

    public Result<?> getWxPayWapInfo(String money, String order) {
        int num = (int) (Double.parseDouble(money) * 100);
        String errMsg = null;
        H5Service service = new H5Service.Builder().config(WxpayConfig.getWxpayConfig(WxpayConfig.WX_WEB)).build();

        // 跟之前下单示例一样，填充预下单参数
        com.wechat.pay.java.service.payments.h5.model.PrepayRequest request = new com.wechat.pay.java.service.payments.h5.model.PrepayRequest();
        com.wechat.pay.java.service.payments.h5.model.Amount amount = new com.wechat.pay.java.service.payments.h5.model.Amount();
        amount.setTotal(num);
        request.setAmount(amount);
        request.setAppid(WxpayConfig.webAppId);
        request.setMchid(WxpayConfig.webMerchantId);
        request.setDescription("支付" + money + "元购买" + num + "唱作音符");
        request.setNotifyUrl(WxpayConfig.notifyUrl(WxpayConfig.WX_WEB));
        request.setOutTradeNo(order);

        com.wechat.pay.java.service.payments.h5.model.SceneInfo sceneInfo = new com.wechat.pay.java.service.payments.h5.model.SceneInfo();
        sceneInfo.setPayerClientIp("");
        com.wechat.pay.java.service.payments.h5.model.H5Info h5Info = new com.wechat.pay.java.service.payments.h5.model.H5Info();
        h5Info.setType("Wap");
        sceneInfo.setH5Info(h5Info);
        request.setSceneInfo(sceneInfo);

        try {
            // response包含了调起支付所需的所有参数，可直接用于前端调起支付
            com.wechat.pay.java.service.payments.h5.model.PrepayResponse response = service.prepay(request);
//            System.out.println(response.getCodeUrl());
            return Result.success(response.getH5Url());
        }
        catch (Exception e){
            e.printStackTrace();
        }

        return Result.failed("支付调用失败");
    }

    public void handleWxpayNotify(HttpServletRequest request, HttpServletResponse response, int type) {
        String errMsg = null;

        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name	= enumeration.nextElement();
            if( name.contains("Wechatpay-") ) {
                String value = request.getHeader(name);
                headerMap.put(name, value);
//                System.out.println(name + ":" + value);
            }
        }

        try {
            //获取支付宝POST过来反馈信息
            BufferedReader bufr = new BufferedReader(new InputStreamReader(request.getInputStream(),
                    StandardCharsets.UTF_8));
            StringBuilder requestBody = new StringBuilder();
            String temp = "";
            while ((temp = bufr.readLine()) != null) {
                requestBody.append(temp);
            }
            bufr.close();

//            System.out.println(requestBody);

//            if(true) {
//                throw new RuntimeException();
//            }

        // 构造 RequestParam
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(headerMap.get("Wechatpay-Serial"))
                    .nonce(headerMap.get("Wechatpay-Nonce"))
                    .signature(headerMap.get("Wechatpay-Signature"))
                    .timestamp(headerMap.get("Wechatpay-Timestamp"))
//                    .serialNumber(request.getHeader("Wechatpay-Serial"))
//                    .nonce(request.getHeader("Wechatpay-Nonce"))
//                    .signature(request.getHeader("Wechatpay-Signature"))
//                    .timestamp(request.getHeader("Wechatpay-Timestamp"))
                    .body(requestBody.toString())
                    .build();

            // 初始化 NotificationParser
            NotificationParser parser = new NotificationParser((NotificationConfig) WxpayConfig.getWxpayConfig(type));

            // 以支付通知回调为例，验签、解密并转换成 Transaction
            Transaction transaction = parser.parse(requestParam, Transaction.class);
            Transaction.TradeStateEnum status = transaction.getTradeState();
            if(status==Transaction.TradeStateEnum.SUCCESS) {
                String out_trade_no = transaction.getOutTradeNo();
//                System.out.println("wxpayNotify: " + out_trade_no);
                orderFinished(out_trade_no, 1.0);

                response.setStatus(HttpStatus.OK.value());
            }
            else{
                errMsg = transaction.getTradeStateDesc();
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            errMsg = e.getMessage();
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
        } catch (IOException e) {

            errMsg = e.getMessage();
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

        log.error(errMsg);
    }

    public Result<?> getWebOrderInfo(Long userId, String payType, String amount){
        String orderNo = orderService.generatorOrderNo(userId, payType);

        Result<?> result;
        if(Objects.equals(payType, "alipay")) {
            result = getAliPayPageInfo(amount, orderNo);
        }
        else if(Objects.equals(payType, "ali_h5")) {
            result = getAliPayWapInfo(amount, orderNo);
        }
        else if(Objects.equals(payType, "wxpay")){
            result = getWxPayPageInfo(amount, orderNo);
        }
        else if(Objects.equals(payType, "wx_h5")){
            result = getWxPayWapInfo(amount, orderNo);
        }
        else {
            return Result.failed("无效的支付方式");
        }

        if(!Objects.equals(result.getCode(), SUCCESS.getCode()))
            return result;

        if(!orderService.createNewOrder(orderNo, amount)){
            return Result.failed("创建订单失败");
        }

        Map<String, String> param = new HashMap<>();
        param.put("order", orderNo);
        param.put("resp", (String) result.getData());

        return Result.success(param);
    }

    public JSONObject getAppOrderInfo(String username, String password, String type, String money){
        JSONObject resp = new JSONObject();

        User user = userService.verifyUser(username, password);
        if(user==null){
            resp.put("result", -1);
//          resp.put("return_msg", "用户信息异常");
            return resp;
        }

        String orderNo = orderService.generatorOrderNo(user.getId(), type);

        String info = null;
        if("PGSD_AC".equals(type) || "PGSD".equals(type)){
            if(Integer.parseInt(money) % 6 != 0) {
                resp.put("result", 0);
                return resp;
            }
        }
        else {
            if ("ali_ad".equals(type)) {
                info = getAliPayAppInfo(money, orderNo);
            } else if ("wx_ad".equals(type)) {
                info = getWxPayAppInfo(money, orderNo);
            }

            if (info == null) {
                resp.put("result", 0);
                return resp;
            }

            resp.put("prepayInfo", info);
        }

        if(!orderService.createNewOrder(orderNo, money)){
            resp.put("result", 0);
            return resp;
        }

        resp.put("result", 1);
        resp.put("order", orderNo);

        return resp;
    }

    public Integer orderFinished(String orderNo, Double discount){
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNo));
        if(order==null)
            return -1;

        if(order.getState()==1) //重复完成
            return 0;

        Integer nowTime = (int)(System.currentTimeMillis()/1000);
        order.setState(1);
        order.setEndtime(nowTime);
        if(!orderService.updateById(order))
            return -2;

        Double coin = order.getMoney();
        Integer notes = (int) (coin * discount * 100);
        String payway = order.getPayway();
        int iClient = switch (payway){
            case "wxpay", "alipay", "ali_h5", "wx_h5" -> 5;
            case "wx_ad", "ali_ad" -> 3;
            case "PGSD_AC", "PGSD" -> 4;
            default -> -1;
        };

        if(iClient>0) {
            statisticsService.statistics(iClient, "recharge", notes);
        }

        if(!userService.addNotes(order.getUserId(), notes, nowTime))
            return -3;

        return notes;
    }

    public JSONObject orderCheck(String username, String password, String orderNo){
        JSONObject resp = new JSONObject();

        User user = userService.verifyUser(username, password);
        if(user==null){
            resp.put("result", -1);
            return resp;
        }

        Order order = orderService.getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNumber, orderNo)
                .eq(Order::getUserId, user.getId()));
        if(order==null) {
            resp.put("result", -2);
            return resp;
        }

        Account account = userService.getAccountById(user.getId());
        if(account!=null)
            resp.put("integral", account.getIntegral());

        resp.put("result", order.getState());
        return resp;
    }
}
