package org.ta.pddserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
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.RequestMapping;
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.InBoundRequest;
import org.ta.pddserver.model.enums.StatusEnum;
import org.ta.pddserver.model.pddjy.request.JYBaseRequestModel;
import org.ta.pddserver.model.pddjy.request.PddServiceConsoInboundRequest;
import org.ta.pddserver.service.impl.LogOrderImpl;
import org.ta.pddserver.service.impl.LogOrderMailDetailImpl;
import org.ta.pddserver.service.impl.LogOrderMailDetailIoImpl;
import org.ta.pddserver.service.impl.StorageImpl;
import org.ta.pddserver.utils.*;

import java.util.Date;
import java.util.List;

@RequestMapping("/operation")
@Slf4j
@RestController
public class OperationController {

    @Resource
    LogOrderMailDetailImpl logOrderMailDetailImpl;
    @Resource
    LogOrderImpl logOrderImpl;
    @Resource
    LogOrderMailDetailIoImpl logOrderMailDetailIoImpl;
    @Resource
    StorageImpl storageImpl;

    /*入库*/
    @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();
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(mailNoResponse.getLogisticsOrderCode());
        int currNum = logOrderEntity.getNum();
        int num = logOrderMailDetailImpl.getInboundedCountByOrderCode(mailNoResponse.getLogisticsOrderCode());

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

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

        log.info("已入库数量 {} ； 全部数量 {}", num, logOrderEntity.getPackageQuantity());
        if (currNum >= logOrderEntity.getPackageQuantity()) {
            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);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }

        LogOrderMailDetailIoEntity logOrderMailDetailIoEntity = new LogOrderMailDetailIoEntity();
        logOrderMailDetailIoEntity.setMailNo(inBoundRequest.getMailNo());
        logOrderMailDetailIoEntity.setExpressCode(mailNoResponse.getExpressCode());
        logOrderMailDetailIoEntity.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, "");
    }


}
