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.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pddserver.entity.*;
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.OrderRejectCode;
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.StorageService;
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 = "仓库系统对接本接口")
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;
    @Autowired
    private LogOrderItemImpl logOrderItemImpl;
    @Autowired
    private CollectOrderDetailImpl collectOrderDetailImpl;
    @Autowired
    private AreaImpl areaImpl;
    @Autowired
    private StorageImpl storageImpl;
    @Autowired
    private OutboundNoticeImpl outboundNoticeImpl;

    /*集运单列表*/
    @Operation(
            summary = "分页查询收到的集运单列表",
            description = "",
            deprecated = false      // 是否废弃
    )
    @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));
    }

    /*出库详情*/
    @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("/logOrderPackageList")
//    public JSONObject logOrderPackageList(HttpServletRequest request, @RequestBody LogOrderPackageListRequest logOrderPackageListRequest) {
//        return JsonResponse.generateLocalCommonSuccessResponse(logOrderPackageImpl.getList(logOrderPackageListRequest));
//    }


//    /*出库扫码*/
//    @PostMapping("/collectOrderScan")
//    public Map<String, Object> collectOrderScan(HttpServletRequest request, @RequestBody CollectOrderScanRequest collectOrderScanRequest) {
//
//        Map<String, Object> map = new HashMap<>();
//
//        CollectOrderResponse collectOrderResponse = collectOrderImpl.getByOrderCode(collectOrderScanRequest.getOrderCode());
//        List<CollectOutMailDetailResponse> list = collectOutMailDetailImpl.getListByOrderCode(collectOrderScanRequest.getOrderCode());
//
//        map.put("collectOrder", collectOrderResponse);
//        map.put("list", list);
//
//        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("/receive")
    public JSONObject receive(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        LogOrderMailDetailEntity mailNoResponse = logOrderMailDetailImpl.getAllInfoByMailNo(receiveRequest.getMailNo());

        boolean key = false;

        String action = receiveRequest.getAction();

        PddServiceConsoFirstBizActionNotifyRequest notifyRequest = new PddServiceConsoFirstBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        notifyRequest.setBizAction(action);
        PddServiceConsoFirstBizActionNotifyRequest.Result notifyResult = new PddServiceConsoFirstBizActionNotifyRequest.Result();
        notifyRequest.setMailNo(mailNoResponse.getMailNo());
        notifyRequest.setExpressCode(mailNoResponse.getExpressCode());

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();

        if (action.equals("warehouse_sign")) {
            notifyRequest.setBizActionDesc("仓库签收");
            notifyResult.setCode(0);
            logOrderMailDetailIoEntity.setStatus(StatusEnum.SIGNED.getCode());

            //根据logisticsOrderCode 判断是否已存放

             StorageEntity storageEntity = storageImpl.getInfoByLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());

             if(storageEntity == null){
                 //计算存储位置
                 List<AreaEntity> list = areaImpl.getList();
                 for(AreaEntity lists : list){
                     // 根据code 计算占用
                     //获取所有入库数量
                     int num = storageImpl.findAllCount(lists.getCode());
                     //获取所有应入库但未入库数量
                     Integer reNum = storageImpl.findReNumCount(lists.getCode());
                     reNum = (reNum == null) ? 0 : reNum;
                     // 区域总可用数量
                     int blank = lists.getTotal() - lists.getReserved();
                     // 实际可使用数量
                     int actual = blank - reNum - num;
                     //需要数量
                     int need = logOrderMailDetailImpl.findCountByLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());

                     if(actual >= need){
                         //区域可用
                         storageEntity = new StorageEntity();
                         storageEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
                         storageEntity.setCode(lists.getCode());
                         storageEntity.setMailNo(receiveRequest.getMailNo());
                         storageEntity.setNum(1);
                         storageEntity.setTotal(need);
                         storageImpl.save(storageEntity);

                         key = true;

                         break;
                     }
                 }

                 if(!key){
                     //没有匹配到合适区域
                     return JsonResponse.generateLocalCommonFailedResponse("-1", "暂无可用区域");
                 }

             }else {

                 StorageEntity storage = storageImpl.getInfoByMailNo(receiveRequest.getMailNo());
                 if(storage == null){
                     StorageEntity storageNew = new StorageEntity();
                     storageNew.setLogisticsOrderCode(storageEntity.getLogisticsOrderCode());
                     storageNew.setCode(storageEntity.getCode());
                     storageNew.setMailNo(receiveRequest.getMailNo());
                     storageNew.setNum(storageEntity.getNum());
                     storageNew.setTotal(storageEntity.getTotal());
                     storageImpl.save(storageNew);


                     //获取已签收

                     //已签收 + 1
                     storageImpl.updateNumByLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());

                 }else {
                     return JsonResponse.generateLocalCommonFailedResponse("-1", "请勿重复签收");
                 }

             }



        } else if (action.equals("warehouse_reject_sign")) {
            notifyRequest.setBizActionDesc("仓库拒签");
            notifyResult.setCode(receiveRequest.getCode());
            notifyResult.setDesc(OrderRejectCode.getByCode(receiveRequest.getCode()).getDesc());
            notifyResult.setRemark(OrderRejectCode.getByCode(receiveRequest.getCode()).getRemark());

            if (receiveRequest.getLength() != null && receiveRequest.getLength() > 0) {

                notifyRequest.setPackageInfo(new PddServiceConsoFirstBizActionNotifyRequest.PackageInfo());
                notifyRequest.getPackageInfo().setWeight((long) PddJYPriceTool.calculateWeight((int) receiveRequest.getLength().longValue(), (int) receiveRequest.getWidth().longValue(), (int) receiveRequest.getHeight().longValue(), (int) receiveRequest.getWeight().longValue(), true));
                notifyRequest.getPackageInfo().setActualWeight(receiveRequest.getWeight());
                notifyRequest.getPackageInfo().setLength(receiveRequest.getLength());
                notifyRequest.getPackageInfo().setWidth(receiveRequest.getWidth());
                notifyRequest.getPackageInfo().setHeight(receiveRequest.getHeight());
            }

            notifyRequest.setResult(notifyResult);
            logOrderMailDetailIoEntity.setStatus(StatusEnum.REJECTED.getCode());
        } else if (action.equals("destroy")) {
            notifyRequest.setBizActionDesc("包裹销毁");
            notifyResult.setCode(0);
            logOrderMailDetailIoEntity.setStatus(StatusEnum.DESTROY.getCode());
        }

        notifyRequest.setResult(notifyResult);

        JYBaseRequestModel requestModel = new JYBaseRequestModel();
        requestModel.setRequest(JSON.toJSONString(notifyRequest));
        requestModel.setRequest_id("" + new Date().getTime());
        requestModel.setType("pdd.service.conso.first.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);

        //更新log_order_mail_detail
        Boolean result = logOrderMailDetailImpl.updateByMailNo(receiveRequest.getMailNo(), logOrderMailDetailIoEntity.getStatus());

        logOrderMailDetailIoEntity.setMailNo(receiveRequest.getMailNo());

        logOrderMailDetailIoEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        logOrderMailDetailIoEntity.setExpressCode(mailNoResponse.getExpressCode());
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);

        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);
//        ioEntity.setReq(JSON.toJSONString(requestModel));
//        ioEntity.setResp(resp);
//        logOrderMailDetailIo.save(ioEntity);

        return JsonResponse.generateLocalCommonSuccessResponse(true);
    }

    /*入库*/
    @Operation(
            summary = "入库",
            description = "",
            deprecated = false      // 是否废弃
    )
    @PostMapping("/inBound")
    public JSONObject inBound(HttpServletRequest request, @RequestBody InBoundRequest inBoundRequest) {
        LogOrderMailDetailEntity mailNoResponse = logOrderMailDetailImpl.getByMailNo(inBoundRequest.getMailNo());
        PddServiceConsoInboundRequest notifyRequest = new PddServiceConsoInboundRequest();
        // 查询orderNO 下所有mailNo,判断是全部还是部分
        Long unNum = logOrderMailDetailImpl.getSumByCodeStatus(mailNoResponse.getLogisticsOrderCode(), (long) StatusEnum.SIGNED.getCode());
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(mailNoResponse.getLogisticsOrderCode());
        Long num = (long) logOrderEntity.getNum();
        log.info("已入库数量 {} ； 未入库数量 {}", num, unNum);

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

        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");


        if (notifyRequest.getPackageQuantity() == num) {
            notifyRequest.setStatus("FULL_INBOUND");
        } else {
            notifyRequest.setStatus("PART_INBOUND");
        }

        notifyRequest.setPackageInfo(new PddServiceConsoInboundRequest.PackageInfo());
        notifyRequest.getPackageInfo().setMailNo(mailNoResponse.getMailNo());
        notifyRequest.getPackageInfo().setExpressCode(mailNoResponse.getExpressCode());
        notifyRequest.getPackageInfo().setLength(inBoundRequest.getLength());
        notifyRequest.getPackageInfo().setActualWeight(inBoundRequest.getWidth());
        notifyRequest.getPackageInfo().setHeight(inBoundRequest.getHeight());
        notifyRequest.getPackageInfo().setWidth(inBoundRequest.getWidth());
        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(0);

        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.sendJsonPost(requestModel);

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
        logOrderMailDetailIoEntity.setMailNo(inBoundRequest.getMailNo());
        logOrderMailDetailIoEntity.setExpressCode(mailNoResponse.getExpressCode());
        logOrderMailDetailIoEntity.setStatus(StatusEnum.INBOUND.getCode());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        logOrderMailDetailIoEntity.setExpressCode(mailNoResponse.getExpressCode());
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);

        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        //更新入库包裹状态
        mailNoResponse.setStatus(logOrderMailDetailIoEntity.getStatus());
        mailNoResponse.setEnterTime(TimeTool.getNowDate());
        logOrderMailDetailImpl.updateById(mailNoResponse);

        logOrderEntity.setNum(notifyRequest.getPackageQuantity().intValue());

        //判断是否全部入库
        if (notifyRequest.getPackageQuantity() <= num) {
            //全部入库
            logOrderEntity.setStatus(StatusEnum.FULLINBOUND.getCode());
        } else {
            logOrderEntity.setStatus(StatusEnum.PARTINBOUND.getCode());
        }

        logOrderImpl.updateById(logOrderEntity);

        return JsonResponse.generateLocalCommonSuccessResponse(true);
    }

    /**
     * 入库异常
     */
    @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());

        Long num = (long) logOrderEntity.getNum();

        // 查询orderNO 下所有mailNo,判断是全部还是部分
//        Long unNum = logOrderMailDetailImpl.getSumByCodeStatus(mailNoResponse.getLogisticsOrderCode(), (long) StatusEnum.SIGNED.getCode());


        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        notifyRequest.setExecuteTime(TimeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        if (num >= logOrderEntity.getPackageQuantity().intValue()) {
            //全部入库
            notifyRequest.setStatus("FULL_INBOUND");
            logOrderEntity.setStatus(StatusEnum.FULLINBOUND.getCode());

        } else {
            //部分入库
            notifyRequest.setStatus("PART_INBOUND");
            logOrderEntity.setStatus(StatusEnum.PARTINBOUND.getCode());
        }

        notifyRequest.setPackageQuantity(num < logOrderEntity.getPackageQuantity() ? num + 1 : logOrderEntity.getPackageQuantity());

        notifyRequest.setPackageInfo(new PddServiceConsoInboundRequest.PackageInfo());
        notifyRequest.getPackageInfo().setMailNo(mailNoResponse.getMailNo());
        notifyRequest.getPackageInfo().setExpressCode(mailNoResponse.getExpressCode());
        notifyRequest.getPackageInfo().setLength(inBoundRequest.getLength());
        notifyRequest.getPackageInfo().setWidth((long) PddJYPriceTool.calculateWeight(inBoundRequest.getLength().intValue(), inBoundRequest.getWidth().intValue(), inBoundRequest.getHeight().intValue(), inBoundRequest.getWeight().intValue(), true));
        notifyRequest.getPackageInfo().setHeight(inBoundRequest.getHeight());
        notifyRequest.getPackageInfo().setWeight(inBoundRequest.getWeight());
        notifyRequest.getPackageInfo().setActualWeight(inBoundRequest.getWidth());
        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);

        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);

        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("拣货完成");

        } 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((long) PddJYPriceTool.calculateWeight(lists.getLength().intValue(), lists.getWidth().intValue(), lists.getHeight().intValue(), lists.getWeight().intValue(), 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().intValue());
                logOrderPackageEntity.setWidth(lists.getWidth().intValue());
                logOrderPackageEntity.setHeight(lists.getHeight().intValue());
                logOrderPackageEntity.setWeight(lists.getWeight().intValue());

                logOrderPackageImpl.save(logOrderPackageEntity);


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

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

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

                }

            }
        }
        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);


//        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 = new CollectOrderEntity();
        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((long) PddJYPriceTool.calculateWeight(lists.getLength().intValue(), lists.getWidth().intValue(), lists.getHeight().intValue(), lists.getWeight().intValue(), 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().intValue());
                logOrderPackageEntity.setWidth(lists.getWidth().intValue());
                logOrderPackageEntity.setHeight(lists.getHeight().intValue());
                logOrderPackageEntity.setWeight(lists.getWeight().intValue());

                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);


//        logOrderMailDetailIoEntity.setMailNo(finishUnpackRequest.getMailNo());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(finishUnpackRequest.getOrderCode());
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);

        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);
            }

            if (collectOrderEntity != null) {
                collectOrderEntity.setStatus(logOrderMailDetailIoEntity.getStatus());
                collectOrderImpl.updateById(collectOrderEntity);
            }

        }

        return JsonResponse.generateLocalCommonSuccessResponse(true);
    }


    /*通知拆包后拣货*/
//    @PostMapping("/finishUnpackPackage")
//    public JSONObject finishUnpackPackage(HttpServletRequest request, @RequestBody FinishUnpackRequest finishUnpackRequest) {
//        LogOrderPackageEntity logOrderPackageEntity = logOrderPackageImpl.getInfoByCode(finishUnpackRequest.getLogisticsOrderCode());
//
//        String action = finishUnpackRequest.getAction();
//
//        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
//
//        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
//        if (action.equals("begin_pick")) {
//            logOrderMailDetailIoEntity.setStatus(StatusEnum.UNPACKBEGINPICK.getCode());
//
//        } else if (action.equals("finish_pick")) {
//            logOrderMailDetailIoEntity.setStatus(StatusEnum.UNPACKFINISHPICK.getCode());
//
//        } else if (action.equals("finish_unpack")) {
//            logOrderMailDetailIoEntity.setStatus(StatusEnum.FINISHUNPACK.getCode());
//
//            PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
//            notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
//            notifyRequest.setOrderCode(logOrderPackageEntity.getLogisticsOrderCode());
//            notifyRequest.setBizAction(action);
//            notifyRequest.setExecuteTime(TimeTool.getNowString());
//            notifyRequest.setTimeZone("UTC+8");
//
//            notifyRequest.setBizActionDesc("拆包完成");
//            notifyRequest.setUnpackRemark("");
//            notifyResult.setCode(0);
//            notifyRequest.setPackageInfos(new ArrayList<>());
//            PddServiceConsoCoBizActionNotifyRequest.PackageInfo packageInfo = new PddServiceConsoCoBizActionNotifyRequest.PackageInfo();
//            notifyRequest.getPackageInfos().add(packageInfo);
//            packageInfo.setWeight((long) logOrderPackageEntity.getWeight());
//            packageInfo.setWidth((long) logOrderPackageEntity.getWidth());
//            packageInfo.setHeight((long) logOrderPackageEntity.getHeight());
//            packageInfo.setLength((long) logOrderPackageEntity.getLength());
//            packageInfo.setActualWeight((long) logOrderPackageEntity.getWeight());
//            packageInfo.setConsoType("SEA");
//            packageInfo.setGoodsType(logOrderPackageEntity.getPackageType());
//
//            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);
//
//            logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
//            logOrderMailDetailIoEntity.setResp(resp);
//
//        }
//
//        logOrderMailDetailIoEntity.setMailNo(logOrderPackageEntity.getMailNo());
//        logOrderMailDetailIoEntity.setExpressCode(logOrderPackageEntity.getExpressCode());
//        logOrderMailDetailIoEntity.setLogisticsOrderCode(logOrderPackageEntity.getLogisticsOrderCode());
//        logOrderMailDetailIoEntity.setExpressCode(logOrderPackageEntity.getExpressCode());
//        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);
//        logOrderPackageEntity.setStatus(logOrderMailDetailIoEntity.getStatus().toString());
//        return JsonResponse.generateLocalCommonSuccessResponse(true);
//
//    }

    /*拣货完成后出库*/
    @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);
                // ---- 开始   修改为不认同前端输入，改为系统自动生成
//                packageInfo.setOutboundMailNo(outPackage.getMailNo());
//                packageInfo.setExpressCode(outPackage.getExpressCode());
                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, "拼多多订单出库失败");
        }
        WorldexUtil.noticePddOrderOut(notifyRequest.getOrderCode());
        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.setAction("FINISHOUTBOUND");
                logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
                logOrderMailDetailIoEntity.setResp(resp);
                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());
                }
            }
        }
        collectOrderImpl.updateOrderStatus(StatusEnum.FINISHOUTBOUND.getCode(), collectOrderResponse.getUid());


        return JsonResponse.generateLocalCommonSuccessResponse(true);
    }

    /*拣货完成后出库*/
    @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());
                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);

        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()));
                }
                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);
        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(problemOrderNotifyRequest.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 response = JSONObject.parseObject(resp).getJSONObject("response");
        if (response != null) {
            if (response.getBoolean("success")) {
                return JsonResponse.generateLocalCommonSuccessResponse(true);
            }
        }
        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) {
        return JsonResponse.generateLocalCommonSuccessResponse(storageImpl.storageSelect(storageRequest.getMailNo()));
    }

    /*确认上架*/
    @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("/storageList")
    public JSONObject storageList(HttpServletRequest request, @RequestBody StorageListRequest storageListRequest) {
        List<StorageListResponse> list = storageImpl.storageList(storageListRequest.getLogisticsOrderCode());
        return JsonResponse.generateLocalCommonSuccessResponse(list);
    }

    /*待出库列表*/
    @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.storageList(storageDelRequest.getLogisticsOrderCode());

        List<String> toMailList = new ArrayList<>();
        List<StorageListResponse> toRemoveList = new ArrayList<>();

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

        String ids = "(";

        for (StorageListResponse lists : list) {
            for (String mailNoLists : storageDelRequest.getMailNo()) {
                if (lists.getMailNo().equals(mailNoLists)) {
                    toRemoveList.add(lists);
                    toMailList.add(mailNoLists);
                    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);

        //根据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);
    }
}
