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.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.entity.CollectOrderSendEntity;
import org.ta.pddserver.entity.CollectOutMailDetailEntity;
import org.ta.pddserver.entity.CollectReceiverDetailEntity;
import org.ta.pddserver.entity.LogOrderMailDetailIoEntity;
import org.ta.pddserver.model.api.request.*;
import org.ta.pddserver.model.api.response.MailNoResponse;
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.ArrayList;
import java.util.Date;

@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";
    @Autowired
    private CollectReceiverDetailImpl collectReceiverDetailImpl;
    @Autowired
    private CollectMailDetailImpl collectMailDetailImpl;

    /*集运单列表*/
    @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("/receive")
    public void receive(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        MailNoResponse mailNoResponse = logOrderMailDetailImpl.getInfoByMailNo(receiveRequest.getMailNo(), receiveRequest.getStatus());

        LogOrderMailDetailIoEntity ioEntity = new LogOrderMailDetailIoEntity();
        ioEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        ioEntity.setExpressCode(mailNoResponse.getExpressCode());
        ioEntity.setMailNo(mailNoResponse.getMailNo());
        ioEntity.setAction(receiveRequest.getAction());
        ioEntity.setStatus(10);

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

        LogOrderMailDetailIoEntity ioEntity = new LogOrderMailDetailIoEntity();
        ioEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        ioEntity.setExpressCode(mailNoResponse.getExpressCode());
        ioEntity.setMailNo(mailNoResponse.getMailNo());
        ioEntity.setStatus(20);

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

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

        LogOrderMailDetailIoEntity ioEntity = new LogOrderMailDetailIoEntity();
        ioEntity.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        ioEntity.setExpressCode(mailNoResponse.getExpressCode());
        ioEntity.setMailNo(mailNoResponse.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");

        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 void outBound(HttpServletRequest request, @RequestBody OutBoundRequest outBoundRequest) {
        PddServiceConsoOutboundRequest notifyRequest = new PddServiceConsoOutboundRequest();

        notifyRequest.setProviderCode(PROVIDER_CODE);
        notifyRequest.setOrderCode(outBoundRequest.getOrderCode());
        notifyRequest.setSegmentCode(outBoundRequest.getSegmentCode());
        notifyRequest.setExecuteTime(timeTool.getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setIsSplitOut("N");
        notifyRequest.setPackageInfos(new ArrayList<>());

        for(OutBoundRequest.OutBoundList outBoundList: outBoundRequest.getOutBound()){
            CollectOutMailDetailEntity collectOutMailDetailEntity = collectOutMailDetailImpl.getInfoByMailNo(outBoundList.getMailNo());

            PddServiceConsoOutboundRequest.PackageInfo packageInfo = new PddServiceConsoOutboundRequest.PackageInfo();
            notifyRequest.getPackageInfos().add(packageInfo);
            packageInfo.setOutboundMailNo(outBoundList.getMailNo());
            packageInfo.setExpressCode(outBoundList.getExpressCode());
            packageInfo.setPackageType(outBoundList.getPackageType());
            packageInfo.setLength(collectOutMailDetailEntity.getLength());
            packageInfo.setWidth(collectOutMailDetailEntity.getWidth());
            packageInfo.setHeight(collectOutMailDetailEntity.getHeight());
            packageInfo.setWeight(collectOutMailDetailEntity.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);
    }


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

}
