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.JsonResponse;
import org.ta.pddserver.utils.PddHttpTool;
import org.ta.pddserver.utils.PddSignTool;
import org.ta.pddserver.utils.TimeTool;

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

    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(), mailNoRequest.getStatus());
        return JsonResponse.generateLocalCommonSuccessResponse(mailNoResponse);
    }

       /*运单号获取所有出库单信息*/
    @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 void receive(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(receiveRequest.getMailNo(), receiveRequest.getStatus());


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

        if (action == "warehouse_sign") {
            notifyRequest.setBizActionDesc("仓库签收");
            notifyResult.setCode(0);
        } else if (action == "warehouse_reject_sign") {
            notifyRequest.setBizActionDesc("仓库拒签");
            notifyResult.setCode(22);
            notifyResult.setDesc("运输品类限制");
            notifyResult.setRemark("运输品类限制");
            notifyRequest.setResult(notifyResult);
        } else if (action == "destroy") {
            notifyRequest.setBizActionDesc("包裹销毁");
            notifyResult.setCode(0);
        }

        notifyRequest.setResult(notifyResult);

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

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

    /*入库*/
    @PostMapping("/inBound")
    public void inBound(HttpServletRequest request, @RequestBody InBoundRequest inBoundRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(inBoundRequest.getMailNo(), inBoundRequest.getStatus());


        PddServiceConsoInboundRequest notifyRequest = new PddServiceConsoInboundRequest();

        Long status = 0L;
        Long unStatus = 0L;

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

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

        notifyRequest.setStatus("FULL_INBOUND");
        notifyRequest.setPackageQuantity(num + 1); // 已入库数量 + 1

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

        //更新入库包裹状态
//
//        ioEntity.setReq(JSON.toJSONString(requestModel));
//        ioEntity.setResp(resp);
//        logOrderMailDetailIo.save(ioEntity);

        //判断是否全部入库
        if(unNum - 1 == 0){
            //全部入库
            logOrderImpl.updateStatusByOrderCode(mailNoResponse.getLogisticsOrderCode(), 0);
        }
    }

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

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

        PddServiceConsoCoBizActionNotifyRequest.Result notifyResult = new PddServiceConsoCoBizActionNotifyRequest.Result();
        if (action == "begin_pick") {
//            ioEntity.setStatus(30);

            notifyRequest.setBizActionDesc("开始拣货");
            notifyResult.setCode(0);
        } else if (action == "finish_pick") {
//            ioEntity.setStatus(40);

            notifyRequest.setBizActionDesc("拣货完成");
            notifyResult.setCode(0);
        } else if (action == "finish_unpack") {
//            ioEntity.setStatus(50);

            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(), action);

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

    /*拣货完成后出库*/
    @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());
        for(CollectOutMailDetailResponse lists: list){
            for(OutBoundRequest.OutBoundList outBoundLists: outBoundList ){
                if(lists.getMailNo().equals(outBoundLists.getMailNo())){
                    list.remove(outBoundList);
                    outBoundRequest.getOutBound().remove(outBoundList);
                }
            }
        }

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


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

}
