package org.ta.pddserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jakarta.annotation.Resource;
import jakarta.annotation.security.RolesAllowed;
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.pdd.entity.*;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pddserver.model.api.request.ReceiveRequest;
import org.ta.pddserver.model.api.request.StorageDelRequest;
import org.ta.pddserver.model.api.request.StorageRequest;
import org.ta.pddserver.model.api.response.StorageListResponse;
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.*;

@RequestMapping("/pda")
@Slf4j
@RestController

public class PDAController {

    @Resource
    LogOrderMailDetailImpl logOrderMailDetailImpl;
    @Resource
    LogOrderImpl logOrderImpl;
    @Resource
    LogOrderMailDetailIoImpl logOrderMailDetailIoImpl;
    @Resource
    StorageImpl storageImpl;
    @Resource
    ShelvesImpl shelvesImpl;
    @Resource
    OutboundRecordImpl outboundRecordImpl;
    @Resource
    OutboundNoticeImpl outboundNoticeImpl;
    @Resource
    UnpackNoticeImpl unpackNoticeImpl;
    @Resource
    LogsMailScanImpl logsMailScanImpl;
    /**
     * PDA 签收
     *
     * @param request        httpRequest
     * @param receiveRequest 签收请求参数
     * @return 回复信息
     */
    @RolesAllowed({"TEMPORARY", "WORKER", "ADMIN"})
    @PostMapping("/sign")
    public JSONObject sign(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        logsMailScanImpl.makeLog(receiveRequest.getMailNo(), "SIGN");
        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 回复消息
     */
    @RolesAllowed({"TEMPORARY", "WORKER", "ADMIN"})
    @PostMapping("/getPosition")
    public JSONObject getPosition(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        StorageEntity storageEntity = storageImpl.getInfoByMailNo(storageRequest.getMailNo());
        if (storageEntity != null) {
            return JsonResponse.generateLocalCommonSuccessResponse(storageEntity, "查询成功0");
        }
        logsMailScanImpl.makeLog(storageRequest.getMailNo(), "POSITION");
        //当前包裹未上架，开始分配上架
        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);
            String[] codes = storageEntity.getCode().split("-");
            shelvesImpl.updateNum(1, codes[0].substring(0, 1), Integer.parseInt(codes[0].substring(1)), Integer.parseInt(codes[1]));
            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);
            String[] codes = storageEntity.getCode().split("-");
            shelvesImpl.updateNum(1, codes[0].substring(0, 1), Integer.parseInt(codes[0].substring(1)), Integer.parseInt(codes[1]));
            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(1, shelvesEntity.getLevel1(), shelvesEntity.getLevel2(), shelvesEntity.getLevel3());
        return JsonResponse.generateLocalCommonSuccessResponse(storageEntity2, "查询成功3");
    }

    /**
     * 分配仓储位置
     *
     * @param request        httpRequest
     * @param storageRequest 分配库位请求参数
     * @return 回复消息
     */
    @RolesAllowed({"TEMPORARY", "WORKER", "ADMIN"})
    @PostMapping("/checkPosition")
    public JSONObject checkPosition(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        StorageEntity storageEntity = storageImpl.getInfoByMailNo(storageRequest.getMailNo());
        if (storageEntity != null) {
            return JsonResponse.generateLocalCommonSuccessResponse(storageEntity, "查询成功0");
        }
        return JsonResponse.generateOpenCommonFailedResponse(-1, "未分配库位");
    }


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

    /**
     * PDA 拣货下架
     */
    @RolesAllowed({"TEMPORARY", "WORKER", "ADMIN"})
    @PostMapping("/downBoard")
    public JSONObject downBoard(HttpServletRequest request, @RequestBody StorageDelRequest storageDelRequest) {

        List<StorageListResponse> list = storageImpl.storageLists(storageDelRequest.getLogisticsOrderCode());
        List<String> toMailList = new ArrayList<>();
        List<StorageListResponse> toRemoveList = new ArrayList<>();
        Map<String, Integer> integerMap = new HashMap<>();
        if (list.size() != storageDelRequest.getMailNo().size()) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "下架包裹数量异常");
        }
        StorageListResponse first = list.get(0);
        String ids = "(";
        for (StorageListResponse lists : list) {
            for (String mailNoLists : storageDelRequest.getMailNo()) {
                if (lists.getMailNo().equals(mailNoLists)) {
                    logsMailScanImpl.makeLog(mailNoLists, "DOWNBOARD");
                    if (integerMap.containsKey(lists.getCode())) {
                        integerMap.put(lists.getCode(), integerMap.get(lists.getCode()) + 1);
                    } else {
                        integerMap.put(lists.getCode(), 1);
                    }
                    toRemoveList.add(lists);
                    toMailList.add(mailNoLists);
                    ids += "'" + mailNoLists + "',";
                }
            }
        }
        ids = ids.substring(0, ids.length() - 1);
        ids += ")";
        list.removeAll(toRemoveList);
        storageDelRequest.getMailNo().removeAll(toMailList);
        if (list.size() != 0 || storageDelRequest.getMailNo().size() != 0) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "下架包裹信息异常");
        }
        //删除位置
        storageImpl.storageDel(ids);
        // 释放货架位置
        for (String code: integerMap.keySet()) {
            String[] codes = code.split("-");
            shelvesImpl.updateNum(-1, codes[0].substring(0, 1), Integer.parseInt(codes[0].substring(1)), Integer.parseInt(codes[1]));

        }
        //根据type 区分修改状态
        if (("pick").equals(storageDelRequest.getType())) {
            // 出库拣货下架
            outboundNoticeImpl.updateStatusByOrderCode(storageDelRequest.getLogisticsOrderCode(), StatusEnum.PICKDOWN.getCode());
        } else {
            // 拆包下架
            unpackNoticeImpl.updateStatusByOrderCode(storageDelRequest.getLogisticsOrderCode(), StatusEnum.UNPACKFINISHPICK.getCode());
        }
        return JsonResponse.generateLocalCommonSuccessResponse(true, "");
    }

    /**
     * PDA 上架
     *
     * @param request        httpRequest
     * @param storageRequest 上架请求参数
     * @return 回复消息
     */
    @RolesAllowed({"TEMPORARY", "WORKER", "ADMIN"})
    @PostMapping("/downScan")
    public JSONObject downScan(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        logsMailScanImpl.makeLog(storageRequest.getMailNo(), "DOWNSCAN");
        StorageEntity storageEntity = storageImpl.getInfoByMailNo(storageRequest.getMailNo());
        if (storageEntity == null) {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "未查询到商品区域信息");
        }

        return JsonResponse.generateLocalCommonSuccessResponse(storageEntity, "验证成功");
    }

    /**
     * PDA 出库扫码
     *
     * @param request        httpRequest
     * @param receiveRequest 出库扫码请求
     * @return 回复信息
     */
    @RolesAllowed({"WORKER", "ADMIN"})
    @PostMapping("/outScan")
    public JSONObject outScan(HttpServletRequest request, @RequestBody ReceiveRequest receiveRequest) {
        LogOrderMailDetailIoEntity entity = logOrderMailDetailIoImpl.getOutboundByMailNo(receiveRequest.getMailNo());
        if (entity == null) {
            return JsonResponse.generateOpenCommonFailedResponse(-1, "未找到出库信息");
        }
        OutboundRecordEntity outboundRecordEntity = outboundRecordImpl.getByMailNo(receiveRequest.getMailNo());
        if (outboundRecordEntity == null) {
            outboundRecordEntity = new OutboundRecordEntity();
            outboundRecordEntity.setMailNo(receiveRequest.getMailNo());
            outboundRecordEntity.setOrderCode(entity.getLogisticsOrderCode());
            outboundRecordImpl.save(outboundRecordEntity);
            return JsonResponse.generateLocalCommonSuccessResponse(outboundRecordEntity, "扫码成功");
        }

        return JsonResponse.generateLocalCommonSuccessResponse(outboundRecordEntity, "重复扫码");
    }


    /**
     * PDA 扫码记录查询
     *
     * @param request        httpRequest
     * @param storageRequest 查询参数
     * @return 回复消息
     */
    @RolesAllowed({"WORKER", "ADMIN"})
    @PostMapping("/scanRecordList")
    public JSONObject scanRecordList(HttpServletRequest request, @RequestBody StorageRequest storageRequest) {
        List<LogsMailScanEntity> list = logsMailScanImpl.getByMail(storageRequest.getMailNo());
        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        return JsonResponse.generateLocalCommonSuccessResponse(map, "查询成功");
    }
}
