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.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.ReceiveRequest;
import org.ta.pddserver.model.api.request.StorageRequest;
import org.ta.pddserver.model.enums.StatusEnum;
import org.ta.pddserver.model.pddjy.request.JYBaseRequestModel;
import org.ta.pddserver.model.pddjy.request.PddServiceConsoFirstBizActionNotifyRequest;
import org.ta.pddserver.service.impl.*;
import org.ta.pddserver.utils.*;

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

@RequestMapping("/pda")
@Slf4j
@RestController
public class PDAController {

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

    /**
     * PDA 签收
     * @param request httpRequest
     * @param receiveRequest 签收请求参数
     * @return 回复信息
     */
    @PostMapping("/sign")
    public JSONObject sign(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        LogOrderMailDetailEntity mailNoResponse = logOrderMailDetailImpl.getAllInfoByMailNo(receiveRequest.getMailNo());
        if (mailNoResponse == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "1包裹无记录");
        }
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(mailNoResponse.getLogisticsOrderCode());
        if (logOrderEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "2集运单无记录");
        }
        if (logOrderEntity.getRemarks() != null || !logOrderEntity.getRemarks().isEmpty()) {
            // 需要拒收
            return JsonResponse.generateOpenCommonFailedResponse(-1, "3集运单需要特殊处理");
        }
        String str = "";
        String action = "warehouse_sign";

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

        notifyRequest.setBizActionDesc("仓库签收");
        notifyResult.setCode(0);
        logOrderMailDetailIoEntity.setStatus(StatusEnum.SIGNED.getCode());

        str = "签收成功";
        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);
        JSONObject jsonObject = JSON.parseObject(resp);
        JSONObject respObject = (JSONObject) jsonObject.get("response");
        if (!respObject.getBoolean("success")) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "拼多多上送信息失败：" + respObject.getString("message") + "；请联系技术人员。");
        }

        //更新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);
        logOrderImpl.updateReceiveNum(1, mailNoResponse.getLogisticsOrderCode());
        return JsonResponse.generateLocalCommonSuccessResponse(true, str);
    }

    /**
     * 分配仓储位置
     * @param request httpRequest
     * @param storageRequest 分配库位请求参数
     * @return 回复消息
     */
    @PostMapping("/getPosition")
    public JSONObject getPosition(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        StorageEntity storageEntity = storageImpl.getInfoByMailNo(storageRequest.getMailNo());
        if (storageEntity != null) {
            shelvesImpl.updateNum(storageEntity.getCode().substring(0, 1), Integer.parseInt(storageEntity.getCode().substring(1, 2)), Integer.parseInt(storageEntity.getCode().substring(3, 4)));
            return JsonResponse.generateLocalCommonSuccessResponse(storageEntity, "查询成功0");
        }
        //当前包裹未上架，开始分配上架
        LogOrderMailDetailEntity mailNoResponse = logOrderMailDetailImpl.getAllInfoByMailNo(storageRequest.getMailNo());
        if (mailNoResponse == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "1包裹无记录");
        }
        StorageEntity storageEntity2 = new StorageEntity();
        // 根据集运单分配位置
        storageEntity = storageImpl.getInfoByLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        if (storageEntity != null) {
            storageEntity2.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
            storageEntity2.setCode(storageEntity.getCode());
            storageEntity2.setMailNo(mailNoResponse.getMailNo());
            storageEntity2.setNum(0);
            storageEntity2.setBuyerCode(storageEntity.getBuyerCode());
            storageImpl.save(storageEntity2);
            shelvesImpl.updateNum(storageEntity.getCode().substring(0, 1), Integer.parseInt(storageEntity.getCode().substring(1, 2)), Integer.parseInt(storageEntity.getCode().substring(3, 4)));
            return JsonResponse.generateLocalCommonSuccessResponse(storageEntity2, "查询成功1");
        }
        // 集运单未分配位置
        LogOrderEntity logOrderEntity = logOrderImpl.getByOrderCode(mailNoResponse.getLogisticsOrderCode());
        if (logOrderEntity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "2入库集运单无记录");
        }
        // 取该会员已经存在的其他的未知
        storageEntity = storageImpl.getByBuyerCode(logOrderEntity.getBuyerCode());
        if (storageEntity != null) {
            storageEntity2.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
            storageEntity2.setCode(storageEntity.getCode());
            storageEntity2.setMailNo(mailNoResponse.getMailNo());
            storageEntity2.setNum(0);
            storageEntity2.setBuyerCode(storageEntity.getBuyerCode());
            storageImpl.save(storageEntity2);
            shelvesImpl.updateNum(storageEntity.getCode().substring(0, 1), Integer.parseInt(storageEntity.getCode().substring(1, 2)), Integer.parseInt(storageEntity.getCode().substring(3, 4)));
            return JsonResponse.generateLocalCommonSuccessResponse(storageEntity2, "查询成功2");
        }
        ShelvesEntity shelvesEntity = shelvesImpl.getUsableOrdered();
        storageEntity2.setLogisticsOrderCode(mailNoResponse.getLogisticsOrderCode());
        storageEntity2.setCode(shelvesEntity.getLevel1() + shelvesEntity.getLevel2() + "-" +shelvesEntity.getLevel3());
        storageEntity2.setMailNo(mailNoResponse.getMailNo());
        storageEntity2.setNum(0);
        storageEntity2.setBuyerCode(logOrderEntity.getBuyerCode());
        storageImpl.save(storageEntity2);
        shelvesImpl.updateNum(shelvesEntity.getLevel1(), shelvesEntity.getLevel2(), shelvesEntity.getLevel3());
        return JsonResponse.generateLocalCommonSuccessResponse(storageEntity2, "查询成功3");
    }


    /**
     * PDA 上架
     * @param request httpRequest
     * @param storageRequest 上架请求参数
     * @return 回复消息
     */
    @PostMapping("/onBoard")
    public JSONObject onBoard(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        StorageEntity storageEntity = storageImpl.getInfoByMailNo(storageRequest.getMailNo());
        if (storageEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未查询到商品区域信息");
        }
        if (!storageRequest.getPlace().startsWith(storageEntity.getCode())) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "位置信息不匹配");
        }
        storageEntity.setPlace(storageRequest.getPlace());
        storageImpl.updateById(storageEntity);
        return JsonResponse.generateLocalCommonSuccessResponse(true, "上架成功");
    }

}
