package com.yami.shop.service.hb.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.internal.LinkedTreeMap;
import com.yami.shop.bean.dto.hb.*;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.ReturnMoneyStsType;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.OrderRefundParam;
import com.yami.shop.bean.vo.OrderRefundSkuVo;
import com.yami.shop.common.util.HttpUtil;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.*;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserAddrOrderService;
import com.yami.shop.service.UserService;
import com.yami.shop.service.hb.IHBOrderService;
import com.yami.shop.utils.HBSignUtil;
import com.yami.shop.utils.SmqjhUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.yami.shop.common.util.HttpUtil.post;


/**
 * 商品信息管理实现
 *
 * @author fubojin
 * @version 1.0.0
 * @since 2025-09-5
 */
@Slf4j
@Service
@AllArgsConstructor
public class HBOrderService implements IHBOrderService {
    private final HBSignUtil hbSignUtil;
    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ShopDetailMapper shopDetailMapper;
    private final UserService userService;
    private final UserAddrOrderService userAddrOrderService;
    private final ProductMapper productMapper;
    private final SkuMapper skuMapper;
    private final OrderRiderLocationMapper orderRiderLocationMapper;
    private final OrderRefundService orderRefundService;
    private final OrderService orderService;
    private final OrderRefundSkuMapper orderRefundSkuMapper;
    private final SmqjhUtil smqjhUtil;

    public HBR addHBGoods(JSONObject hbRequest) {
        try {
            String bodyStr = hbRequest.getString("body");
            log.info("订单信息，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr);
            JSONArray productList = bodyJson.getJSONArray("productList");
            List<Product> spuList = new ArrayList<>();
            List<Sku> skuList = new ArrayList<>();

            for (Object product : productList) {
                JSONObject jsonObject = JSON.parseObject(product.toString());
                String outSkuId = jsonObject.getString("outSkuId");
                String goodsInfoStr = selectHBGoodsInfo(outSkuId);
                JSONObject goodsInfoJson = JSON.parseObject(goodsInfoStr);

                // 2. 逐层解析获取productHostInfoDTOS数组
                JSONObject result = goodsInfoJson.getJSONObject("result");
                JSONObject innerResult = result.getJSONObject("result");
                JSONArray productHostInfoDTOS = innerResult.getJSONArray("productHostInfoDTOS");


                // 3. 遍历获取每个商品信息
                for (int i = 0; i < productHostInfoDTOS.size(); i++) {
                    JSONObject productInfo = productHostInfoDTOS.getJSONObject(i);

                }
            }
            // 这里可以保存到数据库
            // ProductService.saveBatch(spuList);
            // SkuService.saveBatch(skuList);

            return HBR.success("商品信息处理成功，共处理 " + spuList.size() + " 个SPU和SKU");

        } catch (Exception e) {
            log.error("处理商品信息失败：{}", e.getMessage(), e);
            return HBR.error("处理商品信息失败: " + e.getMessage());
        }
    }

    public String selectHBGoodsInfo(String outSkuId) {

        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        JSONObject skuItem = new JSONObject();
//        skuItem.put("skuId", "1328633");      // 海博商品编码
        skuItem.put("outSkuId", outSkuId);    // 商家商品编码
        // 2. 创建商品列表并添加SKU对象
        List<JSONObject> productList = new ArrayList<>();
        productList.add(skuItem);
        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("productList", productList);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 订单查询请求参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/product/getSku", build);
        log.info("post 订单查询结果：{}", post);
        return post;
    }

    @Override
    public String createOrderAsync(String channelOrderId) {

        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("channelOrderId", channelOrderId);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 创建订单推送单号参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/order/createOrderAsync", build);
        log.info("post 创建订单推送结果：{}", post);

        JSONObject jsonObject = JSONObject.parseObject(post);
        if (jsonObject!=null){
            Integer count = orderMapper.getOrderPushLog(channelOrderId);
            if (count==0){
                if (jsonObject.getBoolean("success")){
                    orderMapper.addOrderPushLog(channelOrderId,1,post);
                }else {
                    orderMapper.addOrderPushLog(channelOrderId,0,post);
                }
            }else {
                if (jsonObject.getBoolean("success")){
                    orderMapper.updateOrderPushLog(channelOrderId,1,post);
                }else {
                    orderMapper.updateOrderPushLog(channelOrderId,0,post);
                }
            }
        }
        return post;
    }

    @Override
    public String changeOrderStatus(String channelOrderId, Integer type) {
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("channelOrderId", channelOrderId);
        requestBody.put("operator", "admin");
        // 订单操作时间戳毫秒数
        requestBody.put("operatorTime", System.currentTimeMillis());
        //操作类型 （20：订单已接单 30：订单待配送 60：订单已取消 80：订单已完成）
        requestBody.put("operatorType", type);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 订单推送单号参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/order/changeOrderStatus", build);
        log.info("post 订单推送结果：{}", post);
        return post;
    }

    @Override
    public HBR createOrderResult(JSONObject hBRequest) {
        log.info("海博订单创建完成结果通知请求参数{}", hBRequest);
        JSONObject body = hBRequest.getJSONObject("body");
        String code = body.getString("code");
        if (!"0".equals(code)) {
            log.error("海博订单创建失败：{}", body.getString("message"));
        }
        return HBR.success();
    }

    @Override
    public void orderStatusNotify(JSONObject hBRequest) {
        log.info("海博订单状态变更通知请求参数{}", hBRequest);
        String bodyStr = hBRequest.getString("body");
        log.info("订单信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Integer operatorType = bodyJson.getInteger("operatorType");
        String channelOrderId = bodyJson.getString("channelOrderId");
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(channelOrderId);
        if (order == null) {
            log.error("海博订单状态回调-订单不存在，channelOrderId: {}", channelOrderId);
            return;
        }
        boolean isSmqjhOrder = Objects.equals(order.getOrderType(), 4);
        //如果是已送达直接完成并且通知海博
        order.setHbOrderStatus(operatorType);
        if (operatorType == 70 && order.getDvyType() == 3) {
            order.setHbOrderStatus(80);
        }
        if (operatorType == 70 && order.getDvyType() == 2) {
            order.setHbOrderStatus(80);
        }
        orderMapper.updateById(order);
        if (isSmqjhOrder) {
            syncSmqjhOrderStatus(channelOrderId, order.getHbOrderStatus());
        }

        //取消订单
        if (operatorType == 60) {
            log.info("取消订单{}", channelOrderId);
            try {
                changeOrderStatus(channelOrderId, 60);
            } catch (Exception e) {
                log.error("海博订单取消回调中推送HB状态失败，orderNumber: {}", channelOrderId, e);
            }
            if (!isSmqjhOrder) {
                //创建退款单
                OrderRefundParam orderRefundParam = new OrderRefundParam();
                orderRefundParam.setOrderNumber(order.getOrderNumber());
                orderRefundParam.setApplyType(1);
                orderRefundParam.setRefundType(1);
                orderRefundParam.setIsReceiver(false);
                orderRefundParam.setBuyerReason("17");
                orderRefundParam.setBuyerDesc(bodyJson.getString("reason"));
                orderRefundParam.setBuyerMobile(order.getUserMobile());
                orderRefundParam.setGoodsNum(order.getProductNums());
                orderRefundParam.setRefundAmount(order.getActualTotal());
                orderRefundParam.setPhotoFiles("");

                List<OrderItem> listByOrderNumber = orderItemMapper.getListByOrderNumber(order.getOrderNumber());
                List<OrderRefundSku> orderRefundSkuList = new ArrayList<>();
                for (OrderItem orderItem : listByOrderNumber) {

                    // 查询该订单项的所有退款记录
                    List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                            .eq(OrderRefund::getOrderNumber, orderRefundParam.getOrderNumber())
                            .eq(OrderRefund::getReturnMoneySts, 70)
                            .eq(OrderRefund::getOrderItemId, orderItem.getOrderItemId()));

                    if (ObjectUtil.isNotEmpty(orderRefundList)) {
                        // 计算该订单项已退款的总数量（按退款单ID查询退款商品）
                        Integer totalRefundedCount = calculateTotalRefundedCount(orderRefundList, orderItem.getOrderItemId());

                        // 计算剩余可退款数量
                        Integer remainingCount = orderItem.getProdCount() - totalRefundedCount;

                        if (remainingCount > 0) {
                            // 数量不同，添加剩余数量
                            OrderRefundSku orderRefundSku = new OrderRefundSku();
                            orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                            orderRefundSku.setSkuId(orderItem.getSkuId());
                            orderRefundSku.setProductCount(remainingCount); // 设置剩余数量
                            orderRefundSku.setSkuPrice(orderItem.getPrice());
                            orderRefundSkuList.add(orderRefundSku);
                        }
                        // 如果remainingCount <= 0，说明已全部退款，不添加到列表
                    } else {
                        // 没有退款记录，正常添加全部数量
                        OrderRefundSku orderRefundSku = new OrderRefundSku();
                        orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                        orderRefundSku.setSkuId(orderItem.getSkuId());
                        orderRefundSku.setProductCount(orderItem.getProdCount());
                        orderRefundSku.setSkuPrice(orderItem.getPrice());
                        orderRefundSkuList.add(orderRefundSku);
                    }
                }
                if (ObjectUtil.isEmpty(orderRefundSkuList)) {
                    return;
                }
                orderRefundParam.setOrderRefundSkuList(orderRefundSkuList);

                OrderRefund orderRefund1 = orderRefundService.getOne(new LambdaQueryWrapper<OrderRefund>()
                        .eq(OrderRefund::getOrderNumber, orderRefundParam.getOrderNumber())
                        .notIn(OrderRefund::getReturnMoneySts, Arrays.asList(30, 40, 70)));
                log.info(" 申请系统退款未处理数据参数:{}", JSONObject.toJSONString(orderRefund1));
                if (ObjectUtil.isNotEmpty(orderRefund1)) {
                    orderRefund1.setReturnMoneySts(ReturnMoneyStsType.REJECT.value());
                    orderRefundService.updateById(orderRefund1);
                    //退款单状态同步驳回
                    orderRefundService.changeStatus(orderRefund1.getRefundSn(), ReturnMoneyStsType.REJECT.value());

                    //生成流程记录
                    orderRefundService.addOrderRefundRecord(orderRefund1.getRefundId(), 20, 10, "驳回单个商家整单处理");
                }
                OrderRefund orderRefund = orderService.applyAgain(orderRefundParam, ReturnMoneyStsType.SUCCESS.value());
                orderRefundService.createRefundOrder(order.getOrderNumber(), orderRefund.getRefundSn());
            } else {
                // ========== 市民请集合订单：商家取消时处理售后单 + 创建退款单通知海博 ==========
                try {
                    log.info("市民请集合订单取消，处理退款单并通知海博，订单号: {}", channelOrderId);

                    // Issue 4: 有进行中的售后单 → 改为退款完成(70)，而非驳回
                    OrderRefund ongoingRefund = orderRefundService.getOne(new LambdaQueryWrapper<OrderRefund>()
                            .eq(OrderRefund::getOrderNumber, order.getOrderNumber())
                            .notIn(OrderRefund::getReturnMoneySts, Arrays.asList(30, 40, 70)));
                    log.info("市民请集合-进行中售后单数据:{}", JSONObject.toJSONString(ongoingRefund));
                    if (ObjectUtil.isNotEmpty(ongoingRefund)) {
                        ongoingRefund.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
                        orderRefundService.updateById(ongoingRefund);
                        // 退款单状态同步到海博
                        orderRefundService.changeStatus(ongoingRefund.getRefundSn(), ReturnMoneyStsType.SUCCESS.value());
                        // 生成流程记录
                        orderRefundService.addOrderRefundRecord(ongoingRefund.getRefundId(), 30, 10, "商家取消订单，系统自动完成退款。");
                    }

                    // Issue 3: 计算剩余商品并创建退款单通知海博
                    OrderRefundParam smqjhRefundParam = new OrderRefundParam();
                    smqjhRefundParam.setOrderNumber(order.getOrderNumber());
                    smqjhRefundParam.setApplyType(1);
                    smqjhRefundParam.setRefundType(1);
                    smqjhRefundParam.setIsReceiver(false);
                    smqjhRefundParam.setBuyerReason("17");
                    smqjhRefundParam.setBuyerDesc(bodyJson.getString("reason"));
                    smqjhRefundParam.setBuyerMobile(order.getUserMobile());
                    smqjhRefundParam.setGoodsNum(order.getProductNums());
                    smqjhRefundParam.setRefundAmount(order.getActualTotal());
                    smqjhRefundParam.setPhotoFiles("");

                    List<OrderItem> smqjhOrderItems = orderItemMapper.getListByOrderNumber(order.getOrderNumber());
                    List<OrderRefundSku> smqjhRefundSkuList = new ArrayList<>();
                    for (OrderItem orderItem : smqjhOrderItems) {
                        // 查询该订单项的所有退款记录
                        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                                .eq(OrderRefund::getOrderNumber, order.getOrderNumber())
                                .eq(OrderRefund::getReturnMoneySts, 70)
                                .eq(OrderRefund::getOrderItemId, orderItem.getOrderItemId()));

                        if (ObjectUtil.isNotEmpty(orderRefundList)) {
                            // 计算该订单项已退款的总数量（按退款单ID查询退款商品）
                            Integer totalRefundedCount = calculateTotalRefundedCount(orderRefundList, orderItem.getOrderItemId());
                            Integer remainingCount = orderItem.getProdCount() - totalRefundedCount;
                            if (remainingCount > 0) {
                                OrderRefundSku orderRefundSku = new OrderRefundSku();
                                orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                                orderRefundSku.setSkuId(orderItem.getSkuId());
                                orderRefundSku.setProductCount(remainingCount);
                                orderRefundSku.setSkuPrice(orderItem.getPrice());
                                smqjhRefundSkuList.add(orderRefundSku);
                            }
                        } else {
                            OrderRefundSku orderRefundSku = new OrderRefundSku();
                            orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                            orderRefundSku.setSkuId(orderItem.getSkuId());
                            orderRefundSku.setProductCount(orderItem.getProdCount());
                            orderRefundSku.setSkuPrice(orderItem.getPrice());
                            smqjhRefundSkuList.add(orderRefundSku);
                        }
                    }

                    if (ObjectUtil.isNotEmpty(smqjhRefundSkuList)) {
                        smqjhRefundParam.setOrderRefundSkuList(smqjhRefundSkuList);
                        // 更新订单退款状态，避免applyAgain检查报错
                        order.setRefundStatus(4); // DISAGREE
                        orderMapper.updateById(order);

                        OrderRefund newRefund = orderService.applyAgain(smqjhRefundParam, ReturnMoneyStsType.SUCCESS.value());
                        // 标记handler为已处理，避免海博回调details时重复退款（实际退款由smqjh-oms处理）
                        newRefund.setHandler(true);
                        orderRefundService.updateById(newRefund);
                        // 通知海博创建售后单
                        orderRefundService.createRefundOrder(order.getOrderNumber(), newRefund.getRefundSn());
                    }
                } catch (Exception e) {
                    log.error("市民请集合订单取消-星闪豹侧处理售后单异常，订单号: {}，异常: {}", channelOrderId, e.getMessage(), e);
                }
            }
        }
        //成功直接通知海博
        if (order.getHbOrderStatus() == 80) {
            try {
                changeOrderStatus(channelOrderId, OrderStatus.SUCCESS.value());
            } catch (Exception e) {
                log.error("海博订单完成回调中推送HB状态失败，orderNumber: {}", channelOrderId, e);
            }
        }

        //TODO 市民请集合海博状态通知
        if (isSmqjhOrder) {
            try {
                Map<Object, Object> map = new LinkedTreeMap<>();
                map.put("orderNumber", channelOrderId);
                map.put("hbOrderStatus", operatorType);
                String syncResult = HttpUtil.post(smqjhUtil.getOmsBaseUrl() + "/api/v1/xsb/order/updateHbOrderStatus", map);
                log.info("市民请集合-推送OMS订单状态结果，orderNumber: {}, operatorType: {}, result: {}",
                        channelOrderId, operatorType, syncResult);
            } catch (Exception e) {
                log.error("市民请集合-推送OMS订单状态失败，orderNumber: {}, operatorType: {}",
                        channelOrderId, operatorType, e);
            }
        }
    }

    private void syncSmqjhOrderStatus(String orderNumber, Integer hbOrderStatus) {
        try {
            Map<Object, Object> map = new LinkedTreeMap<>();
            map.put("orderNumber", orderNumber);
            map.put("hbOrderStatus", hbOrderStatus);
            String syncResult = HttpUtil.post(smqjhUtil.getOmsBaseUrl() + "/api/v1/xsb/order/updateHbOrderStatus", map);
            log.info("市民请集合-推送OMS订单状态结果，orderNumber: {}, operatorType: {}, result: {}",
                    orderNumber, hbOrderStatus, syncResult);
        } catch (Exception e) {
            log.error("市民请集合-推送OMS订单状态失败，orderNumber: {}, operatorType: {}",
                    orderNumber, hbOrderStatus, e);
        }
    }

    @Override
    public void updateLogisticStatus(JSONObject hBRequest) {
        log.info("海博订单更新通知请求参数{}", hBRequest);
        JSONObject body = hBRequest.getJSONObject("body");
        String channelOrderId = body.getString("channelOrderId");
        Long changeTime = body.getLong("changeTime");
        Integer logisticStatus = body.getInteger("logisticStatus");
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(channelOrderId);
        order.setHbLogisticStatus(logisticStatus);
        order.setDvyFlowId(body.getString("carrierNo"));
        order.setUpdateTime(new Date(changeTime));
        orderMapper.updateById(order);

        //TODO 市民请集合 物流状态推送
        if (order.getOrderType().equals(4)) {
            Map<Object, Object> map = new LinkedTreeMap<>();
            map.put("orderNumber", channelOrderId);
            map.put("logisticStatus", logisticStatus);
            map.put("dvyFlowId", body.getString("carrierNo"));

            if (logisticStatus.equals(20) || logisticStatus.equals(30)) {
                map.put("deliveryInfo", orderMapper.getRiderInfo(order.getOrderNumber()));
            }
            HttpUtil.post(smqjhUtil.getOmsBaseUrl() + "/api/v1/xsb/order/updateHbLogisticStatus", map);
        }
    }

    @Override
    public void riderLocation(JSONObject hBRequest) {
        String bodyStr = hBRequest.getString("body");
        log.info("订单信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        String channelOrderId = bodyJson.getString("channelOrderId");
        OrderRiderLocation orderRiderLocation = new OrderRiderLocation();
        orderRiderLocation.setOrderNumber(channelOrderId);
        orderRiderLocation.setCourierName(bodyJson.getString("courierName"));
        orderRiderLocation.setCourierPhone(bodyJson.getString("courierPhone"));
        orderRiderLocation.setLatitude(bodyJson.getDouble("latitude"));
        orderRiderLocation.setLongitude(bodyJson.getDouble("longitude"));
        orderRiderLocation.setPushTime(bodyJson.getLong("pushTime"));
        orderRiderLocation.setUpdateTime(new Date());

        OrderRiderLocation orderRiderLocation1 = orderRiderLocationMapper.selectOne(new LambdaQueryWrapper<OrderRiderLocation>().eq(OrderRiderLocation::getOrderNumber, channelOrderId));
        if (orderRiderLocation1 != null) {
            orderRiderLocation.setId(orderRiderLocation1.getId());
            orderRiderLocationMapper.updateById(orderRiderLocation);
        } else {
            orderRiderLocation.setCreateTime(new Date());
            orderRiderLocationMapper.insert(orderRiderLocation);
        }

        //TODO 市民请集合配送员位置
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(channelOrderId);
        if (order.getOrderType().equals(4)) {
            Map<Object, Object> map = new LinkedTreeMap<>();
            map.put("orderNumber", orderRiderLocation.getOrderNumber());
            map.put("courierName", orderRiderLocation.getCourierName());
            map.put("courierPhone", orderRiderLocation.getCourierPhone());
            map.put("pushTime", orderRiderLocation.getPushTime());
            map.put("latitude", orderRiderLocation.getLatitude());
            map.put("longitude", orderRiderLocation.getLongitude());
            HttpUtil.post(smqjhUtil.getOmsBaseUrl() + "/api/v1/xsb/order/addOrUpdateRiderLocation", map);
        }

    }

    @Override
    public void deliveryMsg(JSONObject hBRequest) {
        String bodyStr = hBRequest.getString("body");
        log.info("订单-发货消息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(bodyJson.getString("channelOrderId"));

    }

    @Override
    public void merchantToSelf(JSONObject hBRequest) {
        String bodyStr = hBRequest.getString("body");
        log.info("订单- 商家自提，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(bodyJson.getString("channelOrderId"));
        order.setDvyType(10);
        orderMapper.updateById(order);

        // 推送配送类型变更到市民请集合
        if (order.getOrderType() != null && order.getOrderType() == 4) {
            Map<Object, Object> map = new LinkedTreeMap<>();
            map.put("orderNumber", order.getOrderNumber());
            map.put("dvyType", 10);
            HttpUtil.post(smqjhUtil.getOmsBaseUrl() + "/api/v1/xsb/order/updateDvyType", map);
        }
    }

    @Override
    public void syncHBOrder() {
        List<String> orderList = orderMapper.syncOrderList();
        if (!orderList.isEmpty()){
            orderList.forEach(this::createOrderAsync);
        }
    }


    @Override
    public HBR details(JSONObject hbRequest) {
        String bodyStr = hbRequest.getString("body");
        log.info("订单信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(bodyJson.getString("channelOrderId"));

        if (order == null) {
            log.error("系统订单信息查询不到，单号：{}", bodyJson.getString("channelOrderId"));
            return HBR.error("系统订单信息查询不到，单号：" + bodyJson.getString("channelOrderId"));
        }

        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setChannelOrderId(order.getOrderNumber());
        createOrderRequest.setViewOrderId(order.getOrderNumber());
        createOrderRequest.setOrderStatus(20);
//      createOrderRequest.setDaySeq(Order.getDaySeq());门店流水号

        ShopDetail shopDetail = shopDetailMapper.selectById(order.getShopId());
        createOrderRequest.setOutStationNo(shopDetail.getOutStationNo());
        createOrderRequest.setOutStationName(shopDetail.getShopName());

        User userByUserId = userService.getUserByUserId(order.getUserId());
        if (userByUserId != null) {
            createOrderRequest.setCaution(userByUserId.getUserMobile() + "*" + order.getRemarks());
        }
        if (order.getOrderType() != null && order.getOrderType() == 4) {
            log.info("市民请结合：{}", order);
            createOrderRequest.setRecipientName(order.getConsigneeName());
            createOrderRequest.setRecipientPhone(order.getConsigneeMobile());
            createOrderRequest.setRecipientLatitude(order.getLatitude());
            createOrderRequest.setRecipientLongitude(order.getLongitude());
            createOrderRequest.setRecipientAddress(order.getConsigneeAddress());

        } else {
            UserAddrOrder userAddrOrder = userAddrOrderService.selectByAddrOrderId(order.getAddrOrderId());
            if (userAddrOrder == null) {
                log.info("收货地址信息查询不到，单号：{}", bodyJson.getString("Order"));
                createOrderRequest.setRecipientName(shopDetail.getMobile());
                createOrderRequest.setRecipientPhone(shopDetail.getMobile());
                createOrderRequest.setRecipientLatitude(Double.parseDouble(shopDetail.getShopLat()));
                createOrderRequest.setRecipientLongitude(Double.parseDouble(shopDetail.getShopLng()));
                createOrderRequest.setRecipientAddress(shopDetail.getShopAddress());
            } else {
                createOrderRequest.setRecipientName(userAddrOrder.getReceiver());
                createOrderRequest.setRecipientPhone(userAddrOrder.getMobile());
                createOrderRequest.setRecipientLatitude(userAddrOrder.getLatitude());
                createOrderRequest.setRecipientLongitude(userAddrOrder.getLongitude());
                createOrderRequest.setRecipientAddress(userAddrOrder.getAddress() + userAddrOrder.getAddressName() + userAddrOrder.getAddrDetail());
            }
        }
        int dvyType = 10;
        if (order.getDvyType() == 2) {
            dvyType = 40;
        }

        createOrderRequest.setLogisticsType(dvyType);
        createOrderRequest.setSelfPickCode(order.getSelfPickCode());
        OrderRiderLocation orderRiderLocation = orderRiderLocationMapper.selectOne(new LambdaQueryWrapper<OrderRiderLocation>().eq(OrderRiderLocation::getOrderNumber, order.getOrderNumber()));
        if (orderRiderLocation != null) {
            createOrderRequest.setCarrierNo(orderRiderLocation.getOrderNumber());//运单号，快递单号
            createOrderRequest.setLogisticsDispatcherName(orderRiderLocation.getCourierName());// 骑士姓名
            createOrderRequest.setLogisticsDispatcherMobile(orderRiderLocation.getCourierPhone());//骑士电话
//        createOrderRequest.setLogisticsStationTips(Order.getLogisticsStationTips());配送小费
        }
        createOrderRequest.setOrderAgingType(0);
        createOrderRequest.setOrderConfirmTime(order.getCreateTime().getTime());

        if (order.getPayTime() != null) {
            createOrderRequest.setOrderPayTime(order.getPayTime().getTime());
            //配送预计开始时间
            long time = order.getPayTime().getTime();
            //加一个小时
            time += 60 * 60 * 1000;
            createOrderRequest.setLogisticsPreEndTime(time);
        }
//        createOrderRequest.setOrderPickTime(order.getUpdateTime().getTime());//实际拣货完成时间
//        createOrderRequest.setOrderPickPreEndTime(order.getOrderPickPreEndTime());
        if (order.getDvyTime() != null) {
            createOrderRequest.setOrderOutStockTime(order.getDvyTime().getTime());
        }
//        createOrderRequest.setOrderLogisticsEndTime();
        if (order.getFinallyTime() != null) {
            createOrderRequest.setOrderCompletedTime(order.getFinallyTime().getTime());
        }
        if (order.getCancelTime() != null) {
            createOrderRequest.setOrderCancelTime(order.getCancelTime().getTime());
        }
//        createOrderRequest.setOrderCancelRemark(order.getOrderCancelRemark());
        createOrderRequest.setPreSaleOrder(0);
        createOrderRequest.setAdjusted(0);
//        createOrderRequest.setSelfPickCode(order.getSelfPickCode());
//        createOrderRequest.setExtra(order.getExtra());

        //订单费用信息
        OrderFee orderFee = new OrderFee();
        long totalPrice = (long) (order.getTotal() * 100);
        orderFee.setOriginalPrice(totalPrice);
        long actualTotal = (long) (order.getActualTotal() * 100);
        orderFee.setUserPayPrice(actualTotal);
        orderFee.setOrderSettlement(actualTotal);
//        orderFee.setPackingPay(0);
//        orderFee.setLunchboxPay(0);
//        orderFee.setCashOnDeliveryMedicine(0);
//        orderFee.setPointDeduction(0);
//        orderFee.setColdBoxFee(0);
//        orderFee.setPickUpPartsServerFee(0);
        long freightAmount = (long) (order.getFreightAmount() * 100);
        orderFee.setShippingFee(freightAmount);
        orderFee.setBusinessShippingFeeSubsidy(0L);
        orderFee.setPlatformShippingFeeSubsidy(0L);
        orderFee.setBusinessOrderSubsidy(0L);
        orderFee.setPlatformOrderSubsidy(0L);
        orderFee.setBusinessProductSubsidy(0L);
        orderFee.setPlatformProductSubsidy(0L);
        orderFee.setTotalOrderDiscount(0L);
        orderFee.setProductSaleTotalPrice(totalPrice);
//        orderFee.setUserIntegralDeduction(0L);用户积分抵扣金额
//        orderFee.setAdjustFee(0);
        createOrderRequest.setOrderFee(orderFee);


        //订单商品明细
        List<OrderProduct> orderProductList = new ArrayList<>();

        List<OrderItem> listByOrderNumber = orderItemMapper.getListByOrderNumber(order.getOrderNumber());
        for (OrderItem orderItem : listByOrderNumber) {
            Product product1 = productMapper.selectById(orderItem.getProdId());
            Sku sku = skuMapper.selectById(orderItem.getSkuId());
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setChannelSkuId(sku.getSkuId().toString());
            orderProduct.setOutSkuId(sku.getPartyCode());
            orderProduct.setHbSkuId(Long.parseLong(sku.getHbSkuId()));
            orderProduct.setPreSale(0);
//            orderProduct.setSkuUpc();
            orderProduct.setSkuName(product1.getProdName());
            orderProduct.setSkuWeight(sku.getWeight());
            orderProduct.setUnit(sku.getWeightUnit());
            orderProduct.setCount((long) orderItem.getProdCount());
            orderProduct.setOriginSkuPrice((long) (orderItem.getPrice() * 100));
            orderProduct.setActivitySkuPrice((long) (orderItem.getPrice() * 100));
            orderProduct.setSkuBasicSpec(sku.getSpec());
//            orderProduct.setSkuImg(sku.getPic());
            orderProduct.setBusinessSingleProductSubsidy(0L);
            orderProduct.setPlatformSingleProductSubsidy(0L);
            orderProduct.setBusinessOrderSubsidy(0L);
            orderProduct.setPlatformOrderSubsidy(0L);
            orderProduct.setTransId(sku.getSkuId().toString());
            orderProduct.setParentHBSkuId(0L);
//            orderProduct.setPromotionType(sku.getPromotionType());
//            orderProduct.setProductFeatures(sku.getProductFeatures());

            orderProductList.add(orderProduct);
        }

        createOrderRequest.setProducts(orderProductList);


        //订单支付信息
        List<OrderPayment> orderPaymentList = new ArrayList<>();
        OrderPayment orderPayment = new OrderPayment();
        if (order.getPayType() == null || order.getPayType() == 0) {
            orderPayment.setPaymentType(1301);
        } else if (order.getPayType() == 1) {
            orderPayment.setPaymentType(1002);
        } else if (order.getPayType() == 2) {
            orderPayment.setPaymentType(1001);
        } else {
            orderPayment.setPaymentType(9999);
        }

        orderPayment.setPaymentAmount(totalPrice);
        orderPayment.setPaymentNum(0);
        orderPaymentList.add(orderPayment);
        createOrderRequest.setOrderPayments(orderPaymentList);


        //订单商品活动
//        createOrderRequest.setProductActivities(order.getProductActivities());

        //订单发票信息
//        List<OrderInvoice> orderInvoiceList = new ArrayList<>();
//        OrderInvoice orderInvoice = new OrderInvoice();
//        orderInvoiceList.add(orderInvoice);
//        createOrderRequest.setOrderInvoices(orderInvoiceList);
        //打印json格式
        log.info("海博查询系统订单详情返回数据:{}", JSONObject.toJSONString(createOrderRequest));
        return HBR.success(createOrderRequest);
    }

    /**
     * 统计某个订单项在给定退款单集合中的已退款数量
     */
    private Integer calculateTotalRefundedCount(List<OrderRefund> orderRefundList, Long orderItemId) {
        if (ObjectUtil.isEmpty(orderRefundList)) {
            return 0;
        }
        int totalRefundedCount = 0;
        for (OrderRefund refund : orderRefundList) {
            if (refund == null || refund.getRefundId() == null) {
                continue;
            }
            List<OrderRefundSkuVo> orderRefundSkuVos = orderRefundSkuMapper.selectByRefundId(refund.getRefundId());
            if (ObjectUtil.isEmpty(orderRefundSkuVos)) {
                continue;
            }
            totalRefundedCount += orderRefundSkuVos.stream()
                    .filter(Objects::nonNull)
                    .filter(item -> Objects.equals(item.getOrderItemId(), orderItemId))
                    .map(OrderRefundSkuVo::getProductCount)
                    .filter(Objects::nonNull)
                    .mapToInt(Integer::intValue)
                    .sum();
        }
        return totalRefundedCount;
    }

}
