package com.jwipc.shopping.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jwipc.exception.DaoException;
import com.jwipc.shopping.entity.ShoppingAfterSales;
import com.jwipc.shopping.entity.ShoppingCart;
import com.jwipc.shopping.entity.ShoppingCartInfo;
import com.jwipc.shopping.model.query.OnlineMallCartQuery;
import com.jwipc.shopping.model.query.OnlineMallCommodityQuery;
import com.jwipc.shopping.model.query.OrderTrackQuery;
import com.jwipc.shopping.model.query.ShoppingDetailQuery;
import com.jwipc.shopping.model.vo.*;
import com.jwipc.shopping.service.*;
import com.jwipc.shopping.util.CommonUtil;
import com.jwipc.shopping.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 在线商城 实现类
 * </p>
 *
 * @author li.kui
 * @version 1.0
 * @since 2021/1/3
 */
@Service
public class OnlineMallServiceImpl implements IOnlineMallService {

    private final static Logger LOGGER = LoggerFactory.getLogger(OnlineMallServiceImpl.class);

    @Autowired
    IMiddleWareService middleWareService;
    @Autowired
    IShoppingAfterSalesService shoppingAfterSalesService;

    @Autowired
    IShoppingCartService cartService;

    @Autowired
    IShoppingCartInfoService cartInfoService;

    @Value("${sys.zkh.clientId}")
    private String zkhClientId;
    @Value("${sys.zkh.clientSecret}")
    private String zkhClientSecret;
    /**
     * 获取在线商城商品信息
     *
     * @param query 查询条件
     * @return 结果
     */
//    @Override
//    public OnlineMallResponse.DataBean findOnlineMallCommodity(OnlineMallCommodityQuery query) {
//        LOGGER.info("find online mall commodity data...");
//        // 接口调用结果
//        int callResult = 0;
//        // 接口调用日志信息
//        String message = "";
//
//        JSONObject params = new JSONObject();
//        params.put("source", query.getSource());
//        params.put("user_code", query.getUser_code());
//        params.put("product_name", query.getProduct_name());
//        params.put("pageNum", query.getPageNum());
//        params.put("pageSize", query.getPageSize());
//        MiddleWareQueryParam middleWareQueryParam = new MiddleWareQueryParam();
//        middleWareQueryParam.setInterId(MiddleWareInterfaceFlag.findOnlineMallCommodity);
//        middleWareQueryParam.setData(params.toJSONString());
//        String paramJson = JSON.toJSONString(middleWareQueryParam);
//
//        LOGGER.info("获取在线商城商品信息接口请求参数为: {}", paramJson);
//
//        try {
//            String result = middleWareService.requestMiddleWare(paramJson);
//            LOGGER.info("获取在线商城商品信息接口, 本次调用返回结果为: {}", result);
//
//            if (StringUtils.isNotEmpty(result)) {
//                final OnlineMallResponse response = JSONObject.parseObject(result, OnlineMallResponse.class);
//                if(0 == response.getCode()){
//                    if("0".equals(response.getData().getCode())){
//                        message = "接口调用成功";
//                        callResult = 1;
//
//                        return response.getData();
//                    }else {
//                        message = "商城接口异常! " + response.getData().getMessage();
//                        OnlineMallResponse.DataBean res = new OnlineMallResponse.DataBean();
//                        res.setCode("-1");
//                        res.setMessage(message);
//                        return res;
//                    }
//                }else {
//                    message = "中间件接口异常! " + response.getErrorMsg();
//                    OnlineMallResponse.DataBean res = new OnlineMallResponse.DataBean();
//                    res.setCode("-1");
//                    res.setMessage(message);
//                    return res;
//                }
//            }else {
//                message = "接口调用成功, 但未获取到数据";
//                OnlineMallResponse.DataBean res = new OnlineMallResponse.DataBean();
//                res.setCode("-1");
//                res.setMessage(message);
//                return res;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            LOGGER.error("find online mall commodity data error:" + e.getMessage(), e);
//            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";
//
//            OnlineMallResponse.DataBean res = new OnlineMallResponse.DataBean();
//            res.setCode("-1");
//            res.setMessage(message);
//            return res;
//        }
//        finally {
//            LOGGER.info("接口调用结果: {}, 接口调用描述: {}", callResult, message);
//            // tpiService.saveLog(callResult, message, JSON.toJSONString(query), "findOnlineMallCommodity", "获取在线商城商品信息", query.getUser_code(), 1);
//        }
//    }

    /**
     * 获取在线商城商品信息
     *
     * @param query 查询条件
     * @return 结果
     */
    @Override
    public OnlineShoppingZkhResponse findOnlineMallCommodity1(OnlineMallCommodityQuery query) {
        LOGGER.info("find online mall commodity data...");
        // 接口调用结果
        int callResult = 0;
        // 接口调用日志信息
        String message = "";

        String paramJsonToken = findTokenByCart(query.getSource());

        JSONObject params = new JSONObject();
        params.put("source", query.getSource());
        params.put("user_code", "platform_bhjt"); //query.getUser_code()
        params.put("product_name", query.getProduct_name());
        params.put("pageNum", query.getPageNum());
        params.put("pageSize", query.getPageSize());

        try {
            OnlineShoppingZkhResponse response = middleWareService.requestMiddleWareToken(paramJsonToken, params);
            LOGGER.info("获取在线商城商品信息接口, 本次调用返回结果为: {}", JSON.toJSONString(response));

            if (response != null) {
                //final OnlineShoppingResponse response = JSONObject.parseObject(result, OnlineShoppingResponse.class);
                if ("1".equals(response.getCode())) {
                    message = "接口调用成功";
                    callResult = 1;

                    return response;
                } else {
                    message = "中间件接口异常! " + response.getResulteMessage();
                    response.setMessage(message);
                    response.setCode("-1");
                    return response;
                }
            } else {
                message = "接口调用成功, 但未获取到数据";
                response.setMessage(message);
                response.setCode("-1");
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error("find online mall commodity data error:" + e.getMessage(), e);
            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";

            OnlineShoppingZkhResponse res = new OnlineShoppingZkhResponse();
            res.setMessage(message);
            res.setCode("-1");
            return res;
        } finally {
            LOGGER.info("接口调用结果: {}, 接口调用描述: {}", callResult, message);
            // tpiService.saveLog(callResult, message, JSON.toJSONString(query), "findOnlineMallCommodity", "获取在线商城商品信息", query.getUser_code(), 1);
            //调用方日志
//            String reqBodyData;
//            LogManager.me().executeLog(ApiLogTaskFactory.saveCallLog("sendSignFile", "震坤行",
//                    ThirdSysType.SIGN.getType(),
//                    paramJsonToken,
//                    message,
//                    "",
//                    LocalDateTime.now()
//            ));
        }
    }

    /**
     * 获取在线商城商品详细信息
     *
     * @param query 查询条件
     * @return 结果
     */
    @Override
    public ShoppingDetailReponse findShoppingDetail(ShoppingDetailQuery query) {
        LOGGER.info("find online mall shopping detail data...");
        // 接口调用结果
        int callResult = 0;
        // 接口调用日志信息
        String message = "";

        String paramJsonToken = findTokenByCart("ZKH");

        JSONObject params = new JSONObject();
        params.put("sku", query.getSku());
        params.put("isShow", false);
        try {
            ShoppingDetailReponse response = middleWareService.findShoppingDetail(paramJsonToken, params);
            LOGGER.info("获取在线商城商品明细信息接口, 本次调用返回结果为: {}", JSON.toJSONString(response));

            if (response != null) {
                //final OnlineShoppingResponse response = JSONObject.parseObject(result, OnlineShoppingResponse.class);
                if ("1".equals(response.getResultCode())) {
                    message = "接口调用成功";
                    callResult = 1;

                    return response;
                } else {
                    message = "中间件接口异常! " + response.getResulteMessage();
                    response.setResulteMessage(message);
                    response.setResultCode("-1");
                    return response;
                }
            } else {
                message = "接口调用成功, 但未获取到数据";
                response.setResulteMessage(message);
                response.setResultCode("-1");
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error("find online mall shopping detail data error:" + e.getMessage(), e);
            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";

            ShoppingDetailReponse res = new ShoppingDetailReponse();
            res.setResulteMessage(message);
            res.setResultCode("-1");
            return res;
        } finally {
            LOGGER.info("接口调用结果: {}, 接口调用描述: {}", callResult, message);
        }
    }

    /**
     * 获取在线商城商品详细信息
     *
     * @return 结果
     */
    @Override
    public ApplyProductResponse applyProduct(String skuNo) {
        LOGGER.info("find online mall applyProduct  data...");
        // 接口调用结果
        int callResult = 0;
        // 接口调用日志信息
        String message = "";

        String paramJsonToken = findTokenByCart("ZKH");

        JSONObject params = new JSONObject();
        params.put("sku", skuNo);
        try {
            ApplyProductResponse response = middleWareService.applyProduct(paramJsonToken, params);
            LOGGER.info("获取在线商城商品上架信息接口, 本次调用返回结果为: {}", JSON.toJSONString(response));

            if (response != null) {
                //final OnlineShoppingResponse response = JSONObject.parseObject(result, OnlineShoppingResponse.class);
                if ("0000".equals(response.getResultCode())) {
                    message = "接口调用成功";
                    callResult = 1;

                    return response;
                } else {
                    message = "中间件接口异常! " + response.getResultMessage();
                    response.setResultMessage(message);
                    response.setResultCode("-1");
                    return response;
                }
            } else {
                message = "接口调用成功, 但未获取到数据";
                response.setResultMessage(message);
                response.setResultCode("-1");
                return response;
            }
        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error("find online mall applyProduct  data error:" + e.getMessage(), e);
            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";

            ApplyProductResponse res = new ApplyProductResponse();
            res.setResultMessage(message);
            res.setResultCode("-1");
            return res;
        } finally {
            LOGGER.info("接口调用结果: {}, 接口调用描述: {}", callResult, message);
        }
    }
    /**
     * 商城购物车功能-科力普
     *
     * @param params 购物车商品信息
     * @param userCode 当前操作人
     * @return 结果
     */
//    @Override
//    public OnlineMallResponse pushMallShoppingCartKlp(OnlineMallScKlpDto params, String userCode) {
//        // 接口调用结果
//        int callResult = 0;
//        // 接口调用日志信息
//        String message = "";
//
//        MiddleWareQueryParam middleWareQueryParam = new MiddleWareQueryParam();
//        middleWareQueryParam.setInterId(MiddleWareInterfaceFlag.addOnlineMallShoppingCartKlp);
//        middleWareQueryParam.setData(JSON.toJSONString(params));
//        String paramJson = JSON.toJSONString(middleWareQueryParam);
//
//        try {
//            String result = middleWareService.requestMiddleWare(paramJson);
//            LOGGER.info("选购商品放入商城(科力普)购物车, 本次调用返回结果为: {}", result);
//
//            if (StringUtils.isNotEmpty(result)) {
//                return this.getAddCartResponse(result,false);
//            }else {
//                message = "接口调用成功, 但未获取到数据";
//                return this.getEmptyResponse(message);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            LOGGER.error("push mall shopping cart klp data error:" + e.getMessage(), e);
//            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";
//
//            return this.getEmptyResponse(message);
//        } finally {
//            tpiService.saveLog(callResult, message, JSON.toJSONString(params), "pushMallShoppingCartKlp", "选购商品放入商城(科力普)购物车", userCode, 1);
//        }
//    }


    /**
     * 添加商城购物车功能-西域
     *
     * @param params 购物车商品信息
     * @param userCode 当前操作人
     * @return 结果
     */
//    @Override
//    public OnlineMallResponse pushMallShoppingCartXy(OnlineMallScXyDto params, String userCode) {
//        // 接口调用结果
//        int callResult = 0;
//        // 接口调用日志信息
//        String message = "";
//
//        MiddleWareQueryParam middleWareQueryParam = new MiddleWareQueryParam();
//        middleWareQueryParam.setInterId(MiddleWareInterfaceFlag.addOnlineMallShoppingCartXy);
//        middleWareQueryParam.setData(JSON.toJSONString(params));
//        String paramJson = JSON.toJSONString(middleWareQueryParam);
//
//        try {
//            String result = middleWareService.requestMiddleWare(paramJson);
//            LOGGER.info("选购商品放入商城(西域)购物车, 本次调用返回结果为: {}", result);
//
//            if (StringUtils.isNotEmpty(result)) {
//                return this.getAddCartResponse(result,true);
//            }else {
//                message = "接口调用成功, 但未获取到数据";
//                return this.getEmptyResponse(message);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//            LOGGER.error("push mall shopping cart xy data error:" + e.getMessage(), e);
//            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";
//
//            return this.getEmptyResponse(message);
//        } finally {
//            tpiService.saveLog(callResult, message, JSON.toJSONString(params), "pushMallShoppingCartXy", "选购商品放入商城(西域)购物车", userCode, 1);
//        }
//    }


    /**
     * 获取加入购物车接口返回信息
     *
     * @param interfaceResponse 接口返回
     * @return 结果
     */
//    private OnlineMallResponse getAddCartResponse(String interfaceResponse,boolean isXy){
//        OnlineMallResponse result = new OnlineMallResponse();
//        final OnlineMallAddCartResponse response = JSONObject.parseObject(interfaceResponse, OnlineMallAddCartResponse.class);
//        if(0 == response.getCode()){
//            final OnlineMallAddCartResponse.DataBean mallResponse = response.getData();
//            if(isXy){
//                if("0".equals(mallResponse.getResultCode())){
//                    result.setCode(0);
//                }else {
//                    result.setCode(-1);
//                    result.setErrorMsg("接口调用失败, " + mallResponse.getResultMessage());
//                }
//
//            }else{
//                if("0".equals(mallResponse.getCode())){
//                    result.setCode(0);
//                }else {
//                    result.setCode(-1);
//                    result.setErrorMsg("接口调用失败, " + mallResponse.getMessage());
//                }
//            }
//
//        }else {
//            result.setCode(-1);
//            result.setErrorMsg("接口调用失败, " + response.getErrorMsg());
//        }
//        return result;
//    }

    /**
     * 获取xy加入购物车接口返回信息
     *
     * @param interfaceResponse 接口返回
     * @return 结果
     */
//    private OnlineMallResponse getXYAddCartResponse(String interfaceResponse,boolean isXy){
//        OnlineMallResponse result = new OnlineMallResponse();
//        final OnlineMallAddCartResponse response = JSONObject.parseObject(interfaceResponse, OnlineMallAddCartResponse.class);
//        if(response.getResult()){
//            if(isXy){
//                if("0".equals(response.getResultCode())){
//                    result.setCode(0);
//                }else {
//                    result.setCode(-1);
//                    result.setErrorMsg("接口调用失败, " + response.getResultMessage());
//                }
//
//            }else{
//                if("0".equals(response.getCode())){
//                    result.setCode(0);
//                }else {
//                    result.setCode(-1);
//                    result.setErrorMsg("接口调用失败, " + response.getResultMessage());
//                }
//            }
//
//        }else {
//            result.setCode(-1);
//            result.setErrorMsg("接口调用失败, " + response.getErrorMsg());
//        }
//        return result;
//    }


    /**
     * 获取空的返回
     *
     * @param message 空的原因
     * @return 结果
     */
    private OnlineMallResponse getEmptyResponse(String message) {
        OnlineMallResponse res = new OnlineMallResponse();
        res.setCode(-1);
        res.setErrorMsg(message);

        return res;
    }

    /**
     * 添加商城购物车功能-西域
     *
     * @param params   购物车商品信息
     * @param userCode 当前操作人
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OnlineMallResponse pushShoppingCartXy(ShoppingCart cart, OnlineShoppingXyDto params, String userCode, List<ShoppingCartInfo> scList) {

        // 接口调用结果
        int callResult = 0;
        // 接口调用日志信息
        String message = "";

        String paramJson = JSON.toJSONString(params);

        try {
            LOGGER.info("选购商品放入商城 购物车, 调用参数为: {}", paramJson);
            //推送预订单
            String result = middleWareService.requestMiddleOrder(paramJson, cart.getStoreCode());
            LOGGER.info("选购商品放入商城 购物车, 本次调用返回结果为: {}", result);

            if (StringUtils.isNotEmpty(result)) {
                final OnlineMallOrderResponse response = JSON.parseObject(result, OnlineMallOrderResponse.class);
                if (response.getSuccess()) {
                    if ("0001".equals(response.getResultCode())) {
                        //成功生成预订单，更改商城推送状态
                        cart.setStatus(1);
                        cart.setSrmStatus(5);
                        cart.setOrderId(response.getResult().getOrderId());
                        cartService.updateById(cart);
                        OnlineMallResponse res = new OnlineMallResponse();
                        res.setCode(0);
                        res.setErrorMsg("提交成功");
                        return res;
                    } else {
                        message = "生成预订单失败,商城失败原因为::" + response.getResultMessage();
                        //生成预订单失败，更改商城推送状态
                        cart.setStatus(2);
                        cart.setCallbackDesc(response.getResultMessage());
                        cartService.updateById(cart);

                        return this.getEmptyResponse(message);
                    }
                } else {
                    message = "生成预订单失败,商城失败原因为:" + response.getResultMessage();
                    //生成预订单失败，更改商城推送状态
                    cart.setStatus(2);
                    cart.setCallbackDesc(response.getResultMessage());
                    cartService.updateById(cart);
                    return this.getEmptyResponse(message);
                }

                //return this.getXYAddCartResponse(result,true);
            } else {
                message = "接口调用成功, 但未获取到数据";
                //生成预订单失败，更改商城推送状态
                cart.setStatus(2);
                cart.setCallbackDesc(message);
                cartService.updateById(cart);
                return this.getEmptyResponse(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("push mall shopping cart xy data error:" + e.getMessage(), e);
            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";
            return this.getEmptyResponse(message);
        }
    }

//    public BinHuaOaReturnDto pushShoppingToOa(OnlineMallOrderResponse response,OnlineShoppingXyDto params,OnlineShoppingZkhDto zkhParams) {
//        BinHuaOaReturnDto result = new BinHuaOaReturnDto();
//
//        final ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
//        final BinHuaOaReturnDto.DataBean oaUser = srmToOaService.findOaUserId(shiroUser.getLoginName());
//        if (StringUtils.isEmpty(oaUser.getUSERID())) {
//            result.setCODE(-1);
//            result.setMESSAGE("用户: " + shiroUser.getLoginName() + ", 未查询到OA用户ID, 请联系管理员");
//            return result;
//        }
//        OaOnlineMallOrderData orderData = new OaOnlineMallOrderData();
//        // 定义common头
//        OaOnlineMallOrderData.BASEINFOBean baseinfoBean = new OaOnlineMallOrderData.BASEINFOBean();
//        baseinfoBean.setWFCODE("MM-110");
//        baseinfoBean.setCREATOR(oaUser.getUSERID());
//        baseinfoBean.setREQUESTNAME("互联网商城购物订单审批_" + shiroUser.getName() + "_" + com.xiaoleilu.hutool.date.DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//        baseinfoBean.setISNEXTFLOW("1");
//        orderData.setBASEINFO(baseinfoBean);
//
//        //西域推送
//        if(!Objects.isNull(params)){
//            OaOnlineMallOrderData.HEADDATABean head = new OaOnlineMallOrderData.HEADDATABean();
//            head.setXTBS(2);
//            head.setSRM_REQ_ID(params.getThirdOrder());
//            head.setZGWDDBH(response.getResult().getOrderId());
//            head.setZDDLY(params.getStoreName());
//            head.setZCGZE(response.getResult().getOrderPrice().toString());
//            head.setZSYGC(params.getFactoryName());
//            head.setZSYBM(shiroUser.getDeptName());
//            head.setZCGR(oaUser.getUSERID());
//            head.setZCJSJ(DateUtil.yyyyMMddDash(new Date()));
//            head.setZSM(params.getContent());
//            orderData.setHEADDATA(head);
//
//
//            // 【03】 - 对账单 - 明细数据
//            List<OnlineMallProductDto> itemDtoList = response.getResult().getSku();
//
//            List<OaOnlineMallOrderData.DETAILDATABean> detaildataBeanList = new ArrayList<>();
//            OaOnlineMallOrderData.DETAILDATABean detaildataBean = new OaOnlineMallOrderData.DETAILDATABean();
//            List<OaOnlineMallOrderData.DETAILDATABean.ROWSBean> rowsBeans = new ArrayList<>();
//            for(int i= 0 ;  i<itemDtoList.size() ; i++){
//                OnlineMallProductDto dto = itemDtoList.get(i);
//                OaOnlineMallOrderData.DETAILDATABean.ROWSBean row = new OaOnlineMallOrderData.DETAILDATABean.ROWSBean();
//                // 01 - 序号 - ZXH
//                row.setZXH(String.valueOf(i));
//                // 02 - SKU - ZLX
//                row.setZLX(null == dto.getSkuId() ? "" : dto.getSkuId());
//                // 03 - 商品名称描叙 - ZWLBM
//                row.setZWLBM(null == dto.getName() ? "" : dto.getName());
//                // 04 - 数量 - ZWLMS
//                row.setZWLMS(null == dto.getNum() ? "" : dto.getNum().toString());
//                // 05 - 单位 - ZCGSL
//                row.setZCGSL(null == dto.getSaleUnit() ? "" : dto.getSaleUnit());
//                // 06 - 单价（含税 - ZDW
//                row.setZDW(null == dto.getPrice() ? "" : dto.getPrice().toString());
//                BigDecimal num = new BigDecimal(dto.getNum()).multiply(dto.getPrice());
//                // 07 - 金额（含税） - ZYSDJ
//                row.setZYSDJ(null == num ? "" : num.toString());
//
//                rowsBeans.add(row);
//
//            }
//            detaildataBean.setINDEX(1);
//            detaildataBean.setROWS(rowsBeans);
//            detaildataBeanList.add(detaildataBean);
//
//            orderData.setDETAILDATA(detaildataBeanList);
//        }else if(!Objects.isNull(zkhParams)){
//            //震坤行推送
//            OaOnlineMallOrderData.HEADDATABean head = new OaOnlineMallOrderData.HEADDATABean();
//            head.setXTBS(2);
//            head.setSRM_REQ_ID(zkhParams.getThirdOrder());
//            head.setZGWDDBH(response.getResult().getOrderId());
//            head.setZDDLY(zkhParams.getStoreName());
//            head.setZCGZE(response.getResult().getFreight().toString());
//            head.setZSYGC(zkhParams.getFactoryName());
//            head.setZSYBM(shiroUser.getDeptName());
//            head.setZCGR(oaUser.getUSERID());
//            head.setZCJSJ(DateUtil.yyyyMMddDash(new Date()));
//            head.setZSM(zkhParams.getRemark());
//            orderData.setHEADDATA(head);
//
//
//            // 【03】 - 对账单 - 明细数据
//            List<OnlineMallProductDto> itemDtoList = response.getResult().getSku();
//
//            List<OaOnlineMallOrderData.DETAILDATABean> detaildataBeanList = new ArrayList<>();
//            OaOnlineMallOrderData.DETAILDATABean detaildataBean = new OaOnlineMallOrderData.DETAILDATABean();
//            List<OaOnlineMallOrderData.DETAILDATABean.ROWSBean> rowsBeans = new ArrayList<>();
//            for(int i= 0 ;  i<itemDtoList.size() ; i++){
//                OnlineMallProductDto dto = itemDtoList.get(i);
//                OaOnlineMallOrderData.DETAILDATABean.ROWSBean row = new OaOnlineMallOrderData.DETAILDATABean.ROWSBean();
//                // 01 - 序号 - ZXH
//                row.setZXH(String.valueOf(i));
//                // 02 - SKU - ZLX
//                row.setZLX(null == dto.getSkuId() ? "" : dto.getSkuId());
//                // 03 - 商品名称描叙 - ZWLBM
//                row.setZWLBM(null == dto.getName() ? "" : dto.getName());
//                // 04 - 数量 - ZWLMS
//                row.setZWLMS(null == dto.getNum() ? "" : dto.getNum().toString());
//                // 05 - 单位 - ZCGSL
//                row.setZCGSL(null == dto.getSaleUnit() ? "" : dto.getSaleUnit());
//                // 06 - 单价（含税 - ZDW
//                row.setZDW(null == dto.getPrice() ? "" : dto.getPrice().toString());
//                BigDecimal num = new BigDecimal(dto.getNum()).multiply(dto.getPrice());
//                // 07 - 金额（含税） - ZYSDJ
//                row.setZYSDJ(null == num ? "" : num.toString());
//
//                rowsBeans.add(row);
//
//            }
//            detaildataBean.setINDEX(1);
//            detaildataBean.setROWS(rowsBeans);
//            detaildataBeanList.add(detaildataBean);
//
//            orderData.setDETAILDATA(detaildataBeanList);
//        }
//
//
//        LOGGER.info("提交OA审批参数："+JSON.toJSONString(orderData));
//        result = srmToOaService.onlineMallOrderExamineFlow(orderData, shiroUser.getLoginName());
//        LOGGER.info("提交OA审批返回参数："+JSON.toJSONString(result));
//
//        return result;
//    }


    /**
     * 采购订单推送OA审批
     *
     * @param id 推送OA审批的采购订单主表ID
     * @param shiroUser 当前操作用户
     */
//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public List<String> pushPoToOa(Long id, ShiroUser shiroUser) {
//        // 获取OA用户ID
//        final BinHuaOaReturnDto.DataBean oaUser = srmToOaService.findOaUserId(shiroUser.getLoginName());
//        if (StringUtils.isEmpty(oaUser.getUSERID())) {
//            throw new DaoException("用户: " + shiroUser.getLoginName() + ", 未查询到OA用户ID, 请联系管理员");
//        }
//
//        List<String> result = Lists.newArrayList();
//
//        OnlineMallCartQuery query = new OnlineMallCartQuery();
//        query.setCartId(id);
//        final OnlineMallCartDto poList = cartService.selectByQuery(query);
//
//        List<CpShoppingCartInfo> itemDtoList = shoppingCartInfoService.selectList(new EntityWrapper<CpShoppingCartInfo>().eq("cart_id", id));
//
//        OaOnlineMallOrderData orderData = new OaOnlineMallOrderData();
//        // 定义common头
//        OaOnlineMallOrderData.BASEINFOBean baseinfoBean = new OaOnlineMallOrderData.BASEINFOBean();
//        baseinfoBean.setWFCODE("MM-110");
//        baseinfoBean.setCREATOR(oaUser.getUSERID());
//        baseinfoBean.setREQUESTNAME("互联网商城购物订单审批_" + shiroUser.getName() + "_" + com.xiaoleilu.hutool.date.DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
//        baseinfoBean.setISNEXTFLOW("1");
//        orderData.setBASEINFO(baseinfoBean);
//
//        // 【03】 - 对账单 - 明细数据
//        List<OaOnlineMallOrderData.DETAILDATABean> detaildataBeanList = new ArrayList<>();
//        OaOnlineMallOrderData.DETAILDATABean detaildataBean = new OaOnlineMallOrderData.DETAILDATABean();
//        List<OaOnlineMallOrderData.DETAILDATABean.ROWSBean> rowsBeans = new ArrayList<>();
//        int index = itemDtoList.size();
//        BigDecimal total = BigDecimal.ZERO;
//        for(int i= 0 ;  i<itemDtoList.size() ; i++){
//            CpShoppingCartInfo dto = itemDtoList.get(i);
//            OaOnlineMallOrderData.DETAILDATABean.ROWSBean row = new OaOnlineMallOrderData.DETAILDATABean.ROWSBean();
//            // 01 - 序号 - ZXH
//            row.setZXH(String.valueOf(i));
//            // 02 - SKU - ZLX
//            row.setZLX(null == dto.getSkuCode() ? "" : dto.getSkuCode());
//            // 03 - 商品名称描叙 - ZWLBM
//            row.setZWLBM(null == dto.getSkuName() ? "" : dto.getSkuName());
//            // 04 - 数量 - ZWLMS
//            row.setZWLMS(null == dto.getQty() ? "" : dto.getQty().toString());
//            // 05 - 单位 - ZCGSL
//            row.setZCGSL(null == dto.getUnit() ? "" : dto.getUnit());
//            // 06 - 单价（含税 - ZDW
//            row.setZDW(null == dto.getUnitCost() ? "" : dto.getUnitCost().toString());
//            // 07 - 金额（含税） - ZYSDJ
//            BigDecimal num = dto.getQty().multiply(dto.getUnitCost());
//            row.setZYSDJ(null == num ? "" : num.toString());
//
//            total = total.add(num);
//            rowsBeans.add(row);
//        }
//
//
//        OaOnlineMallOrderData.HEADDATABean head = new OaOnlineMallOrderData.HEADDATABean();
//        head.setXTBS(2);
//        head.setSRM_REQ_ID(poList.getThirdOrder());
//        head.setZGWDDBH(poList.getOrderId());
//        head.setZDDLY(poList.getStoreName());
//        head.setZCGZE(total.toString());
//        head.setZSYGC("("+poList.getFactoryCode() + ")" +poList.getFactoryName());
//        head.setZSYBM(shiroUser.getDeptName());
//        head.setZCGR(oaUser.getUSERID());
//        head.setZCJSJ(DateUtil.yyyyMMddDash(new Date()));
//        head.setZSM(poList.getRemark());
//        orderData.setHEADDATA(head);
//
//        detaildataBean.setINDEX(1);
//        detaildataBean.setROWS(rowsBeans);
//        detaildataBeanList.add(detaildataBean);
//
//        orderData.setDETAILDATA(detaildataBeanList);
//
//        BinHuaOaReturnDto dto = srmToOaService.onlineMallOrderExamineFlow(orderData, shiroUser.getLoginName());
//        LOGGER.info(JSON.toJSONString(dto));
//
//        // 需要更新的数据
//        //oa推送成功，更改oa以及订单状态
//        CpShoppingCart cart = cartService.selectById(id);
//        if(!Objects.isNull(dto)){
//            if(dto.getCODE() == 0) {
//                cart.setOaStatus(dto.getCODE());
//                cart.setOaId(dto.getREQUESTID());
//                cart.setOaDesc(dto.getMESSAGE());
//                cart.setSrmStatus(3);
//                cartService.updateById(cart);
//
//            }else{
//                result.add("采购订单(" + cart.getThirdOrder() + ") 推送OA审批失败, 原因: " + dto.getMESSAGE());
//            }
//        } else {
//            result.add("采购订单(" + cart.getThirdOrder() + ") 推送OA审批失败, 原因: " + dto.getMESSAGE());
//            //oa审批失败，更改oa以及订单状态
//            cart.setOaStatus(dto.getCODE());
//            cart.setOaDesc(dto.getMESSAGE());
//            cart.setSrmStatus(4);
//            cartService.updateById(cart);
//        }
//
//        return result;
//    }

    /**
     * 获取商城token
     *
     * @param source 商城来源
     * @return 结果
     */
    @Override
    public String findTokenByCart(String source) {
        LOGGER.info("find online mall commodity data...");
        // 接口调用结果
        int callResult = 0;
        // 接口调用日志信息
        String message = "";

        String paramJsonToken = "";
        if ("XY".equals(source)) {
            String client_id = "4900e144aa674f4d97e0758be6acb79c";
            Date timestamp = new Date();
            String date = new DateTime(timestamp).toString(DateUtil.getDateTimeFormatter("yyyy-MM-dd HH:mm:ss"));

            String username = "bhjt";
            String salt = "Ehsy2020lion";
            //先获取token信息
            JSONObject paramsToken = new JSONObject();
            paramsToken.put("grant_type", "access_token");
            paramsToken.put("client_id", client_id);
            paramsToken.put("timestamp", date);
            paramsToken.put("username", username);
            //签名规则 md5(client_id + username + timestamp + client_id +salt)
            //salt 值为：Ehsy2020lion
            String sign = client_id + username + date + client_id + salt;
            paramsToken.put("sign", CommonUtil.MD5(sign));

            paramJsonToken = JSON.toJSONString(paramsToken);
            LOGGER.info("获取在线商城商品信息XY接口请求参数为: {}", paramJsonToken);
        } else if ("ZKH".equals(source)) {

//            String client_id = "M9hU8Aa22KQCMMcjv1BHFBB1tpkSbfjwpC8930GiCD6HC1mar6D9g8JDx7UL8VRZbr1yLGce9rcEIvWy";
//            String client_secret = "vNVZjBNiiBhIfxFldTyLPD7yJKUOXyDpGQxK2cWA70lhKefc6pFXJyM4W1TxwTUFeEZt5H1cWAbCapS4orL3gOLC3BD6jhgsagFP";
            Date timestamp = new Date();
            String date = new DateTime(timestamp).toString(DateUtil.getDateTimeFormatter("yyyy-MM-dd HH:mm:ss"));

            String username = "15817414920";
            String password = "zwzn123!";
            //先获取token信息
            JSONObject paramsToken = new JSONObject();
            paramsToken.put("clientId", zkhClientId);
//            paramsToken.put("clientId", zkhClientId);
            paramsToken.put("clientSecret", zkhClientSecret);
//            paramsToken.put("clientSecret", zkhClientSecret);
            /*paramsToken.put("timestamp", date);
            paramsToken.put("username", username);
            paramsToken.put("password", password);*/

            paramJsonToken = JSON.toJSONString(paramsToken);
            LOGGER.info("获取在线商城商品信息ZKH接口请求参数为: {}", paramJsonToken);
        }

        try {
            String response = middleWareService.requestTokenByPush(paramJsonToken, source);
            LOGGER.info("获取在线商城商品token接口, 本次调用返回结果为: {}", JSON.toJSONString(response));

            return response;
        } catch (Exception e) {
            return "";
        }
    }


    /**
     * 确认商城订单
     *
     * @param id 购物订单ID
     * @return 结果 6:商城订单确认成功 7:商城订单确认失败 9:商城订单确认成功但生成SRM订单失败
     */
    @Override
    public Integer confirmMallOrder(Long id) {
        final ShoppingCart head = cartService.getById(id);
        if (5 != head.getSrmStatus()) {
            throw new DaoException("只有“待确认商城订单”状态的单据才能执行该操作, 您选择的订单(" + head.getThirdOrder() + ")当前状态不正确, 请检查");
        }

        OnlineMallCartQuery query = new OnlineMallCartQuery();
        query.setCartId(id);
        final OnlineMallCart cartDto = cartService.selectByQuery(query);

        OnlineShoppingConfirmOrderXyDto orderDto = new OnlineShoppingConfirmOrderXyDto();
        String token = findTokenByCart(cartDto.getStoreCode());
        orderDto.setToken(token);
        orderDto.setOrderId(cartDto.getOrderId());

       /*  final List<ShoppingCartInfo> itemDtoList = cartInfoService.list(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, id));
       List<OnlineShoppingConfirmOrderXyDto.Items> itemList = new ArrayList<>();
        for (ShoppingCartInfo list : itemDtoList) {
            OnlineShoppingConfirmOrderXyDto.Items item = new OnlineShoppingConfirmOrderXyDto.Items();
            item.setQuantity(list.getQty().intValue());
            item.setSkuCode(list.getSkuCode());
            itemList.add(item);
        }
        orderDto.setSkuModifyInfoList(itemList);*/

        String orderJson = JSON.toJSONString(orderDto);
        LOGGER.info("选购商品确认商城(" + cartDto.getStoreName() + ")订单, 调用参数为: {}", orderJson);

        ShoppingCart cart = new ShoppingCart();
        cart.setId(id);

        try {
            String result = middleWareService.requestMiddleConfirmOrder(orderJson, cartDto.getStoreCode());
            LOGGER.info("选购商品确认商城(" + cartDto.getStoreName() + ")订单, 本次调用返回结果为: {}", result);
            if (StringUtils.isNotEmpty(result)) {
                final ApplyProductResponse orderResponse = JSON.parseObject(result, ApplyProductResponse.class);
                if (orderResponse.getSuccess()) {
                    // 确认订单成功，更改商城以及订单状态
                    cart.setStatus(3);
                    cart.setCallbackDesc(orderResponse.getResultMessage());
                    cart.setSrmStatus(6);
                } else {
                    // 确认订单失败，更改商城以及订单状态
                    cart.setStatus(4);
                    cart.setCallbackDesc(orderResponse.getResultMessage());
                    cart.setSrmStatus(7);
                }
            } else {
                // 确认订单失败，更改商城以及订单状态
                cart.setStatus(4);
                cart.setCallbackDesc("确认商城订单失败");
                cart.setSrmStatus(7);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("确认商城订单失败, 原因: {}", e.getMessage(), e);

            // 为了前端不会出现空指针异常
            cart.setSrmStatus(7);
        }
//        finally {
//            // 表示商城订单确认成功
//            if (6 == cart.getSrmStatus()) {
//                try {
//                    boolean res = purchaseOrderService.mallOrderChangePo(head, itemDtoList);
//                    if (!res) {
//                        cart.setSrmStatus(9);
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    LOGGER.error("确认商城订单成功后生成SRM采购订单失败, 原因: {}", e.getMessage(), e);
//                }
//            }
//
        cartService.updateById(cart);
//        }

        return cart.getSrmStatus();
    }

    /**
     * 售后单取消
     */
    @Override
    public String confirmMallOrder2(Long id) {
//        final ShoppingCart head = cartService.getById(id);
        final ShoppingAfterSales sales = shoppingAfterSalesService.getById(id);
//        if ("5" != sales.getStatus()) {
//            throw new DaoException("只有“待确认商城订单”状态的单据才能执行该操作, 您选择的售后单(" + sales.getAfOrderCode() + ")当前状态不正确, 请检查");
//        }
        OrderCancelDto orderCancelDto = new OrderCancelDto();
        if(Objects.nonNull(sales.getAfOrderCode())){
            orderCancelDto.setServiceId(sales.getAfOrderCode());
        }else{
            throw new DaoException("只有“售后订单号不为空”的单据才能执行该操作, 您选择的售后单(" + sales.getAfOrderCode() + ")当前状态不正确, 请检查");
        }

//        OnlineMallCartQuery query = new OnlineMallCartQuery();
//        query.setCartId(id);
//        final OnlineMallCart cartDto = cartService.selectByQuery(query);

//        OnlineShoppingConfirmOrderXyDto orderDto = new OnlineShoppingConfirmOrderXyDto();
//        String token = findTokenByCart(cartDto.getStoreCode());
//        orderDto.setToken(token);
//        orderDto.setOrderId(cartDto.getOrderId());
//
//        String orderJson = JSON.toJSONString(orderDto);
//        LOGGER.info("选购商品确认商城(" + cartDto.getStoreName() + ")订单, 调用参数为: {}", orderJson);
//
//        ShoppingCart cart = new ShoppingCart();
//        cart.setId(id);
        String token = findTokenByCart("ZKH");
//        orderDto.setToken("bearer " + token);
//        orderDto.setOrderId(param.getOrderId());
        String orderJson = JSON.toJSONString(orderCancelDto);


        try {
            String result = middleWareService.requestMiddleConfirmOrder2(token,orderJson, "ZKH");
            LOGGER.info("选购商品取消售后(" +"震坤行" + ")订单, 本次调用返回结果为: {}", result);
            if (StringUtils.isNotEmpty(result)) {
                final ApplyProductResponse orderResponse = JSON.parseObject(result, ApplyProductResponse.class);
                String result1 = orderResponse.getResult();
                JSONObject jsonObject = JSON.parseObject(result1);
                if (orderResponse.getSuccess()) {
                    // 确认订单成功，更改商城以及订单状态
                    sales.setStatus("4");
                    shoppingAfterSalesService.saveOrUpdate(sales);
                } else {
                    // 确认订单失败，更改商城以及订单状态
                    sales.setStatus("1");
                    shoppingAfterSalesService.saveOrUpdate(sales);
                    throw new DaoException("震坤行接口返回报错：" + jsonObject.getString("resultMessage"));


                }
            } else {
                // 确认订单失败，更改商城以及订单状态

            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("确认商城订单失败, 原因: {}", e.getMessage(), e);

            // 为了前端不会出现空指针异常
//            cart.setSrmStatus(7);
        }
//        cartService.updateById(cart);


        return sales.getStatus();
    }

    /**
     * OA推送变更状态
     *
     * @param oaNumber OA流程ID
     * @param oaStatus oa流程状态 1-通过 2-拒绝
     */
//    @Override
//    public void oaPushFlowStatus(String oaNumber, String oaStatus) {
//        if (!"1".equals(oaStatus) && !"2".equals(oaStatus)) {
//            throw new DaoException("审批状态不合法");
//        }
//        // 通过OA流程ID找寻商城订单
//        OnlineMallCartQuery query = new OnlineMallCartQuery();
//        query.setOaId(oaNumber);
//        final OnlineMallCartDto cartDto = cartService.selectByQuery(query);
//        if (cartDto == null) {
//            throw new DaoException("SRM未找到此流程");
//        }
//
//        List<CpShoppingCartInfo> itemDtoList = shoppingCartInfoService.selectList(new EntityWrapper<CpShoppingCartInfo>().eq("cart_id", cartDto.getId()));
//
//        CpShoppingCart cart = cartService.selectById(cartDto.getId());
//
//        if("1".equals(oaStatus)){
//            //OA审批通过，更新订单状态，调用SRM订单创建接口，生成确认订单
//            cart.setOaStatus(1);
//            cart.setOaDesc("OA审批成功");
//            cart.setSrmStatus(5);
//            cartService.updateById(cart);
//
//            // 创建确认订单
//            // OA审批成功，推送商城确认订单
//            OnlineShoppingConfirmOrderXyDto orderDto = new OnlineShoppingConfirmOrderXyDto();
//            String token = findTokenByCart(cartDto.getStoreCode());
//            orderDto.setToken(token);
//            orderDto.setOrder_id(cartDto.getOrderId());
//
//            List<OnlineShoppingConfirmOrderXyDto.Items> itemList = new ArrayList<>();
//            for (CpShoppingCartInfo list:itemDtoList) {
//                OnlineShoppingConfirmOrderXyDto.Items item = new OnlineShoppingConfirmOrderXyDto.Items();
//                item.setSkuCode(list.getSkuCode());
//                item.setQuantity(list.getQty().intValue());
//                itemList.add(item);
//            }
//            orderDto.setSkuModifyInfoList(itemList);
//
//            String orderJson = JSON.toJSONString(orderDto);
//
//            LOGGER.info("选购商品确认商城("+cartDto.getStoreName()+")订单, 调用参数为: {}", orderJson);
//            //推送确认订单
//            try{
//                String result = middleWareService.requestMiddleConfirmOrder(orderJson,cartDto.getStoreCode());
//                LOGGER.info("选购商品确认商城("+cartDto.getStoreName()+")订单, 本次调用返回结果为: {}", result);
//
//                if (StringUtils.isNotEmpty(result)) {
//                    final OnlineMallOrderResponse orderResponse = JSON.parseObject(result, OnlineMallOrderResponse.class);
//                    if(orderResponse.getSuccess()){
//                        // 确认订单成功，更改商城以及订单状态
//                        cart.setStatus(3);
//                        cart.setCallbackDesc(orderResponse.getResultMessage());
//                        cart.setSrmStatus(6);
//                        cartService.updateById(cart);
//
//                        // OA审批成功，调用SRM接口生成SRM采购订单
//                        boolean res = purchaseOrderService.mallOrderChangePo(cart, itemDtoList);
//                        if (!res) {
//                            cart.setSrmStatus(9);
//                            cartService.updateById(cart);
//                        }
//                    }else{
//                        // 确认订单失败，更改商城以及订单状态
//                        cart.setStatus(4);
//                        cart.setCallbackDesc(orderResponse.getResultMessage());
//                        cart.setSrmStatus(7);
//                        cartService.updateById(cart);
//                    }
//                }else{
//                    // 确认订单失败，更改商城以及订单状态
//                    cart.setStatus(4);
//                    cart.setCallbackDesc("生成确认订单失败");
//                    cart.setSrmStatus(7);
//                    cartService.updateById(cart);
//                }
//            }catch (Exception e){
//                e.printStackTrace();
//            }
//        }else{
//            // OA审批不通过，更新订单状态
//            cart.setOaStatus(2);
//            cart.setOaDesc("OA审批驳回");
//            cart.setSrmStatus(8);
//            cartService.updateById(cart);
//        }
//    }


    /**
     * 生成SRM费用采购订单
     *
     * @param id 商城订单ID
     */
//    @Override
//    public void genSrmPo(Long id) {
//        final CpShoppingCart cart = cartService.selectById(id);
//        if (9 != cart.getSrmStatus()) {
//            throw new DaoException("只有“生成SRM采购订单失败”状态的单据才能生成SRM采购订单, 您选择的订单(" + cart.getThirdOrder() + ")当前状态不正确, 请检查");
//        }
//
//        final List<CpShoppingCartInfo> itemDtoList = shoppingCartInfoService.selectList(new EntityWrapper<CpShoppingCartInfo>().eq("cart_id", id));
//        boolean res = purchaseOrderService.mallOrderChangePo(cart, itemDtoList);
//        if (!res) {
//            throw new DaoException("订单生成失败");
//        }
//
//        CpShoppingCart up = new CpShoppingCart();
//        up.setId(cart.getId());
//        up.setSrmStatus(6);
//        cartService.updateById(up);
//    }


    /**
     * 添加商城购物车功能-震坤行
     *
     * @param params 购物车商品信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OnlineMallResponse pushShoppingCartZkh(ShoppingCart cart, OnlineShoppingZkhDto params, List<ShoppingCartInfo> scList) {

        // 接口调用结果
        int callResult = 0;
        // 接口调用日志信息
        String message = "";

//        params.setPurchaseMobile(user.getPhone());
        String paramJson = JSON.toJSONString(params);

        try {
            LOGGER.info("选购商品放入商城(震坤行)购物车, 调用参数为: {}", paramJson);
            //推送预订单
            String result = middleWareService.requestMiddleOrder(paramJson, cart.getStoreCode());
            LOGGER.info("选购商品放入商城(震坤行)购物车, 本次调用返回结果为: {}", result);

            if (StringUtils.isNotEmpty(result)) {
                final OnlineMallOrderResponse response = JSON.parseObject(result, OnlineMallOrderResponse.class);
                if (response.getSuccess()) {
                    if ("0000".equals(response.getResultCode())) {

                        //成功生成预订单，更改商城推送状态
                        cart.setStatus(1);
                        cart.setSrmStatus(5);
                        cart.setOrderId(response.getResult().getOrderId());
                        cartService.updateById(cart);

                        OnlineMallResponse res = new OnlineMallResponse();
                        res.setCode(0);
                        res.setErrorMsg("提交成功");
                        return res;

                    } else {
                        message = "生成预订单失败,震坤行商城失败原因为::" + response.getResultMessage();
                        //生成预订单失败，删除订单及明细
                        cartService.removeById(cart);
                        cartInfoService.removeBatchByIds(scList);
                       /* cart.setStatus(2);
                        cart.setCallbackDesc(response.getResultMessage());
                        cartService.updateById(cart);*/
                        return this.getEmptyResponse(message);
                    }
                } else {
                    message = "生成预订单失败,震坤行商城失败原因为:" + response.getResultMessage();
                    //生成预订单失败，删除订单及明细
                    cartService.removeById(cart);
                    cartInfoService.removeBatchByIds(scList);
                    /*cart.setStatus(2);
                    cart.setCallbackDesc(response.getResultMessage());
                    cartService.updateById(cart);*/
                    return this.getEmptyResponse(message);
                }
            } else {
                message = "接口调用成功, 但未获取到数据";
                //生成预订单失败，删除订单及明细
                cartService.removeById(cart);
                cartInfoService.removeBatchByIds(scList);
               /* cart.setStatus(2);
                cart.setCallbackDesc(message);
                cartService.updateById(cart);*/
                return this.getEmptyResponse(message);
            }
        } catch (Exception e) {
            e.printStackTrace();

            LOGGER.error("push mall shopping cart zkh data error:" + e.getMessage(), e);
            message = StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "空指针异常";
            return this.getEmptyResponse(message);
        }
    }


    /**
     * 震坤行免密登录获取url
     *
     * @param productDescUrl 产品地址
     */
    @Override
    public String getProductUrlByZkh(String productDescUrl) {
        Date timestamp = new Date();
        String date = new DateTime(timestamp).toString(DateUtil.getDateTimeFormatter("yyyy-MM-dd HH:mm:ss"));

        JSONObject paramsToken = new JSONObject();
        String client_id = "A54319";
        String uniqueNo = "test_account";

        String sign = uniqueNo + client_id + productDescUrl + date;
        paramsToken.put("client_id", client_id);
        paramsToken.put("sign", CommonUtil.MD5(sign));
        paramsToken.put("timestamp", date);
        paramsToken.put("isZkhUser", false);
        paramsToken.put("uniqueNo", "test_account");
        paramsToken.put("redirectUrl", productDescUrl);

        String paramJsonToken = JSON.toJSONString(paramsToken);
        LOGGER.info("选购商品(震坤行)免密登录获取地址, 调用参数为: {}", paramJsonToken);

        String data = "";
        //推送确认订单
        try {
            String result = middleWareService.requestMiddleProductUrl(paramJsonToken);
            LOGGER.info("选购商品(震坤行)免密登录获取地址, 本次调用返回结果为: {}", result);

            if (StringUtils.isNotEmpty(result)) {
                final OnlineMallOrderProductUrlResponse orderResponse = JSON.parseObject(result, OnlineMallOrderProductUrlResponse.class);
                if ("200".equals(orderResponse.getErrorCode())) {
                    data = orderResponse.getData();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }


    @Override
    public OrderTrackResponse requestMiddleOrderTrack(String packageId) {
        // 接口调用日志信息
        String message = "";
        String token = findTokenByCart("ZKH");
        OrderTrackQuery orderTrackQuery = new OrderTrackQuery();
        orderTrackQuery.setPackageId(packageId);
        orderTrackQuery.setToken(token);
        String paramJson = JSON.toJSONString(orderTrackQuery);
        OrderTrackResponse response = null;
        try {
            LOGGER.info("查询发货单物流轨迹信息接口, 调用参数为: {}", paramJson);
            //推送预订单
            String result = middleWareService.requestMiddleOrderTrack(paramJson);
            LOGGER.info("查询发货单物流轨迹信息接口, 本次调用返回结果为: {}", result);
            if (StringUtils.isNotEmpty(result)) {
                response = JSON.parseObject(result, OrderTrackResponse.class);
                if (response.getSuccess()) {
                    if ("0000".equals(response.getResultCode())) {
                        return response;
                    }
                } else {
                    return response;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return response;
    }



//    @Override
//    public DelOrderResponse delOrder(Long id, String orderId) {
//        // 接口调用日志信息
//        String message = "";
//        String token = findTokenByCart("ZKH");
//        DelOrderDto delOrderDto = new DelOrderDto();
//        delOrderDto.setOrderId(orderId);
//        delOrderDto.setToken(token);
//        String paramJson = JSON.toJSONString(delOrderDto);
//        DelOrderResponse response = null;
//        try {
//            LOGGER.info("取消订单信息接口, 调用参数为: {}", paramJson);
//            //推送预订单
//            String result = middleWareService.requestMiddleDelOrder(paramJson);
//            LOGGER.info("取消订单信息接口, 本次调用返回结果为: {}", result);
//            if (StringUtils.isNotEmpty(result)) {
//                response = JSON.parseObject(result, DelOrderResponse.class);
//                if (response.getSuccess()) {
//                    if ("0000".equals(response.getResultCode())) {
//                        //采购申请id
//                        List<Long> detailIds = new ArrayList<>();
//                        List<ShoppingCartInfo> list = cartInfoService.list(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, id));
//                        if (CollectionUtils.isNotEmpty(list)) {
//                            list.forEach(item -> {
//                                //查询采购申请明细信息
//                                detailIds.add(item.getId());
//                                PurchaseApplyBillDetailClientDTO applyBillDetail = purchaseApplyBillDetailClient.getByBillCodeAndItemCode(item.getPrCode(), item.getPrItemNo());
//                                //查询采购申请明细信息
//                                detailIds.add(applyBillDetail.getId());
//                            });
//                            //删除 -  删除 状态 =  待确认商城订单 的记录后，对应的采购申请 中 采购方式 = 空 &&  transfer_status = 1
//                            purchaseApplyBillDetailClient.updatePuchaseMethode("",1,detailIds);
//                        }
//
//                        cartService.removeById(id);
//                        cartInfoService.remove(new LambdaQueryWrapper<ShoppingCartInfo>().eq(ShoppingCartInfo::getCartId, id));
//                        return response;
//                    }
//                } else {
//                    return response;
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
//        return response;

//    }


}
