package org.ta.pddserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
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.entity.*;
import org.ta.pddserver.model.api.request.*;
import org.ta.pddserver.model.api.response.*;
import org.ta.pddserver.model.pddjy.request.*;
import org.ta.pddserver.service.impl.*;
import org.ta.pddserver.utils.*;

import java.util.*;

@Slf4j
@RestController
public class PddLocalController {


    @Resource
    LogOrderImpl logOrderImpl;

    @Resource
    LogOrderMailDetailImpl logOrderMailDetailImpl;

    @Resource
    TimeTool timeTool;

    @Resource
    CollectOutMailDetailImpl  collectOutMailDetailImpl;

    @Resource
    CollectOrderSendImpl  collectOrderSendImpl;

    @Resource
    LogOrderMailDetailIoImpl logOrderMailDetailIoImpl;

    private static final String PROVIDER_CODE = "HAIJI_KR";
    private static final String WAREHOUSE_CODE = "HJJY001";
    private static final String CLIENT_ID = "d0217707e1194c46b57e696ac7619a06";
    private static final String CLIENT_SECRET = "a5aba84483d8387030899f01276b06a194942470";
    @Resource
    private CollectReceiverDetailImpl collectReceiverDetailImpl;
    @Resource
    private CollectMailDetailImpl collectMailDetailImpl;

    @Resource
    private CollectOrderImpl collectOrderImpl;

    /*集运单列表*/
    @PostMapping("/logOrderList")
    public JSONObject logOrderList(HttpServletRequest request, @RequestBody LogOrderListRequest logOrderListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse( logOrderImpl.getListByRequest(logOrderListRequest));
    }

    /*包裹列表*/
    @PostMapping("/logOrderMailDetailList")
    public JSONObject logOrderMailDetailList(HttpServletRequest request, @RequestBody LogOrderMailDetailListRequest logOrderMailDetailListRequest) {
        return JsonResponse.generateLocalCommonSuccessResponse(logOrderMailDetailImpl.getListByCodeNo(logOrderMailDetailListRequest));
    }

    /*运单号查询*/
    @PostMapping("/mailNoSelect")
    public JSONObject mailNoSelect(HttpServletRequest request, @RequestBody MailNoRequest mailNoRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(mailNoRequest.getMailNo());
        return JsonResponse.generateLocalCommonSuccessResponse(mailNoResponse);
    }

    /*出库列表*/
    @PostMapping("/collectMailDetailList")
    public JSONObject collectMailDetailList(HttpServletRequest request, @RequestBody CollectMailDetailListRequest collectMailDetailListRequest) {

        return JsonResponse.generateLocalCommonSuccessResponse(collectMailDetailImpl.getList(collectMailDetailListRequest));
    }


    /*出库扫码*/
    @PostMapping("/collectOrderScan")
    public Map collectOrderScan(HttpServletRequest request, @RequestBody CollectOrderScanRequest collectOrderScanRequest) {

        Map<String, Object> map = new HashMap<>();

        CollectOrderResponse collectOrderResponse = collectOrderImpl.getInfoByOrderCode(collectOrderScanRequest.getOrderCode());
        List<CollectOutMailDetailResponse> list = collectOutMailDetailImpl.getListByOrderCode(collectOrderScanRequest.getOrderCode());

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

        return JsonResponse.generateLocalCommonSuccessResponse(map);
    }

    /*待拣包裹列表接口*/
    @PostMapping("/mailNoSelectAll")
    public Map mailNoSelectAll(HttpServletRequest request, @RequestBody MailNoRequest mailNoRequest) {
        Map<String, Object> map = new HashMap<>();

        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("/receive")
    public JSONObject receive(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(receiveRequest.getMailNo());

        String action = receiveRequest.getAction();

        PddServiceConsoFirstBizActionNotifyRequest notifyRequest = new PddServiceConsoFirstBizActionNotifyRequest();
        notifyRequest.setProviderCode(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(10);
        } else if (action.equals("warehouse_reject_sign")) {
            notifyRequest.setBizActionDesc("仓库拒签");
            notifyResult.setCode(22);
            notifyResult.setDesc("运输品类限制");
            notifyResult.setRemark("运输品类限制");
            notifyRequest.setResult(notifyResult);
            logOrderMailDetailIoEntity.setStatus(11);
        } else if (action.equals("destroy")) {
            notifyRequest.setBizActionDesc("包裹销毁");
            notifyResult.setCode(0);
            logOrderMailDetailIoEntity.setStatus(12);
        }

        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(CLIENT_ID);
        requestModel.setClient_id(CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, 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);
    }

    /*入库*/
    @PostMapping("/inBound")
    public JSONObject inBound(HttpServletRequest request, @RequestBody InBoundRequest inBoundRequest) {
        LogOrderMailDetailEntity mailNoResponse = logOrderMailDetailImpl.getByMailNo(inBoundRequest.getMailNo());

        PddServiceConsoInboundRequest notifyRequest = new PddServiceConsoInboundRequest();

        Long status = 20L;
        Long unStatus = 10L;
        // 查询orderNO 下所有mailNo,判断是全部还是部分
        Long unNum = logOrderMailDetailImpl.getSumByCodeStatus(mailNoResponse.getLogisticsOrderCode(), unStatus);
        Long num = logOrderMailDetailImpl.getSumByCodeStatus(mailNoResponse.getLogisticsOrderCode(), status);

        //判断是否存在入库信息
        if(mailNoResponse.getStatus().equals(20)){
            //重复入库

            notifyRequest.setPackageQuantity(num); // 已入库数量
        }else {

            notifyRequest.setPackageQuantity(num + 1); // 已入库数量 + 1
        }


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

        notifyRequest.setStatus("FULL_INBOUND");


        notifyRequest.setPackageInfo(new PddServiceConsoInboundRequest.PackageInfo());
        notifyRequest.getPackageInfo().setMailNo(mailNoResponse.getMailNo());
        notifyRequest.getPackageInfo().setExpressCode(mailNoResponse.getExpressCode());
        notifyRequest.getPackageInfo().setLength(inBoundRequest.getLength());
        notifyRequest.getPackageInfo().setWidth(inBoundRequest.getWidth());
        notifyRequest.getPackageInfo().setHeight(inBoundRequest.getHeight());
        notifyRequest.getPackageInfo().setWeight(inBoundRequest.getWeight());
        notifyRequest.getPackageInfo().setActualWeight(inBoundRequest.getActualWeight());
        notifyRequest.getPackageInfo().setGoodsType("NORMAL");

        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(CLIENT_ID);
        requestModel.setClient_id(CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);

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

        mailNoResponse.setLength(inBoundRequest.getLength().intValue());
        mailNoResponse.setWidth(inBoundRequest.getWidth().intValue());
        mailNoResponse.setHeight(inBoundRequest.getHeight().intValue());
        mailNoResponse.setWeight(inBoundRequest.getWeight().intValue());

        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);


        //更新入库包裹状态
        logOrderMailDetailImpl.updateByMailNo(inBoundRequest.getMailNo(), 20);

        //判断是否全部入库
        if(unNum - 1 == 0 && notifyRequest.getPackageQuantity() > num){
            //全部入库
            logOrderImpl.updateStatusByOrderCode(mailNoResponse.getLogisticsOrderCode(), 20);
        }else {
            logOrderImpl.updateStatusByOrderCode(mailNoResponse.getLogisticsOrderCode(), 21);
        }

        return JsonResponse.generateLocalCommonSuccessResponse(true);
    }

    /*收到拆包通知后 完成拆包*/
    @PostMapping("/finishUnpack")
    public JSONObject finishUnpack(HttpServletRequest request, @RequestBody FinishUnpackRequest finishUnpackRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(finishUnpackRequest.getMailNo());

        String action = finishUnpackRequest.getAction();

        PddServiceConsoCoBizActionNotifyRequest notifyRequest = new PddServiceConsoCoBizActionNotifyRequest();
        notifyRequest.setProviderCode(PROVIDER_CODE);
        notifyRequest.setOrderCode(mailNoResponse.getLogisticsOrderCode());
        notifyRequest.setBizAction(action);
        notifyRequest.setExecuteTime(timeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");

        LogOrderMailDetailIoEntity  logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();

        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
        if (action.equals("begin_pick")) {
            logOrderMailDetailIoEntity.setStatus(50);

            notifyRequest.setBizActionDesc("开始拣货");
            notifyResult.setCode(0);
        } else if (action.equals("finish_pick")) {
            logOrderMailDetailIoEntity.setStatus(59);

            notifyRequest.setBizActionDesc("拣货完成");
            notifyResult.setCode(0);
        } else if (action.equals("finish_unpack")) {
            logOrderMailDetailIoEntity.setStatus(39);

            notifyRequest.setBizActionDesc("拆包完成");
            notifyRequest.setUnpackRemark("");
            notifyResult.setCode(0);
            notifyRequest.setPackageInfos(new ArrayList<>());
            PddServiceConsoCoBizActionNotifyRequest.PackageInfo packageInfo = new PddServiceConsoCoBizActionNotifyRequest.PackageInfo();
            notifyRequest.getPackageInfos().add(packageInfo);
            packageInfo.setWeight(finishUnpackRequest.getWeight());
            packageInfo.setWidth(finishUnpackRequest.getWidth());
            packageInfo.setHeight(finishUnpackRequest.getHeight());
            packageInfo.setLength(finishUnpackRequest.getLength());
            packageInfo.setActualWeight(finishUnpackRequest.getActualWeight());
            packageInfo.setConsoType("SEA");
            packageInfo.setGoodsType("NORMAL");
        }
        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(CLIENT_ID);
        requestModel.setClient_id(CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);

        //更新collect_mail_detail
        Boolean result = collectMailDetailImpl.updateByMailNo(finishUnpackRequest.getMailNo(), logOrderMailDetailIoEntity.getStatus());

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

        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        return JsonResponse.generateLocalCommonSuccessResponse(true);

    }

    /*拣货完成后出库*/
    @PostMapping("/outBound")
    public JSONObject outBound(HttpServletRequest request, @RequestBody OutBoundRequest outBoundRequest) {
        PddServiceConsoOutboundRequest notifyRequest = new PddServiceConsoOutboundRequest();

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

        //获取所有可出库订单
        List<CollectOutMailDetailResponse> list = collectOutMailDetailImpl.getListByOrderCode(outBoundRequest.getOrderCode());

        // 存储需要删除的元素
        List<CollectOutMailDetailResponse> toRemoveList = new ArrayList<>();
        List<OutBoundRequest.OutBoundList> toRemoveOutBound = new ArrayList<>();


        for(CollectOutMailDetailResponse 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(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<>());

        PddServiceConsoOutboundRequest.PackageInfo packageInfo = new PddServiceConsoOutboundRequest.PackageInfo();
        notifyRequest.getPackageInfos().add(packageInfo);
        packageInfo.setOutboundMailNo(outBoundRequest.getMailNo());
        packageInfo.setExpressCode(outBoundRequest.getExpressCode());
        packageInfo.setPackageType(outBoundRequest.getPackageType());
        packageInfo.setLength(outBoundRequest.getLength());
        packageInfo.setWidth(outBoundRequest.getWidth());
        packageInfo.setHeight(outBoundRequest.getHeight());
        packageInfo.setWeight(outBoundRequest.getWeight());


        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.getInfoByMailNo(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(CLIENT_ID);
        requestModel.setClient_id(CLIENT_ID);
        long time = new Date().getTime() / 1000;
        requestModel.setTimestamp(time);
        requestModel.setSign(PddSignTool.generateSign(requestModel, CLIENT_SECRET));
        String resp = PddHttpTool.sendJsonPost(requestModel);

        LogOrderMailDetailIoEntity  logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
        logOrderMailDetailIoEntity.setMailNo(outBoundRequest.getMailNo());
        logOrderMailDetailIoEntity.setExpressCode(outBoundRequest.getExpressCode());
        logOrderMailDetailIoEntity.setLogisticsOrderCode(outBoundRequest.getOrderCode());
        logOrderMailDetailIoEntity.setExpressCode(outBoundRequest.getExpressCode());
        logOrderMailDetailIoEntity.setStatus(60);
        logOrderMailDetailIoEntity.setReq(JSON.toJSONString(requestModel));
        logOrderMailDetailIoEntity.setResp(resp);

        logOrderMailDetailIoImpl.save(logOrderMailDetailIoEntity);

        //更新collect_mail_detail
        for(CollectOutMailDetailResponse lists: list) {
            Boolean result = collectMailDetailImpl.updateByMailNo(lists.getMailNo(), logOrderMailDetailIoEntity.getStatus());
        }
        return JsonResponse.generateLocalCommonSuccessResponse(true);
    }


    /*流水查询*/
    @PostMapping("/logOrderMailDetailIoSelect")
    public JSONObject logOrderMailDetailIoSelect(HttpServletRequest request, @RequestBody LogOrderMailDetailIoRequest param) {
        return JsonResponse.generateLocalCommonSuccessResponse(logOrderMailDetailIoImpl.getListByRequest(param));
    }

}
