package org.ta.pddserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.RolesAllowed;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.ta.pdd.entity.*;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pddserver.lotto.ImagePdfCollectGenerator;
import org.ta.pddserver.lotto.ImagePdfGenerator;
import org.ta.pddserver.lotto.LottoLabelInfo;
import org.ta.pddserver.model.api.request.*;
import org.ta.pddserver.model.api.response.*;
import org.ta.pddserver.model.enums.ErrorEnum;
import org.ta.pddserver.model.enums.OrderProblemType;
import org.ta.pddserver.model.enums.StatusEnum;
import org.ta.pddserver.model.pddjy.request.*;
import org.ta.pddserver.model.pddjy.response.PddServiceConsoDerelictionResponse;
import org.ta.pddserver.service.impl.*;
import org.ta.pddserver.serviceutil.WaybillOperator;
import org.ta.pddserver.utils.*;

import java.util.*;

@Slf4j
@RestController
@Tag(name = "业务对接接口", description = "仓库系统对接本接口")
@RequestMapping("/hj-api/")
@RolesAllowed({"WORKER", "ADMIN"})
public class PddLocalController {


    @Resource
    LogOrderImpl logOrderImpl;

    @Resource
    LogOrderMailDetailImpl logOrderMailDetailImpl;

    @Resource
    CollectOutMailDetailImpl collectOutMailDetailImpl;

    @Resource
    CollectOrderSendImpl collectOrderSendImpl;

    @Resource
    LogOrderMailDetailIoImpl logOrderMailDetailIoImpl;

    @Resource
    LogOrderPackageImpl logOrderPackageImpl;

    @Resource
    PackageNoticeImpl packageNoticeImpl;

    @Resource
    private CollectReceiverDetailImpl collectReceiverDetailImpl;
    @Resource
    private CollectMailDetailImpl collectMailDetailImpl;

    @Resource
    private CollectOrderImpl collectOrderImpl;

    @Resource
    UnpackMailDetailImpl unpackMailDetailImpl;

    @Resource
    UnpackNoticeImpl unpackNoticeImpl;

    @Resource
    WaybillOperator waybillOperator;
    @Resource
    private LogOrderItemImpl logOrderItemImpl;
    @Resource
    private CollectOrderDetailImpl collectOrderDetailImpl;
    @Resource
    private AreaImpl areaImpl;
    @Resource
    private StorageImpl storageImpl;
    @Resource
    private OutboundNoticeImpl outboundNoticeImpl;

    @Resource
    private LottoConfigImpl lottoConfigImpl;
    @Resource
    private PackageDetailImpl packageDetailImpl;

    @Resource
    private TempStorageImpl tempStorageImpl;
    @Resource
    private UserImpl userImpl;
    @Resource
    private ShelvesImpl shelvesImpl;
    @Resource
    private CollectFreightFeeDetailImpl collectFreightFeeDetailImpl;
    @Resource
    private LogsMailScanImpl logsMailScanService;
    @Resource
    PickRecordImpl pickRecordImpl;

    /*集运单列表*/
    @Operation(
            summary = "分页查询收到的集运单列表",
            description = "",
            deprecated = false      // 是否废弃
    )
//    @PreAuthorize("hasAnyAuthority('ADMIN', 'read')")
    @PostMapping("/logOrderList")
    public JSONObject logOrderList(HttpServletRequest request, @RequestBody LogOrderListRequest logOrderListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(logOrderImpl.getListByRequest(logOrderListRequest), "");
    }

    @PostMapping("/logOrderInfo")
    public Map<String, Object> logOrderInfo(HttpServletRequest request, @RequestBody LogOrderListRequest logOrderListRequest) {
        Map<String, Object> map = new HashMap<>();
        LogOrderInfoResponse logOrderInfoResponse = logOrderImpl.getLogOrderInfo(logOrderListRequest.getLogisticsOrderCode());
        List<LogOrderMailDetailEntity> logOrderMailDetailList = logOrderMailDetailImpl.getListByCode(logOrderListRequest.getLogisticsOrderCode());
        List<LogOrderItemResponse> logOrderItemList = logOrderItemImpl.getListByLogisticsOrderCode(logOrderListRequest.getLogisticsOrderCode());
        map.put("info", logOrderInfoResponse);
        map.put("detailList", logOrderMailDetailList);
        map.put("itemList", logOrderItemList);
        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /*包裹列表*/
    @Operation(
            summary = "签收、入库列表",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/logOrderMailDetailList")
    public JSONObject logOrderMailDetailList(HttpServletRequest request, @RequestBody LogOrderMailDetailListRequest logOrderMailDetailListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(logOrderMailDetailImpl.getListByCodeNo(logOrderMailDetailListRequest), "");
    }

    /*运单号查询*/
    @Operation(
            summary = "运单号查询订单信息,精准查询",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/mailNoSelect")
    public JSONObject mailNoSelect(HttpServletRequest request, @RequestBody MailNoRequest mailNoRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(mailNoRequest.getMailNo());
        return JsonResponse.generateLocalCommonSuccessResponse(mailNoResponse, "");
    }

    /*待拆包列表*/
    @Operation(
            summary = "分页查询拆包列表",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/packageNoticeList")
    public JSONObject packageNoticeList(HttpServletRequest request, @RequestBody PackageNoticeRequest packageNoticeRequest) {

        return JsonResponse.generateLocalCommonSuccessResponse(packageNoticeImpl.getList(packageNoticeRequest), "");
    }

    /*待拆包查询*/
    @Operation(
            summary = "运单号查询拆包信息,精准查询",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/packageScan")
    public Map<String, Object> packageScan(HttpServletRequest request, @RequestBody MailNoRequest mailNoRequest) {
        UnpackMailDetailEntity unpackMailDetailEntity = unpackMailDetailImpl.getByMailNo(mailNoRequest.getMailNo());
        if (unpackMailDetailEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到拆包信息");
        }
        UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(unpackMailDetailEntity.getOrderCode());
        if (unpackNoticeEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "信息获取失败，请检查上传信息");
        }

        List<UnpackMailDetailEntity> list = unpackMailDetailImpl.getListByCode(unpackMailDetailEntity.getOrderCode());

        Map<String, Object> map = new HashMap<>();
        map.put("logOrder", unpackNoticeEntity);
        map.put("list", list);

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

//    /*出库列表*/
//    @Operation(
//            summary = "运单号查询拆包信息,精准查询",
//            description = "",
//            deprecated = false      // 是否废弃
//    )
//    @PostMapping("/collectMailDetailList")
//    public JSONObject collectMailDetailList(HttpServletRequest request, @RequestBody CollectMailDetailListRequest collectMailDetailListRequest) {
//
//        return JsonResponse.generateLocalCommonSuccessResponse(collectMailDetailImpl.getList(collectMailDetailListRequest));
//    }

    /*待拣货列表*/
    @Operation(
            summary = "分页查询拣货、出库列表",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/collectOrderList")
    public JSONObject collectOrderList(HttpServletRequest request, @RequestBody CollectOrderListRequest collectOrderListRequest) {

        return JsonResponse.generateLocalCommonSuccessResponse(collectOrderImpl.getList(collectOrderListRequest), "");
    }

    @PostMapping("/collectOrderUnprintList")
    public JSONObject collectOrderUnprintList(HttpServletRequest request, @RequestBody CollectOrderListRequest collectOrderListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(collectOrderImpl.getUnprintList(collectOrderListRequest), "");
    }

    /*出库详情*/
    @Operation(
            summary = "出库详情",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/collectOrderInfo")
    public Map<String, Object> collectOrderInfo(HttpServletRequest request, @RequestBody CollectOrderListRequest collectOrderListRequest) {
        CollectOrderInfoResponse collectOrderResponse = collectOrderImpl.getInfoByOrderCode(collectOrderListRequest.getOrderCode());
        List<CollectMailDetailEntity> mailDetailList = collectMailDetailImpl.getListByOrderCode(collectOrderListRequest.getOrderCode());
        List<CollectOrderDetailResponse> orderDetailList = collectOrderDetailImpl.getListByOrderCode(collectOrderListRequest.getOrderCode());
        CollectReceiverDetailEntity collectReceiver = collectReceiverDetailImpl.getInfoByOrderCode(collectOrderListRequest.getOrderCode());
        Map<String, Object> map = new HashMap<>();
        map.put("info", collectOrderResponse);
        map.put("mail", mailDetailList);
        map.put("detail", orderDetailList);
        map.put("receiver", collectReceiver);

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /*拣货扫码*/
    @Operation(
            summary = "运单号，拣货扫码",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/collectMailDetailScan")
    public Map<String, Object> collectMailDetailScan(HttpServletRequest request, @RequestBody CollectMailDetailRequest collectMailDetailRequest) {

        Map<String, Object> map = new HashMap<>();
        CollectMailDetailEntity mailDetailEntity = collectMailDetailImpl.getByMailNo(collectMailDetailRequest.getMailNo());
        if (mailDetailEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未找到需要拣货的包裹信息");
        }


        List<CollectMailDetailEntity> list = collectMailDetailImpl.getListByOrderCode(mailDetailEntity.getOrderCode());

        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(mailDetailEntity.getOrderCode());

        map.put("collectOrder", collectOrderResponse);
        map.put("collectOutMailDetail", mailDetailEntity);
        map.put("list", list);

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }


    /*待拣包裹列表接口*/
    @Operation(
            summary = "运单号，出库扫码",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/mailNoSelectAll")
    public Map<String, Object> mailNoSelectAll(HttpServletRequest request, @RequestBody MailNoRequest mailNoRequest) {
        Map<String, Object> map = new HashMap<>();
        CollectMailDetailEntity collectMailDetail = collectMailDetailImpl.getByMailNo(mailNoRequest.getMailNo());
        if (collectMailDetail == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "该包裹不存在出库信息");
        }
        List<CollectMailDetailEntity> list = collectMailDetailImpl.getListByOrderCode(collectMailDetail.getOrderCode());
        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(collectMailDetail.getOrderCode());
        CollectReceiverDetailEntity collectReceiver = collectReceiverDetailImpl.getInfoByOrderCode(collectMailDetail.getOrderCode());

        map.put("collectMailDetail", collectMailDetail);
        map.put("list", list);
        map.put("collectOrder", collectOrderResponse);
        map.put("collectReceiver", collectReceiver);

//        CollectOutMailDetailEntity collectOutMailDetail = collectOutMailDetailImpl.getInfoByMailNo(mailNoRequest.getMailNo());
//        List<CollectOutMailDetailResponse> list = collectOutMailDetailImpl.getListByOrderCode(collectOutMailDetail.getOrderCode());

//        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(collectOutMailDetail.getOrderCode());

//        map.put("list", list);
//        map.put("collectOutMailDetail", collectOutMailDetail);

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /**
     * 入库异常
     */
    @Operation(
            summary = "入库异常",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/inBoundError")
    public JSONObject inBoundError(HttpServletRequest request, @RequestBody InBoundRequest inBoundRequest) {

        LogOrderMailDetailEntity mailNoResponse = logOrderMailDetailImpl.getByMailNo(inBoundRequest.getMailNo());
        PddServiceConsoInboundRequest notifyRequest = new PddServiceConsoInboundRequest();
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(mailNoResponse.getLogisticsOrderCode());
        int currNum = logOrderEntity.getNum();
        int num = logOrderMailDetailImpl.getInboundedCountByOrderCode(mailNoResponse.getLogisticsOrderCode());

        //判断是否存在入库信息
        if (mailNoResponse.getStatus() == StatusEnum.INBOUND.getCode()) {
            //重复入库
            mailNoResponse.setEnterTime(TimeTool.getNowDate());
        } else {
            mailNoResponse.setEnterTime(TimeTool.getNowDate());
            mailNoResponse.setStatus(StatusEnum.INBOUND.getCode());
            num += 1;
        }
        notifyRequest.setPackageQuantity(num);
        mailNoResponse.setLength(inBoundRequest.getLength().intValue());
        mailNoResponse.setWidth(inBoundRequest.getWidth().intValue());
        mailNoResponse.setHeight(inBoundRequest.getHeight().intValue());
        mailNoResponse.setWeight(inBoundRequest.getWeight().intValue());

        notifyRequest.setPackageInfo(new PddServiceConsoInboundRequest.PackageInfo());
        notifyRequest.getPackageInfo().setMailNo(mailNoResponse.getMailNo());
        notifyRequest.getPackageInfo().setExpressCode(mailNoResponse.getExpressCode());
        notifyRequest.getPackageInfo().setLength(inBoundRequest.getLength());
        notifyRequest.getPackageInfo().setHeight(inBoundRequest.getHeight());
        notifyRequest.getPackageInfo().setWidth(inBoundRequest.getWidth());
        notifyRequest.getPackageInfo().setActualWeight(inBoundRequest.getWeight());
        notifyRequest.getPackageInfo().setWeight((long) PddJYPriceTool.calculateWeight(inBoundRequest.getLength().intValue(), inBoundRequest.getWidth().intValue(), inBoundRequest.getHeight().intValue(), inBoundRequest.getWeight().intValue(), true));
        notifyRequest.getPackageInfo().setGoodsType(inBoundRequest.getGoodsType());

        notifyRequest.setResult(new PddServiceConsoInboundRequest.Result());
        notifyRequest.getResult().setCode(inBoundRequest.getCode());
        notifyRequest.getResult().setDesc(ErrorEnum.getByCode(inBoundRequest.getCode()).getDesc());
        notifyRequest.getResult().setRemark(ErrorEnum.getByCode(inBoundRequest.getCode()).getDesc());

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.inbound");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
//        String resp = PddHttpTool.postRequest(requestModel);
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();

        logOrderMailDetailIoEntity.setMailNo(inBoundRequest.getMailNo());
        logOrderMailDetailIoEntity.setExpressCode(mailNoResponse.getExpressCode());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        logOrderMailDetailIoEntity.setExpressCode(mailNoResponse.getExpressCode());
        logOrderMailDetailIoEntity.setStatus(StatusEnum.BOUNDERROR.getCode());
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);
        logOrderMailDetailIoEntity.setAction("INBOUND-ERROR");
        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        mailNoResponse.setStatus(StatusEnum.BOUNDERROR.getCode());

        logOrderMailDetailImpl.updateById(mailNoResponse);

        return JsonResponse.generateLocalCommonSuccessResponse(true, "");
    }

    /**
     * 拣货异常
     */
    @Operation(
            summary = "拣货异常",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/unpackError")
    public JSONObject beginPickError(HttpServletRequest request, @RequestBody FinishUnpackRequest finishUnpackRequest) {

        CollectOrderEntity collectOrderEntity = new CollectOrderEntity();

        PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);

        notifyRequest.setBizAction(finishUnpackRequest.getAction());
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();

        if (("begin_pick").equals(finishUnpackRequest.getAction())) {

            collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(finishUnpackRequest.getOrderCode());

            if (collectOrderEntity == null) {
                return JsonResponse.generateLocalCommonFailedResponse("-1", "信息获取失败，请检查参数");
            }

            logOrderMailDetailIoEntity.setStatus(StatusEnum.BEGINPICKERROR.getCode());

            notifyRequest.setBizActionDesc("开始拣货");


        } else if (("finish_pick").equals(finishUnpackRequest.getAction())) {

            collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(finishUnpackRequest.getOrderCode());

            if (collectOrderEntity == null) {
                return JsonResponse.generateLocalCommonFailedResponse("-1", "信息获取失败，请检查参数");
            }

            logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHPICKERROR.getCode());

            notifyRequest.setBizActionDesc("拣货完成");
            logOrderMailDetailIoEntity.setAction("BEGIN-PICK");

        } else if (("finish_unpack").equals(finishUnpackRequest.getAction())) {

//            LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(finishUnpackRequest.getOrderCode());
//
//            if (logOrderEntity == null) {
//                return JsonResponse.generateLocalCommonFailedResponse("-1", "未查到集运单信息，请检查参数");
//            }

            UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(finishUnpackRequest.getOrderCode());
            if (unpackNoticeEntity == null) {
                return JsonResponse.generateLocalCommonFailedResponse("-1", "未查到集运单信息，请检查参数");
            }

            notifyRequest.setOrderCode(finishUnpackRequest.getOrderCode());
            notifyRequest.setBizActionDesc("拆包完成");
            notifyRequest.setUnpackRemark("");

            logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHUNPACKERROR.getCode());

            notifyRequest.setPackageInfos(new ArrayList<>());

            for (FinishUnpackRequest.PackageInfo lists : finishUnpackRequest.getPackageInfo()) {
                PddServiceConsoCoBizActionNotifyRequest.PackageInfo packageInfo = new PddServiceConsoCoBizActionNotifyRequest.PackageInfo();
                packageInfo.setWeight(lists.getWeight());
                packageInfo.setWidth(lists.getWidth());
                packageInfo.setHeight(lists.getHeight());
                packageInfo.setLength(lists.getLength());
                packageInfo.setActualWeight(PddJYPriceTool.calculateWeight(lists.getLength(), lists.getWidth(), lists.getHeight(), lists.getWeight(), true));
                packageInfo.setConsoType(unpackNoticeEntity.getConsoType());
                packageInfo.setGoodsType(finishUnpackRequest.getGoodsType());

                notifyRequest.getPackageInfos().add(packageInfo);

                LogOrderPackageEntity logOrderPackageEntity = new LogOrderPackageEntity();
                logOrderPackageEntity.setStatus("" + StatusEnum.FINISHUNPACK.getCode());
                logOrderPackageEntity.setLogisticsOrderCode(finishUnpackRequest.getOrderCode());
                logOrderPackageEntity.setPackageType(finishUnpackRequest.getGoodsType());
                logOrderPackageEntity.setLength(lists.getLength());
                logOrderPackageEntity.setWidth(lists.getWidth());
                logOrderPackageEntity.setHeight(lists.getHeight());
                logOrderPackageEntity.setWeight(lists.getWeight());

                logOrderPackageImpl.save(logOrderPackageEntity);


//                logOrderEntity.setStatus(logOrderMailDetailIoEntity.getStatus());
//                logOrderImpl.updateById(logOrderEntity);

                // todo 错误代码，需验证
//                PackageNoticeEntity packageNoticeEntity = packageNoticeImpl.getByOrderCode(finishUnpackRequest.getOrderCode());
//
//                if (packageNoticeEntity != null) {
//                    packageNoticeEntity.setStatus("" + logOrderMailDetailIoEntity.getStatus());
//                    packageNoticeImpl.updateById(packageNoticeEntity);
//
//                }
                unpackNoticeImpl.updateStatusByOrderCode(unpackNoticeEntity.getOrderCode(), StatusEnum.FINISHUNPACK.getCode());
                logOrderMailDetailIoEntity.setAction("BFINISH-PICK");

            }
        }
        notifyRequest.setResult(new PddServiceConsoCoBizActionNotifyRequest.Result());

        notifyRequest.getResult().setCode(finishUnpackRequest.getCode());
        notifyRequest.getResult().setDesc(ErrorEnum.getByCode(finishUnpackRequest.getCode()).getDesc());
        notifyRequest.getResult().setRemark(ErrorEnum.getByCode(finishUnpackRequest.getCode()).getDesc());


        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.co.biz.action.notify");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }


//        logOrderMailDetailIoEntity.setMailNo(finishUnpackRequest.getMailNo());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(finishUnpackRequest.getOrderCode());

        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);

        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        if (("begin_pick").equals(finishUnpackRequest.getAction()) || ("finish_pick").equals(finishUnpackRequest.getAction())) {

            //更新collect_mail_detail
            List<CollectMailDetailEntity> collectMailDetailEntityList = collectMailDetailImpl.getListByOrderCode(finishUnpackRequest.getOrderCode());
            for (CollectMailDetailEntity lists : collectMailDetailEntityList) {
                lists.setStatus(logOrderMailDetailIoEntity.getStatus());
                collectMailDetailImpl.updateById(lists);
            }

            collectOrderEntity.setStatus(logOrderMailDetailIoEntity.getStatus());

            collectOrderImpl.updateById(collectOrderEntity);
        }

        return JsonResponse.generateLocalCommonSuccessResponse(true, "");
    }

    /**
     * 拣货异常
     */
    @Operation(
            summary = "出库通知、开始拣货、拣货完成",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/finishUnpack")
    public JSONObject finishUnpack(HttpServletRequest request, @RequestBody FinishUnpackRequest finishUnpackRequest) {

        String action = finishUnpackRequest.getAction();
//        UnpackMailDetailEntity unpackMailDetailEntity = unpackMailDetailImpl.getByMailNo(finishUnpackRequest.getMailNo());

        PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setOrderCode(finishUnpackRequest.getOrderCode());
        notifyRequest.setBizAction(action);
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();

        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
        CollectOrderEntity collectOrderEntity = null;
        if (action.equals("begin_pick")) {

            collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(finishUnpackRequest.getOrderCode());

            if (collectOrderEntity == null) {
                return JsonResponse.generateLocalCommonFailedResponse("-1", "信息获取失败，请检查参数");
            }

            logOrderMailDetailIoEntity.setStatus(StatusEnum.BEGINPICK.getCode());

            notifyRequest.setBizActionDesc("开始拣货");
            notifyResult.setCode(0);
        } else if (action.equals("finish_pick")) {
            collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(finishUnpackRequest.getOrderCode());

            if (collectOrderEntity == null) {
                return JsonResponse.generateLocalCommonFailedResponse("-1", "信息获取失败，请检查参数");
            }

            logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHPICK.getCode());

            notifyRequest.setBizActionDesc("拣货完成");
            notifyResult.setCode(0);
        } else if (action.equals("finish_unpack")) {
            UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(finishUnpackRequest.getOrderCode());
//            LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(finishUnpackRequest.getOrderCode());
//            if (logOrderEntity == null) {
//                return JsonResponse.generateLocalCommonFailedResponse("-1", "未查到集运单信息，请检查参数");
//            }
//            logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHUNPACK.getCode());

            notifyRequest.setBizActionDesc("拆包完成");
            notifyRequest.setUnpackRemark("");
            notifyResult.setCode(0);
            notifyRequest.setPackageInfos(new ArrayList<>());

            List<LogOrderPackageEntity> list = new ArrayList<>();

            for (FinishUnpackRequest.PackageInfo lists : finishUnpackRequest.getPackageInfo()) {

                PddServiceConsoCoBizActionNotifyRequest.PackageInfo packageInfo = new PddServiceConsoCoBizActionNotifyRequest.PackageInfo();
                packageInfo.setWeight(lists.getWeight());
                packageInfo.setWidth(lists.getWidth());
                packageInfo.setHeight(lists.getHeight());
                packageInfo.setLength(lists.getLength());
                packageInfo.setActualWeight(PddJYPriceTool.calculateWeight(lists.getLength(), lists.getWidth(), lists.getHeight(), lists.getWeight(), true));
                packageInfo.setConsoType(unpackNoticeEntity.getConsoType());
                packageInfo.setGoodsType(finishUnpackRequest.getGoodsType());

                notifyRequest.getPackageInfos().add(packageInfo);

                LogOrderPackageEntity logOrderPackageEntity = new LogOrderPackageEntity();
                logOrderPackageEntity.setStatus("" + logOrderMailDetailIoEntity.getStatus());
                logOrderPackageEntity.setLogisticsOrderCode(finishUnpackRequest.getOrderCode());
                logOrderPackageEntity.setPackageType(finishUnpackRequest.getGoodsType());
                logOrderPackageEntity.setLength(lists.getLength());
                logOrderPackageEntity.setWidth(lists.getWidth());
                logOrderPackageEntity.setHeight(lists.getHeight());
                logOrderPackageEntity.setWeight(lists.getWeight());

                logOrderPackageImpl.save(logOrderPackageEntity);

                PackageNoticeEntity packageNoticeEntity = packageNoticeImpl.getByOrderCode(finishUnpackRequest.getOrderCode());

                if (packageNoticeEntity != null) {
                    packageNoticeEntity.setStatus("" + logOrderMailDetailIoEntity.getStatus());
                    packageNoticeImpl.updateById(packageNoticeEntity);
                }


            }

        }
        notifyRequest.setResult(notifyResult);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.co.biz.action.notify");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }


//        logOrderMailDetailIoEntity.setMailNo(finishUnpackRequest.getMailNo());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(finishUnpackRequest.getOrderCode());
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);
        logOrderMailDetailIoEntity.setAction("FINISH-UNPACK");
        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        if (action.equals("begin_pick") || action.equals("finish_pick")) {

            //更新collect_mail_detail
            List<CollectMailDetailEntity> collectMailDetailEntityList = collectMailDetailImpl.getListByOrderCode(finishUnpackRequest.getOrderCode());
            for (CollectMailDetailEntity lists : collectMailDetailEntityList) {
                lists.setStatus(logOrderMailDetailIoEntity.getStatus());
                collectMailDetailImpl.updateById(lists);
            }

            collectOrderEntity.setStatus(logOrderMailDetailIoEntity.getStatus());
            collectOrderImpl.updateById(collectOrderEntity);

        }

        return JsonResponse.generateLocalCommonSuccessResponse(true, "");
    }


    // 开始拣货集合函数
    public String startPick(String orderCode) {
        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
        PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setOrderCode(orderCode);
        notifyRequest.setBizAction("begin_pick");
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        logOrderMailDetailIoEntity.setStatus(StatusEnum.BEGINPICK.getCode());

        notifyRequest.setBizActionDesc("开始拣货");
        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
        notifyResult.setCode(0);

        notifyRequest.setResult(notifyResult);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.co.biz.action.notify");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。";
        }

        logOrderMailDetailIoEntity.setLogisticsOrderCode(orderCode);
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);
        logOrderMailDetailIoEntity.setAction("START_PICK");
        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        //更新collect_mail_detail
        List<CollectMailDetailEntity> collectMailDetailEntityList = collectMailDetailImpl.getListByOrderCode(orderCode);
        for (CollectMailDetailEntity lists : collectMailDetailEntityList) {
            lists.setStatus(logOrderMailDetailIoEntity.getStatus());
            collectMailDetailImpl.updateById(lists);
        }

        collectOrderImpl.updateStatusByOrderCode(logOrderMailDetailIoEntity.getStatus(), orderCode);
        return null;

    }

    // 拣货完成集合函数
    public String completePick(String orderCode) {
        PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setOrderCode(orderCode);
        notifyRequest.setBizAction("finish_pick");
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();

        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
        logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHPICK.getCode());

        notifyRequest.setBizActionDesc("拣货完成");
        notifyResult.setCode(0);
        notifyRequest.setResult(notifyResult);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.co.biz.action.notify");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return "拼多多上送拣货完成信息失败：" + respObject.getString("message") + "；请联系技术人员。";
        }

        logOrderMailDetailIoEntity.setLogisticsOrderCode(orderCode);
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);
        logOrderMailDetailIoEntity.setAction("FINISH-PICK");
        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        collectOrderImpl.updateStatusByOrderCode(logOrderMailDetailIoEntity.getStatus(), orderCode);

        return null;
    }

    /*拣货完成后出库*/
    @Operation(
            summary = "拣货完成后出库",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/outBound")
    public JSONObject outBound(HttpServletRequest request, @RequestBody OutBoundRequest outBoundRequest) {
        PddServiceConsoOutboundRequest notifyRequest = new PddServiceConsoOutboundRequest();

        List<OutBoundRequest.OutBoundList> outBoundList = outBoundRequest.getOutBound();

        // TODO 此处异常，需要处理
        //获取所有可出库订单
        List<CollectMailDetailEntity> list = collectMailDetailImpl.getListByOrderCode(outBoundRequest.getOrderCode());

        if (list != null && !list.isEmpty()) {
            // 拆单操作
            // 存储需要删除的元素
            List<CollectMailDetailEntity> toRemoveList = new ArrayList<>();
            List<OutBoundRequest.OutBoundList> toRemoveOutBound = new ArrayList<>();


            for (CollectMailDetailEntity lists : list) {
                for (OutBoundRequest.OutBoundList outBoundLists : outBoundList) {
                    if (lists.getMailNo().equals(outBoundLists.getMailNo())) {
                        toRemoveList.add(lists);
                        toRemoveOutBound.add(outBoundLists);
                    }
                }
            }

            list.removeAll(toRemoveList);
            outBoundList.removeAll(toRemoveOutBound);

//            if (list.size() > 0 || outBoundList.size() > 0) {
//                //出库信息与已存信息不匹配，无法出库
//                return JsonResponse.generateLocalCommonFailedResponse("-1", "出库单数异常");
//            }
        }
        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setSegmentCode(collectOrderResponse.getSegmentCode());
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setIsSplitOut("N");
        notifyRequest.setPackageInfos(new ArrayList<>());


        if (outBoundRequest.getOutPackageList() != null && outBoundRequest.getOutPackageList().size() > 0) {
            for (OutBoundRequest.OutPackage outPackage : outBoundRequest.getOutPackageList()) {
                PddServiceConsoOutboundRequest.PackageInfo packageInfo = new PddServiceConsoOutboundRequest.PackageInfo();
                notifyRequest.getPackageInfos().add(packageInfo);
                if (notifyRequest.getSegmentCode().equals("RETURNSELLER")) {
                    packageInfo.setOutboundMailNo(outPackage.getMailNo());
                    packageInfo.setExpressCode(outPackage.getExpressCode());
                } else {
                    // ---- 开始   修改为不认同前端输入，改为系统自动生成
                    WaybillOperator.WaybillInfo waybillInfo = waybillOperator.generateWaybillInfo();
                    packageInfo.setOutboundMailNo(waybillInfo.getMailNo());
                    packageInfo.setExpressCode(waybillInfo.getExpressCode());
                    outPackage.setExpressCode(waybillInfo.getExpressCode());
                    outPackage.setMailNo(waybillInfo.getMailNo());
                    // 结束 ----
                }

                packageInfo.setPackageType(outPackage.getPackageType());
                packageInfo.setLength(outPackage.getLength());
                packageInfo.setWidth(outPackage.getWidth());
                packageInfo.setHeight(outPackage.getHeight());
                packageInfo.setWeight(outPackage.getWeight());
                if (outPackage.getOutBound() != null && outPackage.getOutBound().size() > 0) {
                    packageInfo.setInboundMailDetails(new ArrayList<>());
                    for (String mailNo : outPackage.getOutBound()) {
                        PddServiceConsoOutboundRequest.InboundMailDetail inboundMailDetail = new PddServiceConsoOutboundRequest.InboundMailDetail();
                        inboundMailDetail.setMailNo(mailNo);
                        LogOrderMailDetailEntity mailDetailEntity = logOrderMailDetailImpl.getByMailNo(mailNo);
                        inboundMailDetail.setExpressCode(mailDetailEntity.getExpressCode());
                        packageInfo.getInboundMailDetails().add(inboundMailDetail);
                    }
                }
            }
        }


        notifyRequest.setSenderDetail(new PddServiceConsoOutboundRequest.SenderDetail());

        CollectOrderSendEntity collectOrderSendEntity = collectOrderSendImpl.getInfo();

        notifyRequest.getSenderDetail().setName(collectOrderSendEntity.getName());
        notifyRequest.getSenderDetail().setTelePhone(collectOrderSendEntity.getTelePhone());
        notifyRequest.getSenderDetail().setCountry(collectOrderSendEntity.getCountry());
        notifyRequest.getSenderDetail().setProvince(collectOrderSendEntity.getProvince());
        notifyRequest.getSenderDetail().setCity(collectOrderSendEntity.getCity());
        notifyRequest.getSenderDetail().setDistrict(collectOrderSendEntity.getDistrict());
        notifyRequest.getSenderDetail().setDetailAddress(collectOrderSendEntity.getDetailAddress());


        CollectReceiverDetailEntity collectReceiverDetailEntity = collectReceiverDetailImpl.getInfoByOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setReceiverDetail(new PddServiceConsoOutboundRequest.ReceiverDetail());
        notifyRequest.getReceiverDetail().setName(collectReceiverDetailEntity.getName());
        notifyRequest.getReceiverDetail().setTelePhone(collectReceiverDetailEntity.getTelePhone());
        notifyRequest.getReceiverDetail().setCountry(collectReceiverDetailEntity.getCountry());
        notifyRequest.getReceiverDetail().setProvince(collectReceiverDetailEntity.getProvince());
        notifyRequest.getReceiverDetail().setCity(collectReceiverDetailEntity.getCity());
        notifyRequest.getReceiverDetail().setDistrict(collectReceiverDetailEntity.getDistrict());
        notifyRequest.getReceiverDetail().setDetailAddress(collectReceiverDetailEntity.getDetailAddress());

        notifyRequest.setResult(new PddServiceConsoOutboundRequest.Result());
        notifyRequest.getResult().setCode(0);


        log.info("derelictionRequest:{}", JSON.toJSONString(notifyRequest));
        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.outbound");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多订单出库失败");
        }
        int i = 1;
        if (outBoundRequest.getOutPackageList() != null && outBoundRequest.getOutPackageList().size() > 0) {
            for (OutBoundRequest.OutPackage outPackage : outBoundRequest.getOutPackageList()) {
                LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
                logOrderMailDetailIoEntity.setMailNo(outPackage.getMailNo());
                logOrderMailDetailIoEntity.setUpMailNo(outPackage.getMailNo());
                logOrderMailDetailIoEntity.setExpressCode(outPackage.getExpressCode());
                logOrderMailDetailIoEntity.setLogisticsOrderCode(outBoundRequest.getOrderCode());
                logOrderMailDetailIoEntity.setExpressCode(outPackage.getExpressCode());
                logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHOUTBOUND.getCode());
                logOrderMailDetailIoEntity.setAction("FINISHOUTBOUND");
                logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
                logOrderMailDetailIoEntity.setResp(resp);
                logOrderMailDetailIoEntity.setWxOrderCode(notifyRequest.getOrderCode() + "-" + (i ++));
                if (outPackage.getOutBound() != null && outPackage.getOutBound().size() > 0) {
                    logOrderMailDetailIoEntity.setRemarks(JSONObject.toJSONString(outPackage.getOutBound()));
                }
                logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

                //更新collect_mail_detail
                for (CollectMailDetailEntity lists : list) {
                    Boolean result = collectMailDetailImpl.updateByMailNo(lists.getMailNo(), logOrderMailDetailIoEntity.getStatus());
                }
                WorldexUtil.noticePddOrderOut(logOrderMailDetailIoEntity.getWxOrderCode());
            }
        }
        collectOrderImpl.updateOrderStatus(StatusEnum.FINISHOUTBOUND.getCode(), collectOrderResponse.getUid());

        return JsonResponse.generateLocalCommonSuccessResponse(outBoundRequest.getOutPackageList(), "");
    }

    /*拣货完成后出库*/
    @Operation(
            summary = "拣货完成后出库异常",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/outBoundError")
    public JSONObject outBoundError(HttpServletRequest request, @RequestBody OutBoundRequest outBoundRequest) {
        PddServiceConsoOutboundRequest notifyRequest = new PddServiceConsoOutboundRequest();

        List<OutBoundRequest.OutBoundList> outBoundList = outBoundRequest.getOutBound();

        // TODO 此处异常，需要处理
        //获取所有可出库订单
        List<CollectMailDetailEntity> list = collectMailDetailImpl.getListByOrderCode(outBoundRequest.getOrderCode());

        if (list != null && !list.isEmpty()) {
            // 拆单操作
            // 存储需要删除的元素
            List<CollectMailDetailEntity> toRemoveList = new ArrayList<>();
            List<OutBoundRequest.OutBoundList> toRemoveOutBound = new ArrayList<>();


            for (CollectMailDetailEntity lists : list) {
                for (OutBoundRequest.OutBoundList outBoundLists : outBoundList) {
                    if (lists.getMailNo().equals(outBoundLists.getMailNo())) {
                        toRemoveList.add(lists);
                        toRemoveOutBound.add(outBoundLists);
                    }
                }
            }

            list.removeAll(toRemoveList);
            outBoundList.removeAll(toRemoveOutBound);

            if (list.size() > 0 || outBoundList.size() > 0) {
                //出库信息与已存信息不匹配，无法出库
                return JsonResponse.generateLocalCommonFailedResponse("-1", "出库单数异常");
            }
        }
        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setSegmentCode(collectOrderResponse.getSegmentCode());
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setIsSplitOut("N");
        notifyRequest.setPackageInfos(new ArrayList<>());

        /*
        if (outBoundRequest.getOutPackageList() != null && outBoundRequest.getOutPackageList().size() > 0) {
            for (OutBoundRequest.OutPackage outPackage : outBoundRequest.getOutPackageList()) {
                PddServiceConsoOutboundRequest.PackageInfo packageInfo = new PddServiceConsoOutboundRequest.PackageInfo();
                notifyRequest.getPackageInfos().add(packageInfo);
                // ---- 开始   修改为不认同前端输入，改为系统自动生成
//                packageInfo.setOutboundMailNo(outPackage.getMailNo());
//                packageInfo.setExpressCode(outPackage.getExpressCode());
                if (notifyRequest.getSegmentCode().equals("RETURNSELLER")) {
                    packageInfo.setOutboundMailNo(outPackage.getMailNo());
                    packageInfo.setExpressCode(outPackage.getExpressCode());
                } else {
                    // ---- 开始   修改为不认同前端输入，改为系统自动生成
                    WaybillOperator.WaybillInfo waybillInfo = waybillOperator.generateWaybillInfo();
                    packageInfo.setOutboundMailNo(waybillInfo.getMailNo());
                    packageInfo.setExpressCode(waybillInfo.getExpressCode());
                    outPackage.setExpressCode(waybillInfo.getExpressCode());
                    outPackage.setMailNo(waybillInfo.getMailNo());
                    // 结束 ----
                }
                // 结束 ----
                packageInfo.setPackageType(outPackage.getPackageType());
                packageInfo.setLength(outPackage.getLength());
                packageInfo.setWidth(outPackage.getWidth());
                packageInfo.setHeight(outPackage.getHeight());
                packageInfo.setWeight(outPackage.getWeight());
                if (outPackage.getOutBound() != null && outPackage.getOutBound().size() > 0) {
                    packageInfo.setInboundMailDetails(new ArrayList<>());
                    for (String mailNo : outPackage.getOutBound()) {
                        PddServiceConsoOutboundRequest.InboundMailDetail inboundMailDetail = new PddServiceConsoOutboundRequest.InboundMailDetail();
                        inboundMailDetail.setMailNo(mailNo);
                        LogOrderMailDetailEntity mailDetailEntity = logOrderMailDetailImpl.getByMailNo(mailNo);
                        inboundMailDetail.setExpressCode(mailDetailEntity.getExpressCode());
                        packageInfo.getInboundMailDetails().add(inboundMailDetail);
                    }
                }
            }
        }
        */

        notifyRequest.setSenderDetail(new PddServiceConsoOutboundRequest.SenderDetail());

        CollectOrderSendEntity collectOrderSendEntity = collectOrderSendImpl.getInfo();

        notifyRequest.getSenderDetail().setName(collectOrderSendEntity.getName());
        notifyRequest.getSenderDetail().setTelePhone(collectOrderSendEntity.getTelePhone());
        notifyRequest.getSenderDetail().setCountry(collectOrderSendEntity.getCountry());
        notifyRequest.getSenderDetail().setProvince(collectOrderSendEntity.getProvince());
        notifyRequest.getSenderDetail().setCity(collectOrderSendEntity.getCity());
        notifyRequest.getSenderDetail().setDistrict(collectOrderSendEntity.getDistrict());
        notifyRequest.getSenderDetail().setDetailAddress(collectOrderSendEntity.getDetailAddress());


        CollectReceiverDetailEntity collectReceiverDetailEntity = collectReceiverDetailImpl.getInfoByOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setReceiverDetail(new PddServiceConsoOutboundRequest.ReceiverDetail());
        notifyRequest.getReceiverDetail().setName(collectReceiverDetailEntity.getName());
        notifyRequest.getReceiverDetail().setTelePhone(collectReceiverDetailEntity.getTelePhone());
        notifyRequest.getReceiverDetail().setCountry(collectReceiverDetailEntity.getCountry());
        notifyRequest.getReceiverDetail().setProvince(collectReceiverDetailEntity.getProvince());
        notifyRequest.getReceiverDetail().setCity(collectReceiverDetailEntity.getCity());
        notifyRequest.getReceiverDetail().setDistrict(collectReceiverDetailEntity.getDistrict());
        notifyRequest.getReceiverDetail().setDetailAddress(collectReceiverDetailEntity.getDetailAddress());

        notifyRequest.setResult(new PddServiceConsoOutboundRequest.Result());
        notifyRequest.getResult().setCode(outBoundRequest.getResult().getCode());
        notifyRequest.getResult().setDesc(outBoundRequest.getResult().getDesc());
        notifyRequest.getResult().setRemark(outBoundRequest.getResult().getRemark());


        log.info("derelictionRequest:{}", JSON.toJSONString(notifyRequest));
        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.outbound");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }

        if (outBoundRequest.getOutPackageList() != null && outBoundRequest.getOutPackageList().size() > 0) {
            for (OutBoundRequest.OutPackage outPackage : outBoundRequest.getOutPackageList()) {
                LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
                logOrderMailDetailIoEntity.setMailNo(outPackage.getMailNo());
                logOrderMailDetailIoEntity.setExpressCode(outPackage.getExpressCode());
                logOrderMailDetailIoEntity.setLogisticsOrderCode(outBoundRequest.getOrderCode());
                logOrderMailDetailIoEntity.setExpressCode(outPackage.getExpressCode());
                logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHOUTBOUND.getCode());
                logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
                logOrderMailDetailIoEntity.setResp(resp);
                if (outPackage.getOutBound() != null && outPackage.getOutBound().size() > 0) {
                    logOrderMailDetailIoEntity.setRemarks(JSONObject.toJSONString(outPackage.getOutBound()));
                }
                logOrderMailDetailIoEntity.setAction("OUTBOUND-ERROR");
                logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

                //更新collect_mail_detail
                for (CollectMailDetailEntity lists : list) {
                    Boolean result = collectMailDetailImpl.updateByMailNo(lists.getMailNo(), logOrderMailDetailIoEntity.getStatus());
                }
            }
        }


        return JsonResponse.generateLocalCommonSuccessResponse(true, "");
    }

    /* 无主件号识别快递包裹识别 */
    @Operation(
            summary = "无主件号识别快递包裹识别",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/dereliction")
    public JSONObject dereliction(HttpServletRequest request, @RequestBody DerelictionRequest derelictionRequest) {
        PddServiceConsoDerelictionRequest notifyRequest = new PddServiceConsoDerelictionRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setMailNo(derelictionRequest.getMailNo());
        notifyRequest.setExpressCode(derelictionRequest.getExpressCode());
        notifyRequest.setDereRecogCode(derelictionRequest.getDereRecogCode());

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.dereliction");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }
        PddServiceConsoDerelictionResponse response = JSON.parseObject(resp, PddServiceConsoDerelictionResponse.class);

        if (response != null) {
            String logisticsOrderCode = response.getLogisticsOrderCode();
            if (logisticsOrderCode != null) {
                return JsonResponse.generateLocalCommonSuccessResponse(response, "");
            }
        }
        return JsonResponse.generateOpenCommonFailedResponse(-1, "该包裹信息无法识别");

    }

    /* 问题件反馈 */
    @Operation(
            summary = "问题件反馈",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/problemOrderNotify")
    public JSONObject problemOrderNotify(HttpServletRequest request, @RequestBody ProblemOrderNotifyRequest problemOrderNotifyRequest) {
        OrderProblemType problemType = OrderProblemType.verify(problemOrderNotifyRequest.getReasonCode());
        if (problemType == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "问题类型有误");
        }
        LogOrderMailDetailEntity mailDetailEntity = logOrderMailDetailImpl.getByMailNo(problemOrderNotifyRequest.getMailNo());
        if (mailDetailEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到包裹信息");
        }

        PddServiceConsoProblemOrderNotifyRequest notifyRequest = new PddServiceConsoProblemOrderNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setMailInfos(new ArrayList<>());
        PddServiceConsoProblemOrderNotifyRequest.MailInfo mailInfo = new PddServiceConsoProblemOrderNotifyRequest.MailInfo();
        notifyRequest.getMailInfos().add(mailInfo);
        mailInfo.setMailNo(problemOrderNotifyRequest.getMailNo());
        mailInfo.setOrderCode(mailDetailEntity.getLogisticsOrderCode());
        mailInfo.setExpressCode(mailDetailEntity.getExpressCode());

        mailInfo.setReasonCode(problemType.getValue());

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.problem.order.notify");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }
        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
        logOrderMailDetailIoEntity.setMailNo(mailDetailEntity.getMailNo());
        logOrderMailDetailIoEntity.setStatus(StatusEnum.INBOUND.getCode());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(mailDetailEntity.getLogisticsOrderCode());
        logOrderMailDetailIoEntity.setExpressCode(mailDetailEntity.getExpressCode());
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);
        logOrderMailDetailIoEntity.setAction("PROBLEMNOTIFY");
        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        JSONObject response = JSONObject.parseObject(resp).getJSONObject("response");
        if (response != null) {
            if (response.getBoolean("success")) {
                unpackMailDetailImpl.updateMailToProblem(mailDetailEntity.getMailNo());
                collectMailDetailImpl.updateMailToProblem(mailDetailEntity.getMailNo());
                logOrderMailDetailImpl.updateMailToProblem(mailDetailEntity.getMailNo());
                return JsonResponse.generateLocalCommonSuccessResponse(mailDetailEntity, "问题件申报成功");
            }
        }
        return JsonResponse.generateOpenCommonFailedResponse(-1, "问题件申报失败");

    }

    /*区域列表*/
    @PostMapping("/areaList")
    public JSONObject areaList(HttpServletRequest request, @RequestBody AreaListRequest areaListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(areaImpl.areaList(areaListRequest), "");
    }

    /*区域新增*/
    @PostMapping("/areaAdd")
    public JSONObject areaAdd(HttpServletRequest request, @RequestBody AreaEntity areaEntity) {
        return areaImpl.areaAdd(areaEntity);
    }

    /*区域修改*/
    @PostMapping("/areaEdit")
    public JSONObject areaEdit(HttpServletRequest request, @RequestBody AreaEntity areaEntity) {
        return areaImpl.areaEdit(areaEntity);
    }

    /*区域删除*/
    @PostMapping("/areaDele")
    public JSONObject areaDele(HttpServletRequest request, @RequestBody AreaEntity areaEntity) {
        return areaImpl.areaDele(areaEntity);
    }

    /*通过运单号查询存放区域*/
    @PostMapping("/storageSelect")
    public JSONObject storageSelect(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        StorageResponse response = storageImpl.storageSelect(storageRequest.getMailNo());
        if (response != null) {
            if (response.getPlace() != null && !response.getPlace().isEmpty()) {
                response.setCode(response.getCode() + '>' + response.getPlace());
            }
        }
        return JsonResponse.generateLocalCommonSuccessResponse(response, "");
    }

    /*确认上架*/
    @PostMapping("/storageAdd")
    public JSONObject storageAdd(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        StorageEntity storageEntity = storageImpl.getInfoByMailNo(storageRequest.getMailNo());
        if (storageEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未查询到商品区域信息");
        }
        if (storageEntity.getPlace() != null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "请勿重复上架");
        }
        storageEntity.setPlace(storageRequest.getPlace());
        storageImpl.updateById(storageEntity);
        return JsonResponse.generateLocalCommonSuccessResponse(true, "上架成功");
    }

    /*待拆包列表*/
    @PostMapping("/unpackNoticeList")
    public JSONObject unpackNoticeList(HttpServletRequest request, @RequestBody UnpackNoticeListRequest unpackNoticeListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(unpackNoticeImpl.getListByRequest(unpackNoticeListRequest), "");
    }

    /*拆包待打单列表*/
    @PostMapping("/unpackLabelList")
    public JSONObject unpackLabelList(HttpServletRequest request, @RequestBody UnpackNoticeListRequest unpackNoticeListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(unpackNoticeImpl.getUnprintListByRequest(unpackNoticeListRequest), "");
    }

    /*详情列表*/
    @PostMapping("/storageList")
    public JSONObject storageList(HttpServletRequest request, @RequestBody StorageListRequest storageListRequest) {
        Map<String, Object> map = storageImpl.storageList(storageListRequest.getLogisticsOrderCode());
        String info = null;
        if (pickRecordImpl.checkAddReceiver(storageListRequest.getLogisticsOrderCode())) {
            info = "请注意，您是本拣货单的责任拣货人";
        }
        return JsonResponse.generateLocalCommonSuccessResponse(map, info);
    }

    /*待出库列表*/
    @PostMapping("/outboundNoticeList")
    public JSONObject outboundNoticeList(HttpServletRequest request, @RequestBody OutboundNoticeListRequest outboundNoticeListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(outboundNoticeImpl.getListByRequest(outboundNoticeListRequest), "");
    }

    /*拣货下架*/
    @PostMapping("/storageDel")
    public JSONObject storageDel(HttpServletRequest request, @RequestBody StorageDelRequest storageDelRequest) {
        List<StorageListResponse> list = storageImpl.storageLists(storageDelRequest.getLogisticsOrderCode());

        List<String> toMailList = new ArrayList<>();
        List<StorageListResponse> toRemoveList = new ArrayList<>();
        Map<String, Integer> integerMap = new HashMap<>();

        if (list.size() != storageDelRequest.getMailNo().size()) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "下架包裹数量异常");
        }
        StorageListResponse first = list.get(0);

        String ids = "(";

        for (StorageListResponse lists : list) {
            for (String mailNoLists : storageDelRequest.getMailNo()) {
                if (lists.getMailNo().equals(mailNoLists)) {
                    if (integerMap.containsKey(lists.getCode())) {
                        integerMap.put(lists.getCode(), integerMap.get(lists.getCode()) + 1);
                    } else {
                        integerMap.put(lists.getCode(), 1);
                    }
                    toRemoveList.add(lists);
                    toMailList.add(mailNoLists);
//                    logsMailScanService.makeLog(lists.getMailNo(), "DOWNBOARD");
                    ids += "'" + mailNoLists + "',";
                }
            }
        }

        ids = ids.substring(0, ids.length() - 1);
        ids += ")";

        list.removeAll(toRemoveList);
        storageDelRequest.getMailNo().removeAll(toMailList);

        if (list.size() != 0 || storageDelRequest.getMailNo().size() != 0) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "下架包裹信息异常");
        }

        //删除位置
        storageImpl.storageDel(ids);

        // 释放货架位置
        for (String code: integerMap.keySet()) {
            String[] codes = code.split("-");
            shelvesImpl.updateNum(-1, codes[0].substring(0, 1), Integer.parseInt(codes[0].substring(1)), Integer.parseInt(codes[1]));

        }

        //根据type 区分修改状态
        if (("pick").equals(storageDelRequest.getType())) {
            // 出库拣货下架
            outboundNoticeImpl.updateStatusByOrderCode(storageDelRequest.getLogisticsOrderCode(), StatusEnum.PICKDOWN.getCode());
        } else {
            // 拆包下架
            unpackNoticeImpl.updateStatusByOrderCode(storageDelRequest.getLogisticsOrderCode(), StatusEnum.UNPACKFINISHPICK.getCode());
        }

        return JsonResponse.generateLocalCommonSuccessResponse(true, "");
    }

    // 发往韩国的面单打印
    @PostMapping("/mailLabel")
    public JSONObject mailLabel(HttpServletRequest request, HttpServletResponse response, @RequestBody MailNoRequest mailNoRequest) {
        String mailNo = mailNoRequest.getMailNo();
        LogOrderMailDetailIoEntity mailDetailIoEntity = logOrderMailDetailIoImpl.getOutboundByMailNo(mailNo);
        if (mailDetailIoEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未找到出库运单");
        }
        CollectReceiverDetailEntity receiverDetailEntity = collectReceiverDetailImpl.getInfoByOrderCode(mailDetailIoEntity.getLogisticsOrderCode());
        LottoLabelInfo lottoLabelInfo = lottoConfigImpl.getLottoLabelInfoByPostCode(receiverDetailEntity.getPostCode());
        if (lottoLabelInfo == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "获取快递终端信息异常");
        }
        byte[] bytes = ImagePdfGenerator.generatePdfWithTextImage(
                mailNo,
                lottoLabelInfo.getPortCode(),
                receiverDetailEntity.getName(),
                receiverDetailEntity.getTelePhone(),
                receiverDetailEntity.getPostCode(),
                receiverDetailEntity.getDetailAddress(),
                receiverDetailEntity.getOrderCode(),
                lottoLabelInfo.getArea1(),
                lottoLabelInfo.getArea2(),
                lottoLabelInfo.getArea3(),
                lottoLabelInfo.getArea4());

        if (bytes == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "面单制作失败");
        }
        JSONObject result = new JSONObject();
        result.put("mailNo", mailNo);
        result.put("file", Base64.getEncoder().encodeToString(bytes));
        return JsonResponse.generateLocalCommonSuccessResponse(result, "");
    }

    // 拆包的临时面单打印
    /*拆包PDF*/
    @PostMapping("/unpackLabel")
    public JSONObject unpackLabel(HttpServletRequest request, HttpServletResponse response, @RequestBody UnpackNoticeRequest unpackNoticeRequest) {

        String orderCode = unpackNoticeRequest.getOrderCode();
        UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(orderCode);
        if (unpackNoticeEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未找到拆包信息");
        }

        List<UnpackMailDetailEntity> list = unpackMailDetailImpl.getListByCode(unpackNoticeRequest.getOrderCode());

        byte[] bytes = ImagePdfCollectGenerator.generatePdQRfWithCollectTextImage(orderCode, "拆包", "" + list.size() + "件");


        if (bytes == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "面单制作失败");
        }
        unpackNoticeImpl.updatePrintNum(1, unpackNoticeEntity.getUid());
        pickRecordImpl.checkAddRecord(orderCode, 1);
        JSONObject result = new JSONObject();
        result.put("orderCode", orderCode);
        result.put("file", Base64.getEncoder().encodeToString(bytes));
        return JsonResponse.generateLocalCommonSuccessResponse(result, "");
    }

    // 合包的临时面单打印
    /*出库PDF*/
    @PostMapping("/collectLabel")
    public JSONObject collectLabel(HttpServletRequest request, HttpServletResponse response, @RequestBody UnpackNoticeRequest unpackNoticeRequest) {

        String orderCode = unpackNoticeRequest.getOrderCode();
        CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(orderCode);
        if (collectOrderEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未找到出库信息");
        }

        List<PackageDetailEntity> packages = packageDetailImpl.getByOrderCode(orderCode);

        byte[] bytes = null;
        if(packages!= null && packages.size()>0){
            bytes = ImagePdfCollectGenerator.generatePdQRfWithCollectTextImage(orderCode, "拆包出库", "已打包" + packages.size() + "件");
        } else {
            List<CollectMailDetailEntity> mailDetailList = collectMailDetailImpl.getListByOrderCode(orderCode);
            bytes = ImagePdfCollectGenerator.generatePdQRfWithCollectTextImage(orderCode, orderCode.startsWith("PT") ? "退运" : "出库", "" + mailDetailList.size() + "件");
        }

        if (bytes == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "面单制作失败");
        }
        collectOrderImpl.updatePrintNum(1, collectOrderEntity.getOrderCode());
        String info = "";
        PickRecordEntity pickRecordEntity = pickRecordImpl.checkAddRecord(orderCode, 2);
        if (pickRecordEntity.getType() == 2 && orderCode.startsWith("PP")) {
            // 合包单，此处处理开始拣货
            info = this.startPick(orderCode);
        }
        JSONObject result = new JSONObject();
        result.put("orderCode", orderCode);
        result.put("file", Base64.getEncoder().encodeToString(bytes));
        return JsonResponse.generateLocalCommonSuccessResponse(result, info);
    }

    @PostMapping("/packageScanOrderCode")
    public Map<String, Object> packageScanOrderCode(HttpServletRequest request, @RequestBody PackageScanOrderCodeRequest packageScanOrderCodeRequest) {
        Map<String, Object> map = new HashMap<>();
        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(packageScanOrderCodeRequest.getOrderCode());
        if (collectOrderResponse != null) {
            List<CollectMailDetailEntity> list = collectMailDetailImpl.getListByOrderCode(packageScanOrderCodeRequest.getOrderCode());
            map.put("list", list);
            map.put("orderInfo", collectOrderResponse);
            map.put("packType", "出库");
        } else {
            UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(packageScanOrderCodeRequest.getOrderCode());
            if (unpackNoticeEntity == null) {
                return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到该打包单信息");
            }
            List<UnpackMailDetailEntity> list = unpackMailDetailImpl.getListByCode(packageScanOrderCodeRequest.getOrderCode());
            map.put("list", list);
            map.put("orderInfo", unpackNoticeEntity);
            map.put("packType", "拆包");
        }

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    // 打包后的临时面单打印
    /*出库PDF*/
    @PostMapping("/packageMailLabel")
    public JSONObject packageMailLabel(HttpServletRequest request, HttpServletResponse response, @RequestBody PackageLabelRequest labelRequest) {

        String orderCode = labelRequest.getOrderCode();
        String typeString = null;
        if (orderCode.startsWith("PT")) {
            typeString = "退运";
        } else {
            CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(orderCode);
            if (collectOrderEntity == null) {
                typeString = "拆包";
            } else {
                typeString = "出库";
            }
        }


        List<PackageDetailEntity> list = packageDetailImpl.getByOrderCode(orderCode);

//        byte[] bytes = ImagePdfCollectGenerator.generatePdfWithCollectTextImage(orderCode + "-" + labelRequest.getMailNo(), typeString, "" + list.size() + "件");
        byte[] bytes = ImagePdfCollectGenerator.generatePdQRfWithCollectTextImage(orderCode + "-" + labelRequest.getMailNo(), typeString, "" + list.size() + "件");

        if (bytes == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "面单制作失败");
        }
        JSONObject result = new JSONObject();
        result.put("orderCode", orderCode);
        result.put("file", Base64.getEncoder().encodeToString(bytes));
        return JsonResponse.generateLocalCommonSuccessResponse(result, "请打印");
    }

    @PostMapping("/packageComplete")
    public JSONObject packageComplete(HttpServletRequest request, @RequestBody PackageCompleteRequest completeRequest) {
        List<String> mailList = new ArrayList<>();
        String orderCode = completeRequest.getOrderCode();
        for (PackageCompleteRequest.OutPackage outPackage : completeRequest.getOutPackageList()) {
            mailList.addAll(outPackage.getOutBound());
        }
        boolean unpack = false;
        //获取所有可出库订单
        List<CollectMailDetailEntity> list = collectMailDetailImpl.getListByOrderCode(orderCode);
        if (list == null || list.isEmpty()) {
            unpack = true;
        }
        packageDetailImpl.removeByOrderCode(completeRequest.getOrderCode());
        List<PackageDetailEntity> results = new ArrayList<>();
        for (PackageCompleteRequest.OutPackage outPackage : completeRequest.getOutPackageList()) {
            PackageDetailEntity detailEntity = new PackageDetailEntity();
            detailEntity.setOrderCode(completeRequest.getOrderCode());
            detailEntity.setMailNo(outPackage.getMailNo());
            detailEntity.setWidth(outPackage.getWidth());
            detailEntity.setHeight(outPackage.getHeight());
            detailEntity.setLength(outPackage.getLength());
            detailEntity.setWeight(outPackage.getWeight());
            detailEntity.setInMails(JSONObject.toJSONString(outPackage.getOutBound()));
            detailEntity.setPackageType(outPackage.getPackageType());
            detailEntity.setOrderType(outPackage.getOrderType());
//            detailEntity.setOperator(SecurityContextHolder.getContext().getAuthentication().getName());
            packageDetailImpl.save(detailEntity);
            results.add(detailEntity);
        }
        if (!unpack) {
            CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(orderCode);
            String info = "打包成功";
            if (collectOrderEntity == null && collectOrderEntity.getStatus() >= StatusEnum.UNPACKBEGINPICK.getCode() && collectOrderEntity.getStatus()< StatusEnum.PICKDOWN.getCode()) {
                String msg = this.completePick(orderCode);
                if (msg != null) {
                    info += ";" + msg;
                }
            }
            return JsonResponse.generateLocalCommonSuccessResponse(completeRequest.getOutPackageList(), info);
        }
        log.info("拆包单，同时发送拆包信息");
        String action = "finish_unpack";

        PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setOrderCode(orderCode);
        notifyRequest.setBizAction(action);
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
        CollectOrderEntity collectOrderEntity = new CollectOrderEntity();
        UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(orderCode);

        notifyRequest.setBizActionDesc("拆包完成");
        notifyRequest.setUnpackRemark("");
        notifyResult.setCode(0);
        notifyRequest.setPackageInfos(new ArrayList<>());


        for (PackageCompleteRequest.OutPackage outPackage : completeRequest.getOutPackageList()) {

            PddServiceConsoCoBizActionNotifyRequest.PackageInfo packageInfo = new PddServiceConsoCoBizActionNotifyRequest.PackageInfo();
            packageInfo.setWeight(outPackage.getWeight());
            packageInfo.setWidth(outPackage.getWidth());
            packageInfo.setHeight(outPackage.getHeight());
            packageInfo.setLength(outPackage.getLength());
            packageInfo.setActualWeight(PddJYPriceTool.calculateWeight(outPackage.getLength(), outPackage.getWidth(), outPackage.getHeight(), outPackage.getWeight(), true));
            packageInfo.setConsoType(unpackNoticeEntity.getConsoType());
            packageInfo.setGoodsType(outPackage.getOrderType());
            notifyRequest.getPackageInfos().add(packageInfo);

            LogOrderPackageEntity logOrderPackageEntity = new LogOrderPackageEntity();
            logOrderPackageEntity.setStatus("" + logOrderMailDetailIoEntity.getStatus());
            logOrderPackageEntity.setLogisticsOrderCode(orderCode);
            logOrderPackageEntity.setPackageType(outPackage.getOrderType());
            logOrderPackageEntity.setLength(outPackage.getLength());
            logOrderPackageEntity.setWidth(outPackage.getWidth());
            logOrderPackageEntity.setHeight(outPackage.getHeight());
            logOrderPackageEntity.setWeight(outPackage.getWeight());
            logOrderPackageImpl.save(logOrderPackageEntity);

            PackageNoticeEntity packageNoticeEntity = packageNoticeImpl.getByOrderCode(orderCode);

            if (packageNoticeEntity != null) {
                packageNoticeEntity.setStatus("" + logOrderMailDetailIoEntity.getStatus());
                packageNoticeImpl.updateById(packageNoticeEntity);
            }


        }
        notifyRequest.setResult(notifyResult);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.co.biz.action.notify");
        requestModel.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requestModel.setClient_id(PddAPIConfig.CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, PddAPIConfig.CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }


//        logOrderMailDetailIoEntity.setMailNo(finishUnpackRequest.getMailNo());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(orderCode);
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);
        logOrderMailDetailIoEntity.setAction("FINISH-UNPACK");
        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);
        return JsonResponse.generateLocalCommonSuccessResponse(completeRequest.getOutPackageList(), "打包成功且拆包成功");
    }

    @PostMapping("/packageScanUnpackOrderCode")
    public JSONObject packageScanUnpackOrderCode(HttpServletRequest request, @RequestBody UnpackNoticeRequest unpackNoticeRequest) {
        UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(unpackNoticeRequest.getOrderCode());
        if (unpackNoticeEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到拆包通知信息");
        }
        List<PackageDetailEntity> packageDetailEntityList = packageDetailImpl.getByOrderCode(unpackNoticeRequest.getOrderCode());
        Map<String, Object> map = new HashMap<>();
        map.put("detail", unpackNoticeEntity);
        map.put("list", packageDetailEntityList);
        return JsonResponse.generateLocalCommonSuccessResponse(map, "获取成功");
    }

    @PostMapping("/packageScanOutboundOrderCode")
    public Map<String, Object> packageScanOutboundOrderCode(HttpServletRequest request, @RequestBody UnpackNoticeRequest unpackNoticeRequest) {
        Map<String, Object> map = new HashMap<>();
        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(unpackNoticeRequest.getOrderCode());

        if (collectOrderResponse == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "集运单信息不存在");
        }
        List<PackageDetailEntity> list = packageDetailImpl.getByOrderCode(unpackNoticeRequest.getOrderCode());
        CollectReceiverDetailEntity collectReceiver = collectReceiverDetailImpl.getInfoByOrderCode(unpackNoticeRequest.getOrderCode());

        map.put("list", list);
        map.put("collectOrder", collectOrderResponse);
        map.put("collectReceiver", collectReceiver);

//        CollectOutMailDetailEntity collectOutMailDetail = collectOutMailDetailImpl.getInfoByMailNo(mailNoRequest.getMailNo());
//        List<CollectOutMailDetailResponse> list = collectOutMailDetailImpl.getListByOrderCode(collectOutMailDetail.getOrderCode());

//        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(collectOutMailDetail.getOrderCode());

//        map.put("list", list);
//        map.put("collectOutMailDetail", collectOutMailDetail);

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    @PostMapping("/collectOrderAllInfo")
    public Map<String, Object> collectOrderAllInfo(HttpServletRequest request, @RequestBody UnpackNoticeRequest unpackNoticeRequest) {
        String orderCode = unpackNoticeRequest.getOrderCode();
        CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(orderCode);
        if (collectOrderEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到出库信息");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("CollectOrder", collectOrderEntity);
        CollectReceiverDetailEntity collectReceiver = collectReceiverDetailImpl.getInfoByOrderCode(orderCode);
        map.put("CollectReceiverDetail", collectReceiver);
        List<CollectOrderDetailResponse> list = collectOrderDetailImpl.getListByOrderCode(orderCode);
        map.put("CollectOrderDetail", list);
        List<CollectMailDetailEntity> list1 = collectMailDetailImpl.getListByOrderCode(orderCode);
        map.put("CollectMailDetail", list1);
        OutboundNoticeEntity noticeEntity = outboundNoticeImpl.getByOrderCode(orderCode);
        map.put("OutboundNotice", noticeEntity);
        List<LogOrderMailDetailIoEntity> list2 = logOrderMailDetailIoImpl.getOutByOrderCode(orderCode);
        map.put("LogOrderMailDetailIo", list2);
        UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(orderCode);
        map.put("UnpackNotice", unpackNoticeEntity);
        List<UnpackMailDetailEntity> list3 = unpackMailDetailImpl.getListByCode(orderCode);
        map.put("UnpackMailDetail", list3);
        map.put("payOrder", collectFreightFeeDetailImpl.getByOrderCode(orderCode));
        map.put("packageDetail", packageDetailImpl.getByOrderCode(orderCode));
        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    @PostMapping("/collectOrderAllInfoByPayOrder")
    public Map<String, Object> collectOrderAllInfoByPayOrder(HttpServletRequest request, @RequestBody UnpackNoticeRequest unpackNoticeRequest) {
        String payOrderCode = unpackNoticeRequest.getOrderCode();
        CollectFreightFeeDetailEntity freightFeeDetail = collectFreightFeeDetailImpl.getByPayOrder(payOrderCode);
        if (freightFeeDetail == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到支付单信息");
        }
        String orderCode = freightFeeDetail.getOrderCode();
        CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(orderCode);
        if (collectOrderEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到出库信息");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("CollectOrder", collectOrderEntity);
        CollectReceiverDetailEntity collectReceiver = collectReceiverDetailImpl.getInfoByOrderCode(orderCode);
        map.put("CollectReceiverDetail", collectReceiver);
        List<CollectOrderDetailResponse> list = collectOrderDetailImpl.getListByOrderCode(orderCode);
        map.put("CollectOrderDetail", list);
        List<CollectMailDetailEntity> list1 = collectMailDetailImpl.getListByOrderCode(orderCode);
        map.put("CollectMailDetail", list1);
        OutboundNoticeEntity noticeEntity = outboundNoticeImpl.getByOrderCode(orderCode);
        map.put("OutboundNotice", noticeEntity);
        List<LogOrderMailDetailIoEntity> list2 = logOrderMailDetailIoImpl.getOutByOrderCode(orderCode);
        map.put("LogOrderMailDetailIo", list2);
        UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(orderCode);
        map.put("UnpackNotice", unpackNoticeEntity);
        List<UnpackMailDetailEntity> list3 = unpackMailDetailImpl.getListByCode(orderCode);
        map.put("UnpackMailDetail", list3);
        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /* 临时入库 */
    @PostMapping("/tempOn")
    public JSONObject tempOn(HttpServletRequest request, @RequestBody TempOnRequest tempOnRequest) {

        TempStorageEntity tempStorageEntity = tempStorageImpl.getByMailNo(tempOnRequest.getMailNo());
        if (tempStorageEntity == null) {
            tempStorageEntity = new TempStorageEntity();
            tempStorageEntity.setMailNo(tempOnRequest.getMailNo());
            tempStorageEntity.setPlace(tempOnRequest.getPlace());
            tempStorageImpl.save(tempStorageEntity);
        } else {
            tempStorageEntity.setPlace(tempOnRequest.getPlace());
            tempStorageImpl.updateById(tempStorageEntity);
        }

        return JsonResponse.generateLocalCommonSuccessResponse(tempStorageEntity, "上架成功");
    }

    /* 临时入库 */
    @PostMapping("/tempOff")
    public JSONObject tempOff(HttpServletRequest request, @RequestBody TempOnRequest tempOnRequest) {
        TempStorageEntity tempStorageEntity = tempStorageImpl.getByMailNo(tempOnRequest.getMailNo());
        if (tempStorageEntity != null) {
            tempStorageImpl.removeById(tempStorageEntity.getUid());
        }
        return JsonResponse.generateLocalCommonSuccessResponse(tempStorageEntity, "下架成功");
    }

    /* 临时入库 */
    @PostMapping("/getTemp")
    public JSONObject getTemp(HttpServletRequest request, @RequestBody TempOnRequest tempOnRequest) {
        List<TempStorageEntity> list = tempStorageImpl.getListByMailNo(tempOnRequest.getMailNo());
        return JsonResponse.generateLocalCommonSuccessResponse(list, "");
    }

    /* 修改出库单收货人邮编 */
    @PostMapping("/editReceiverPostCode")
    public JSONObject editReceiverPostCode(HttpServletRequest request, @RequestBody EditPostCodeRequest editPostCodeRequest) {
        CollectReceiverDetailEntity receiverDetailEntity = collectReceiverDetailImpl.getInfoByOrderCode(editPostCodeRequest.getOrderCode());
        if (receiverDetailEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "收件信息不存在，无法编辑邮编");
        }
        receiverDetailEntity.setPostCode(editPostCodeRequest.getPostCode());
        if (!collectReceiverDetailImpl.updateById(receiverDetailEntity)) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "修改失败");
        }
        return JsonResponse.generateLocalCommonSuccessResponse(receiverDetailEntity, "修改成功");
    }


    /* 出库包裹查询 */
    @PostMapping("/MailDetailIoSelect")
    public JSONObject MailDetailIoSelect(HttpServletRequest request, @RequestBody MailNoRequest mailDetailIoSelectRequest) {

        String action = "FINISHOUTBOUND";


        MailDetailIoSelectResponse mailDetailIoSelectResponse = logOrderMailDetailIoImpl.findInfoByMailNoAction(mailDetailIoSelectRequest.getMailNo(), action);
        if (mailDetailIoSelectResponse == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "集运单信息不存在");
        }
        List<PackageDetailEntity> packageDetailList = packageDetailImpl.getByOrderCode(mailDetailIoSelectResponse.getLogisticsOrderCode());
        CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(mailDetailIoSelectResponse.getLogisticsOrderCode());
        List<CollectMailDetailEntity> collectMailDetailEntityList = collectMailDetailImpl.getListByOrderCode(mailDetailIoSelectResponse.getLogisticsOrderCode());
        LogOrderMailDetailEntity logOrderMailDetailEntity = logOrderMailDetailImpl.getAllInfoByMailNo(collectMailDetailEntityList.get(0).getMailNo());
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(logOrderMailDetailEntity.getLogisticsOrderCode());
        List<LogOrderMailDetailEntity> logOrderMailDetailEntityList = logOrderMailDetailImpl.getListByCode(logOrderMailDetailEntity.getLogisticsOrderCode());

        Map<String, Object> map = new HashMap<>();
        map.put("mailDetail", mailDetailIoSelectResponse);
        map.put("collectMailDetail", collectMailDetailEntityList);
        map.put("packageDetail", packageDetailList);
        map.put("collectOrder", collectOrderEntity);
        map.put("logOrder", logOrderEntity);
        map.put("logOrderMailDetail", logOrderMailDetailEntityList);
        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }


    /* 拆包查询 */
    @PostMapping("/unpackNoticeSelect")
    public JSONObject unpackNoticeSelect(HttpServletRequest request, @RequestBody UnpackNoticeSelectRequest unpackNoticeSelectRequest) {

        UnpackNoticeEntity unpackNoticeSelectResponse = unpackNoticeImpl.getByCode(unpackNoticeSelectRequest.getOrderCode());
        if (unpackNoticeSelectResponse == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "集运单信息不存在");
        }
        List<UnpackMailDetailEntity> unpackMailDetailEntityList = unpackMailDetailImpl.getListByCode(unpackNoticeSelectRequest.getOrderCode());
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(unpackNoticeSelectRequest.getOrderCode());
        List<LogOrderMailDetailEntity> logOrderMailDetailEntityList = logOrderMailDetailImpl.getListByCode(unpackNoticeSelectRequest.getOrderCode());

        Map<String, Object> map = new HashMap<>();
        map.put("unpackNotice", unpackNoticeSelectResponse);
        map.put("unpackMailDetail", unpackMailDetailEntityList);
        map.put("logOrder", logOrderEntity);
        map.put("logOrderMailDetail", logOrderMailDetailEntityList);
        map.put("packageDetail", packageDetailImpl.getByOrderCode(unpackNoticeSelectRequest.getOrderCode()));
        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /* 包裹查询 */
    @PostMapping("/logOrderMailSelect")
    public JSONObject logOrderMailSelect(HttpServletRequest request, @RequestBody MailNoRequest mailNoRequest) {
        LogOrderMailDetailEntity logOrderMailDetailEntity = logOrderMailDetailImpl.getByMailNo(mailNoRequest.getMailNo());
        if (logOrderMailDetailEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "集运单信息不存在");
        }

        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(logOrderMailDetailEntity.getLogisticsOrderCode());
        Map<String, Object> map = new HashMap<>();
        map.put("logOrder", logOrderEntity);
        map.put("logOrderMailDetail", logOrderMailDetailImpl.getListByCode(logOrderEntity.getLogisticsOrderCode()));
        UnpackMailDetailEntity unpackMailDetailEntity = unpackMailDetailImpl.getByMailNo(mailNoRequest.getMailNo());
        if (unpackMailDetailEntity != null) {
            UnpackNoticeEntity unpackNoticeEntity = unpackNoticeImpl.getByCode(unpackMailDetailEntity.getOrderCode());
            map.put("unpackNotice", unpackNoticeEntity);
            map.put("unpackMailDetail", unpackMailDetailImpl.getListByCode(unpackMailDetailEntity.getOrderCode()));
            CollectOrderEntity collectOrderEntity = collectOrderImpl.getAllInfoByOrderCode(unpackNoticeEntity.getOrderCode());
            if (collectOrderEntity != null) {
                map.put("collectOrder", collectOrderEntity);
                map.put("collectMailDetail", collectMailDetailImpl.getListByOrderCode(collectOrderEntity.getOrderCode()));
            }
        }

        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /* 账号列表 */
    @PostMapping("/userList")
    public JSONObject userList(HttpServletRequest request, @RequestBody UserRequest userRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(userImpl.getListByRequest(userRequest), "");
    }

    /* 账号新增 */
    @PostMapping("/userAdd")
    public JSONObject userAdd(HttpServletRequest request, @RequestBody UserEntity userEntity) {
        UserEntity userEntityInfo = userImpl.getInfoByAccount(userEntity.getAccount());
        if (userEntityInfo != null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "账号已存在");
        }

        userImpl.save(userEntity);

        return JsonResponse.generateLocalCommonSuccessResponse(userEntity, "新增成功");
    }

    /* 账号修改 */
    @PostMapping("/userEdit")
    public JSONObject userEdit(HttpServletRequest request, @RequestBody UserEntity userEntity) {
        UserEntity userEntityInfo = userImpl.getInfoByAccount(userEntity.getAccount());
        if (userEntityInfo != null) {
            if (userEntity.getUid().equals(userEntityInfo.getUid())) {
                userImpl.updateById(userEntity);
            } else {
                return JsonResponse.generateLocalCommonFailedResponse("-1", "账号已存在");
            }

        }

        userImpl.updateById(userEntity);

        return JsonResponse.generateLocalCommonSuccessResponse(userEntity, "修改成功");
    }

    /* 账号 */
    @PostMapping("/userDel")
    public JSONObject userDel(HttpServletRequest request, @RequestBody UserEntity userEntity) {
        UserEntity userEntityInfo = userImpl.getById(userEntity.getUid());
        if (userEntityInfo.getStatus() == 1) {
            userEntityInfo.setStatus(-1);
            userImpl.updateById(userEntity);
        } else {
            userEntity.setStatus(1);
            userImpl.updateById(userEntity);
        }
        return JsonResponse.generateLocalCommonSuccessResponse(userEntity, "修改成功");
    }
}
