package com.gree.mall.manager.logic.order;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.order.*;
import com.gree.mall.manager.bean.order.refund.OrderOfflineRefundAddBean;
import com.gree.mall.manager.bean.websit.WebsitPartsRetVO;
import com.gree.mall.manager.commonmapper.OrderMapper;
import com.gree.mall.manager.enums.DeliveryStatusEnum;
import com.gree.mall.manager.enums.IsYesNoEnum;
import com.gree.mall.manager.enums.OrderStatusEnum;
import com.gree.mall.manager.enums.material.DirectFlagEnum;
import com.gree.mall.manager.enums.material.GoodsMaterialStockAccBillTypeEnum;
import com.gree.mall.manager.enums.material.GoodsMaterialTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.ExpressLogic;
import com.gree.mall.manager.logic.StorageLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.logic.goods.GoodsMaterialStockAccLogic;
import com.gree.mall.manager.logic.goods.JxGoodsLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.StringUtil;
import com.gree.mall.manager.zfire.bean.ZfireParamBean;
import com.gree.mall.manager.zfire.util.FieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderDeliveryLogic {

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailService orderDetailService;

    @Autowired
    OrderDetailCodeService orderDetailCodeService;

    @Autowired
    GoodsSpecService goodsSpecService;

    @Autowired
    JxGoodsLogic jxGoodsLogic;

    @Autowired
    GoodsMaterialStockAccLogic goodsMaterialStockAccLogic;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    GoodsMaterialItemService goodsMaterialItemService;

    @Autowired
    StorageLogic storageLogic;

    @Autowired
    ExpressLogic expressLogic;

    @Autowired
    OrderShareLogic orderShareLogic;

    @Autowired
    OrderLogic orderLogic;

    @Autowired
    OrderDeliveryDetailService orderDeliveryDetailService;

    @Autowired
    OrderDeliveryService orderDeliveryService;

    @Autowired
    OrderOfflineRefundLogic orderOfflineRefundLogic;

    public IPage<OrderDeliveryVO> page(ZfireParamBean zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        List<String> companyWechatIds = adminUser.getCompanyWechatIds();

        //1.组装查询条件
        ZfireParamBean zfireParam = FieldUtils.supplyParam(zfireParamBean, OrderDeliveryVO.class);



        IPage<OrderDeliveryVO> orderDeliveryVOIPage = orderMapper.orderDelivery(new Page(zfireParamBean.getPageNum(),
                        zfireParamBean.getPageSize()),
                zfireParam
                , companyWechatIds);

        return orderDeliveryVOIPage;
    }

    @Transactional(rollbackFor = Exception.class)
    public void deliverV2(SendOrderBody sendOrderBody) throws Exception {
        //判断导入条码是否符合数量
        List<OrderDetail> list = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, sendOrderBody.getOrderId()).list();
        List<OrderDetailCode> orderDetailCodes = orderDetailCodeService.lambdaQuery().
                eq(OrderDetailCode::getOrderId, sendOrderBody.getOrderId())
                .isNull(OrderDetailCode::getDeliveryId)
                .list();

        List<OrderDeliveryDetail> orderDeliveryDetails = new ArrayList<>();

        for (OrderDeliveryDetail orderDeliveryDetail : sendOrderBody.getOrderDeliveryDetailList()) {
            if (orderDeliveryDetail.getSendNum() > 0){
                orderDeliveryDetails.add(orderDeliveryDetail);
            }

        }
        if (CollectionUtils.isEmpty(orderDeliveryDetails))
            throw new RemoteServiceException("无发货产品");

        sendOrderBody.setOrderDeliveryDetailList(orderDeliveryDetails);

        sendOrderBody.setOrderDetailCodes(orderDetailCodes);





        //最后调用发货
        String delivery = this.deliverGoods(sendOrderBody.getOrderDeliveryDetailList(),sendOrderBody.getOrderId(), sendOrderBody.getLogisticsNo(),
                sendOrderBody.getCompanyCode(), sendOrderBody.getStorageId(),
                sendOrderBody.getWorkOrder(), sendOrderBody.getExchange()
                ,sendOrderBody.getPickName(),sendOrderBody.getPickPhone(),sendOrderBody.getPickType());

        //减少库存+减去条码
        this.subStock(sendOrderBody,delivery);
    }

    /**
     * 发货
     */
    @Transactional
    public String deliverGoods(List<OrderDeliveryDetail> orderDeliveryList,String orderId, String logisticsNo, String companyCode, String storageId, Boolean workOrder, Boolean exchange,String pickName,String pickPhone ,String pickType) throws Exception {
        //仓库
        Storage detail = storageLogic.detail(storageId);
        //快递公司
        DeliverGoodsBean deliverGoodsBean = new DeliverGoodsBean();
        deliverGoodsBean.setOrderId(orderId);
        if (!StringUtil.isEmpty(logisticsNo)) {
            String companyName = expressLogic.expressCompanyName(companyCode);
            deliverGoodsBean.setExpressCorp(companyName);
            deliverGoodsBean.setLogisticsNo(logisticsNo);
        }
        if(detail != null) {
            deliverGoodsBean.setWarehouse(detail.getStorageName());
            deliverGoodsBean.setWarehouseId(detail.getStorageId());
        }
        deliverGoodsBean.setSend(workOrder);
        deliverGoodsBean.setExchangeOrder(exchange);
        deliverGoodsBean.setPickName(pickName);
        deliverGoodsBean.setPickPhone(pickPhone);
        deliverGoodsBean.setPickType(pickType);
        //预检查
        preCheck(deliverGoodsBean);
        //发货
        return updateDeliverItem(deliverGoodsBean,orderDeliveryList,companyCode);
    }


    public String updateDeliverItem(DeliverGoodsBean deliverGoodsBean,List<OrderDeliveryDetail> orderDeliveryList,String companyCode) throws Exception {
        String orderId = deliverGoodsBean.getOrderId();
        OrderInfo orderInfo = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderId, orderId)
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.DFH.toString())
                .one();

        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery()
                .eq(OrderDetail::getOrderId, orderInfo.getOrderId()).list();

        Boolean isOver =true;

        for (OrderDetail orderDetail : orderDetails) {
            Integer integer = orderDeliveryList.stream().filter(item -> item.getOrderDetailId().equals(orderDetail.getOrderDetailId()))
                    .map(OrderDeliveryDetail::getSendNum).reduce(Integer::sum).orElse(0);

            List<OrderDeliveryDetail> orderDeliveryDetails = orderDeliveryDetailService.lambdaQuery().eq(OrderDeliveryDetail::getDeliveryId, orderDetail.getOrderDetailId()).list();

            orderDetail.setSendStockNum(orderDetail.getSendStockNum()+integer);

            // 总发货数量  》   订单数量  + 发货前退得金额

            if ((orderDetail.getSendStockNum()  > (orderDetail.getNum() - (orderDetail.getBeforeRefundNum()) )))
                throw new RemoteServiceException("总发货数量超过了订单数量");

            Integer num = orderDetail.getNum()-orderDetail.getBeforeRefundNum();

            if (! num.equals( orderDetail.getSendStockNum())) {
                isOver = false;
            }

            orderDetail.updateById();
        }

        if (org.apache.commons.lang3.StringUtils.isBlank(orderId)) {
            throw new RemoteServiceException("订单号不能为空");
        }

        if (orderInfo == null) {
            throw new RemoteServiceException(String.format("订单号:%s不正确或已发货,请检查", deliverGoodsBean.getOrderId()));
        }
        Storage detail = storageLogic.detailByName(orderInfo.getCompanyWechatId(), deliverGoodsBean.getWarehouse());

        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            ExpressCompany company = expressLogic.expressCompany(deliverGoodsBean.getExpressCorp());
            if (company == null) {
                throw new RemoteServiceException(String.format("订单号:%s物流公司出错,请检查", deliverGoodsBean.getOrderId()));
            }
            orderInfo.setCompanyCode(company.getCode());
            orderInfo.setCompanyName(company.getName());
        }
        orderInfo.setLogisticsNo(deliverGoodsBean.getLogisticsNo());

        if (isOver) {
            orderInfo.setOrderStatus(OrderStatusEnum.YFH.toString());
        }

        if(detail != null) {
            orderInfo.setStorageName(detail.getStorageName());
            orderInfo.setStorageAddress(detail.getStorageAddress());
            orderInfo.setStoragePhone(detail.getStorageMobile());
        }
        orderInfo.setDeliverTime(new Date());
        orderInfo.setWorkOrder(deliverGoodsBean.getSend());
        orderInfo.setExchangeOrder(deliverGoodsBean.getExchangeOrder());
        orderInfo.setPickName(deliverGoodsBean.getPickName());
        orderInfo.setPickPhone(deliverGoodsBean.getPickPhone());
        orderInfo.setPickType(deliverGoodsBean.getPickType());
        orderInfo.updateById();

        if (isOver) {
            orderShareLogic.updateOrderStatus(orderId, OrderStatusEnum.YFH.toString());

            //对接工单
            orderLogic.orderToWorkorder(orderInfo);
        }


        //订阅物流
        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            expressLogic.subscribeExpress(deliverGoodsBean.getLogisticsNo(), orderInfo.getCompanyCode(), orderInfo.getRecePhone());
        }

        OrderDelivery orderDelivery = new OrderDelivery();

        orderDelivery.setOrderId(orderInfo.getOrderId());
        orderDelivery.setStatus(DeliveryStatusEnum.SEND.getKey());
        orderDelivery.setLogisticsNo(deliverGoodsBean.getLogisticsNo());
        orderDelivery.setCompanyCode(companyCode);
        orderDelivery.setCompanyName(deliverGoodsBean.getExpressCorp());
        orderDelivery.setDeliverTime(new Date());
        orderDelivery.setPickName(deliverGoodsBean.getPickName());
        orderDelivery.setPickPhone(deliverGoodsBean.getPickPhone());
        orderDelivery.setPickType(deliverGoodsBean.getPickType());
        orderDelivery.setCompanyName(orderInfo.getCompanyName());
        orderDelivery.setCompanyWechatId(orderInfo.getCompanyWechatId());
        orderDelivery.setCompanyWechatName(orderInfo.getCompanyWechatName());

        orderDelivery.setStorageStockId(deliverGoodsBean.getWarehouseId());
        orderDelivery.setStorageStockName(deliverGoodsBean.getWarehouse());
        orderDelivery.setCompanyWechatId(orderInfo.getCompanyWechatId());

        orderDelivery.setSendInsideCodeQty(0);
        orderDelivery.setSendOutCodeQty(0);
        orderDelivery.setSendPartsCodeQty(0);
        orderDelivery.setSendNum(0);
        orderDelivery.setNum(0);

        orderDelivery.setLogisticsNo(deliverGoodsBean.getLogisticsNo());
        orderDelivery.setCompanyName(deliverGoodsBean.getExpressCorp());
        orderDelivery.setOrderId(orderInfo.getOrderId());
        orderDelivery.insert();

        orderDetailCodeService.lambdaUpdate().
                eq(OrderDetailCode::getOrderId, orderDelivery.getOrderId())
                .isNull(OrderDetailCode::getDeliveryId)
                .set(OrderDetailCode::getDeliveryId,orderDelivery.getDeliveryId())
                .update();

        List<OrderDetailCode> list = orderDetailCodeService.lambdaQuery().eq(OrderDetailCode::getOrderId, orderDelivery.getOrderId())
                .eq(OrderDetailCode::getDeliveryId, orderDelivery.getDeliveryId()).list();


        for (OrderDeliveryDetail orderDeliveryDetail : orderDeliveryList) {

            OrderDetail orderDetail = orderDetails.stream().filter(item -> item.getOrderDetailId().equals(orderDeliveryDetail.getOrderDetailId()))
                    .collect(Collectors.toList()).get(0);


            Integer insideQty = list.stream().filter(item -> item.getGoodsMaterialItemType().equals(GoodsMaterialTypeEnum.INSIDE.getKey())
                    && item.getGoodsMaterialId().equals(orderDetail.getGoodsMaterialId())
            )
                    .map(OrderDetailCode::getStockQty)
                    .reduce(Integer::sum).orElse(0);

            Integer partsQty = list.stream().filter(item -> item.getGoodsMaterialItemType().equals(GoodsMaterialTypeEnum.PARTS.getKey())
            && item.getGoodsMaterialId().equals(orderDetail.getGoodsMaterialId())
            )
                    .map(OrderDetailCode::getStockQty)
                    .reduce(Integer::sum).orElse(0);

            Integer outQty = list.stream().filter(item -> item.getGoodsMaterialItemType().equals(GoodsMaterialTypeEnum.OUT.getKey())
                    && item.getGoodsMaterialId().equals(orderDetail.getGoodsMaterialId())
            )
                    .map(OrderDetailCode::getStockQty)
                    .reduce(Integer::sum).orElse(0);

            orderDelivery.setSendInsideCodeQty(orderDelivery.getSendInsideCodeQty()+insideQty);
            orderDelivery.setSendOutCodeQty(orderDelivery.getSendOutCodeQty()+outQty);
            orderDelivery.setSendPartsCodeQty(orderDelivery.getSendPartsCodeQty()+partsQty);

            orderDelivery.setSendNum(orderDelivery.getSendNum()+orderDeliveryDetail.getSendNum());

            orderDeliveryDetail.setSendInsideCodeQty(insideQty);
            orderDeliveryDetail.setSendOutCodeQty(outQty);
            orderDeliveryDetail.setSendPartsCodeQty(partsQty);

            orderDeliveryDetail.setDeliveryId(orderDelivery.getDeliveryId());
        }
        for (OrderDetail orderDetail : orderDetails) {
            orderDelivery.setNum(orderDelivery.getNum()+(orderDetail.getNum()-orderDetail.getBeforeRefundNum()));
        }

        orderDelivery.updateById();

        orderDeliveryDetailService.saveBatch(orderDeliveryList);



       return orderDelivery.getDeliveryId();


//        User user = userLogic.getById(orderInfo.getUserId());
//        if (user != null) {
//            //对接微信发货 //自动发货对接微信(立即发货，腾讯那边会有延迟问题找不到订单，所以交给定时器处理)
//            //wechatLogic.deliver(orderInfo,user.getMiniOpenId());
//            //对接小程序发货通知
//            msgSubscriptLogic.sendFhNotice(user.getUserId(), user.getOpenId(), orderInfo.getOrderId(), orderInfo.getPayAmount()
//                    , orderInfo.getCompanyName(), orderInfo.getLogisticsNo());
//        }

    }






    private void preCheck(DeliverGoodsBean deliverGoodsBean) {
        String orderId = deliverGoodsBean.getOrderId();
        if (org.apache.commons.lang3.StringUtils.isBlank(orderId)) {
            throw new RemoteServiceException("订单号不能为空");
        }
        OrderInfo orderInfo = orderInfoService.lambdaQuery()
                .eq(OrderInfo::getOrderId, orderId)
                .eq(OrderInfo::getOrderStatus, OrderStatusEnum.DFH.toString())
                .one();

        if (orderInfo == null) {
            throw new RemoteServiceException("订单号不正确或已发货："+orderId);
        }
        if (StringUtils.isNotBlank(deliverGoodsBean.getWarehouse())) {
            Storage detail = storageLogic.detailByName(orderInfo.getCompanyWechatId(), deliverGoodsBean.getWarehouse().trim());
            if (detail == null) {
                throw new RemoteServiceException("仓库不正确，订单号："+orderId);
            }
        }
        if (!StringUtil.isEmpty(deliverGoodsBean.getLogisticsNo())) {
            ExpressCompany company = expressLogic.expressCompany(deliverGoodsBean.getExpressCorp().trim());
            if (company == null) {
                throw new RemoteServiceException("物流公司出错，订单号：" + orderId);
            }
        }
    }


    private void subStock(SendOrderBody sendOrderBody ,String deid) throws InterruptedException {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        log.info("发货"+adminUser.toString());

        //库存扣除 // 库存变更台账
        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, sendOrderBody.getOrderId()).list();
        for (OrderDetail orderDetail : orderDetails) {
            if (orderDetail.getIsVr() || StringUtil.isEmpty(orderDetail.getGoodsMaterialId()) || adminUser.getJoinCode().equals("NO"))
                continue;

            List<OrderDeliveryDetail> orderDeliveryDetailList = sendOrderBody.getOrderDeliveryDetailList().stream().filter(item -> item.getOrderDetailId().equals(orderDetail.getOrderDetailId()))
                    .collect(Collectors.toList());

            if (CollectionUtils.isEmpty(orderDeliveryDetailList))
                continue;

            OrderDeliveryDetail orderDeliveryDetail = orderDeliveryDetailList.get(0);

            if (StringUtil.isEmpty(orderDetail.getGoodsSpecId())){

            }else {
                GoodsSpec goodsSpec = goodsSpecService.getById(orderDetail.getGoodsSpecId());

                if (goodsSpec == null)
                    throw new RemoteServiceException("未找到对应商品规格");

                orderDetail.setGoodsMaterialId(goodsSpec.getGoodsCode());
            }


            jxGoodsLogic.subMaterialStock(orderDetail.getGoodsMaterialId(), orderDeliveryDetail.getSendNum(), null,sendOrderBody.getStorageId());
            goodsMaterialStockAccLogic.add(orderDetail.getGoodsMaterialId(), orderDetail.getPrice(), orderDeliveryDetail.getSendNum(), DirectFlagEnum.SUB,
                    sendOrderBody.getOrderId(), GoodsMaterialStockAccBillTypeEnum.A,sendOrderBody.getStorageId(),sendOrderBody.getStorageName());
        }

        OrderInfo orderInfo = orderInfoService.getById(sendOrderBody.getOrderId());

        log.info("发货"+adminUser.getJoinCode().toString());
        log.info("发货"+sendOrderBody.getOrderDetailCodes().toString());

        if (adminUser.getJoinCode().equals("CODE")){

            this.checkCode(orderDetails,sendOrderBody);
            //条码变更台账  条码减去批次库存
            jxGoodsLogic.subCodeAcc(sendOrderBody.getOrderDetailCodes(), orderInfo,sendOrderBody.getStorageId(),sendOrderBody.getStorageName());
        }

        //添加销售台账
        jxGoodsLogic.addGoodsSaleLedger(sendOrderBody.getOrderId(),deid);

    }


    private void checkCode(List<OrderDetail> list,SendOrderBody sendOrderBody) {

        AdminUserCom adminUser = commonLogic.getAdminUser();

        for (OrderDetail orderDetail : list) {
            if (orderDetail.getIsVr() || StringUtil.isEmpty(orderDetail.getGoodsMaterialId()) && adminUser.getJoinCode().equals("CODE"))
                continue;


            List<OrderDeliveryDetail> orderDeliveryDetailList = sendOrderBody.getOrderDeliveryDetailList().stream()
                    .filter(item -> item.getOrderDetailId().equals(orderDetail.getOrderDetailId()) )
                    .collect(Collectors.toList());



            OrderDeliveryDetail orderDeliveryDetail = orderDeliveryDetailList.get(0);

            List<GoodsMaterialItem> goodsMaterialItems = goodsMaterialItemService.lambdaQuery()
                    .eq(GoodsMaterialItem::getGoodsMaterialId, orderDetail.getGoodsMaterialId()).list();
            for (GoodsMaterialItem goodsMaterialItem : goodsMaterialItems) {
                //需要条码数量
                Integer num = goodsMaterialItem.getQty()* orderDeliveryDetail.getSendNum();

                if (num == 0)
                    return;
                if (goodsMaterialItem.getUniqueCode().equals(IsYesNoEnum.YES.getKey())){
                    List<OrderDetailCode> collect = sendOrderBody.getOrderDetailCodes().stream()
                            .filter(item -> item.getGoodsMaterialItemId().equals(goodsMaterialItem.getId())
                                    && item.getOrderDetailId().equals(orderDetail.getOrderDetailId())
                                    && StringUtil.isEmpty(item.getDeliveryId())
                            )
                            .collect(Collectors.toList());

                    if (CollectionUtils.isEmpty(collect) )
                        throw new RemoteServiceException("条码未导入");

                    if (collect.size() != num)
                        throw new RemoteServiceException(goodsMaterialItem.getName()+"此条码名称数量不对，条码数量"+collect.size()+"需要数量"+num);

                }else {
                    List<OrderDetailCode> collect = sendOrderBody.getOrderDetailCodes().stream()
                            .filter(item -> item.getGoodsMaterialItemId().equals(goodsMaterialItem.getId())
                                    && item.getOrderDetailId().equals(orderDetail.getOrderDetailId())
                                    && StringUtil.isEmpty(item.getDeliveryId())
                            )
                            .collect(Collectors.toList());

                    if (CollectionUtils.isEmpty(collect) )
                        throw new RemoteServiceException("条码未导入");

                    Integer codeNum = 0;
                    for (OrderDetailCode orderDetailCode : collect) {
                        codeNum = codeNum+orderDetailCode.getStockQty();
                    }


                    if ( !codeNum.equals(num))
                        throw new RemoteServiceException(goodsMaterialItem.getName() + "此条码名称数量不对，条码数量" + codeNum + "需要数量" + num);
                }
            }
        }
    }


    public OrderDeliveryDetailVO detail(String deliveryId) {
        OrderDelivery orderDelivery = orderDeliveryService.getById(deliveryId);

        OrderDeliveryDetailVO orderDeliveryDetailVO = BeanUtil.toBean(orderDelivery, OrderDeliveryDetailVO.class);

        List<OrderDeliveryDetail> list = orderDeliveryDetailService.lambdaQuery().eq(OrderDeliveryDetail::getDeliveryId, deliveryId).list();

        List<OrderDetailSend> orderDetailSends = new ArrayList<>();

        for (OrderDeliveryDetail orderDeliveryDetail : list) {
            OrderDetail orderDetail = orderDetailService.getById(orderDeliveryDetail.getOrderDetailId());
            OrderDetailSend orderDetailSend = BeanUtil.toBean(orderDetail, OrderDetailSend.class);
            orderDetailSend.setSendNum(orderDeliveryDetail.getSendNum());
            orderDetailSend.setSendInsideCodeQty(orderDeliveryDetail.getSendInsideCodeQty());
            orderDetailSend.setSendOutCodeQty(orderDeliveryDetail.getSendOutCodeQty());
            orderDetailSend.setSendPartsCodeQty(orderDeliveryDetail.getSendPartsCodeQty());
            orderDetailSend.setRefundNum(orderDeliveryDetail.getRefundNum());

            orderDetailSends.add(orderDetailSend);
        }

        orderDeliveryDetailVO.setOrderDetailSendList(orderDetailSends);

        return orderDeliveryDetailVO;
    }

    public void refundBatch(String deliveryId) {
        OrderDelivery orderDelivery = orderDeliveryService.getById(deliveryId);
        List<OrderDeliveryDetail> orderDeliveryDetails = orderDeliveryDetailService.lambdaQuery().eq(OrderDeliveryDetail::getDeliveryId, deliveryId).list();

        List<OrderDetail> orderDetails = orderDetailService.lambdaQuery().eq(OrderDetail::getOrderId, orderDelivery.getOrderId()).list();

        List<OrderDetailCode> orderDetailCodeList = orderDetailCodeService.lambdaQuery().eq(OrderDetailCode::getDeliveryId, deliveryId).list();

        OrderOfflineRefundAddBean orderOfflineRefundAddBean = new OrderOfflineRefundAddBean();
        orderOfflineRefundAddBean.setOrderId(orderDelivery.getOrderId());
        orderOfflineRefundAddBean.setDeliveryId(orderDelivery.getDeliveryId());
        orderOfflineRefundAddBean.setStorageStockId(orderDelivery.getStorageStockId());
        orderOfflineRefundAddBean.setStorageStockName(orderDelivery.getStorageStockName());

        Map<String, OrderDetail> orderDetailMap = orderDetails.stream().collect(Collectors.toMap(v -> v.getOrderDetailId(), Function.identity()));


        List<OrderOfflineRefundItem> orderOfflineRefundItems = new ArrayList<>();

        for (OrderDeliveryDetail orderDeliveryDetail : orderDeliveryDetails) {
            OrderDetail orderDetail = orderDetailMap.get(orderDeliveryDetail.getOrderDetailId());

            OrderOfflineRefundItem orderOfflineRefundItem = new OrderOfflineRefundItem();
            orderOfflineRefundItem.setOrderDetailId(orderDetail.getOrderDetailId());
            orderOfflineRefundItem.setOrderId(orderDetail.getOrderId());
            orderOfflineRefundItem.setRefundNum(orderDeliveryDetail.getSendNum());

            orderOfflineRefundItem.setRefundAmount(orderDetail.getPayAmount());

            orderOfflineRefundItems.add(orderOfflineRefundItem);

        }
        List<OrderOfflineItemCode> orderOfflineItemCodes = new ArrayList<>();

        for (OrderDetailCode orderDetailCode : orderDetailCodeList) {
            OrderOfflineItemCode orderOfflineItemCode = BeanUtil.toBean(orderDetailCode, OrderOfflineItemCode.class);
            orderOfflineItemCodes.add(orderOfflineItemCode);
        }


        orderOfflineRefundAddBean.setOrderOfflineRefundItems(orderOfflineRefundItems);
        orderOfflineRefundAddBean.setOrderOfflineItemCodes(orderOfflineItemCodes);

        orderOfflineRefundLogic.save(orderOfflineRefundAddBean);

    }
}
