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.pdd.entity.LogOrderMailDetailIoEntity;
import org.ta.pdd.entity.TraceObjectEntity;
import org.ta.pddserver.model.api.request.CollectOrderListRequest;
import org.ta.pddserver.model.api.request.CollectOrderRequest;
import org.ta.pddserver.model.api.request.TraceObjectRequest;
import org.ta.pddserver.model.api.response.CollectOrderDetailResponse;
import org.ta.pddserver.model.api.response.CollectOrderInfoResponse;
import org.ta.pddserver.model.api.response.CollectReceiverDetailResponse;
import org.ta.pddserver.model.enums.StatusEnum;
import org.ta.pddserver.model.pddlg.common.TraceObject;
import org.ta.pddserver.model.pddlg.request.PddLogisticsCoTrackNotifyRequest;
import org.ta.pddserver.model.pddlg.response.PddLogisticsCoTrackNotifyResponse;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/logistics")
@Slf4j
public class DataGetController {

    @Resource
    private CollectOrderImpl collectOrderImpl;

    @Resource
    private CollectOrderDetailImpl collectOrderDetailImpl;
    @Resource
    private TraceObjectImpl traceObjectImpl;
    @Resource
    private CollectReceiverDetailImpl collectReceiverDetailImpl;
    @Resource
    private LogOrderMailDetailIoImpl logOrderMailDetailIoImpl;

    /*待拆包列表*/
    @PostMapping("/notifyTrace")
    public JSONObject notifyTrace(HttpServletRequest request, @RequestBody TraceObjectRequest traceObjectRequest) {
        TraceObjectEntity traceObject = new TraceObjectEntity();
        traceObject.setTrackingNumber(traceObjectRequest.getTrackingNumber());
        traceObject.setTrackingOrderNo(traceObjectRequest.getTrackingOrderNo());
        LogOrderMailDetailIoEntity ioEntity = logOrderMailDetailIoImpl.getOutboundByMailNo(traceObject.getTrackingNumber());
        traceObject.setTrackingNumber(ioEntity.getUpMailNo());
        traceObject.setTrackingOrderNo(ioEntity.getLogisticsOrderCode());
        traceObject.setId(traceObjectRequest.getId());
        traceObject.setStatusCode(traceObjectRequest.getStatusCode());
        traceObject.setDescription(traceObjectRequest.getDescription());
        traceObject.setOperationTime(traceObjectRequest.getOperationTime());
        traceObject.setTransferFlag(traceObjectRequest.getTransferFlag());
        traceObject.setTransferNo(traceObjectRequest.getTransferNo());
        traceObject.setTransferPartnerId(traceObjectRequest.getTransferPartnerId());
        traceObject.setTimeZone(traceObjectRequest.getTimeZone());
        traceObject.setSiteName(traceObjectRequest.getSiteName());
        traceObject.setSiteType(traceObjectRequest.getSiteType());
        traceObject.setSiteNo(traceObjectRequest.getSiteNo());
        traceObject.setNextSiteName(traceObjectRequest.getNextSiteName());
        traceObject.setNextSiteNo(traceObjectRequest.getNextSiteNo());
        traceObject.setFailReason(traceObjectRequest.getFailReason());
        traceObject.setWeight(traceObjectRequest.getWeight());
        traceObject.setCountry(traceObjectRequest.getCountry());
        traceObject.setCity(traceObjectRequest.getCity());
        traceObject.setProvince(traceObjectRequest.getProvince());
        traceObject.setDistrict(traceObjectRequest.getDistrict());
        traceObject.setContact(traceObjectRequest.getContact());
        traceObject.setContactInfo(traceObjectRequest.getContactInfo());
        traceObject.setSignerName(traceObjectRequest.getSignerName());
        traceObject.setAddress(traceObjectRequest.getAddress());
        traceObject.setRemark(traceObjectRequest.getRemark());

        traceObjectImpl.save(traceObject);

        //推送pdd
        PddLogisticsCoTrackNotifyRequest requests = new PddLogisticsCoTrackNotifyRequest();
        requests.setClient_id(PddAPIConfig.CLIENT_ID);
        requests.setShip_id(PddAPIConfig.SHIP_ID);
        requests.setTarget_client_id(PddAPIConfig.CLIENT_ID);
        requests.setTimestamp(System.currentTimeMillis() / 1000);
        PddLogisticsCoTrackNotifyRequest.DataObject dataObject = getDataObject(traceObjectRequest.getTrackingNumber(), ioEntity.getUpMailNo());
        requests.setDataObject(dataObject);
        requests.encodeData();
        requests.setSign(PddSignTool.generateSign(requests, PddAPIConfig.CLIENT_SECRET));
        log.info("requestModel:{}", JSON.toJSONString(requests));
        String resp = PddHttpTool.sendJsonPost(requests);
        log.info("resp = {}", resp);
        PddLogisticsCoTrackNotifyResponse response = JSON.parseObject(resp, PddLogisticsCoTrackNotifyResponse.class);
        log.info("response = {}", JSON.toJSONString(response));

        return JsonResponse.generateLocalCommonSuccessResponse(true, "操作成功");
    }

    /*出库详情*/
    @PostMapping("/orderInfo")
    public JSONObject collectOrderInfo(HttpServletRequest request, @RequestBody CollectOrderRequest collectOrderRequest) {
        String orderCode = collectOrderRequest.getOrderCode();
        if (orderCode.contains("-")) {
            orderCode = orderCode.split("-")[0];
        }
        Map<String, Object> map = new HashMap<>();
        CollectOrderInfoResponse collectOrderInfoResponse = collectOrderImpl.getInfoByOrderCode(orderCode);
        List<CollectOrderDetailResponse> list = collectOrderDetailImpl.getListByOrderCode(orderCode);
        CollectReceiverDetailResponse collectOrderReceiverDetailResponse = collectReceiverDetailImpl.getByOrderCode(orderCode);
        List<LogOrderMailDetailIoEntity> logistics = logOrderMailDetailIoImpl.getOutByWxOrderCode(collectOrderRequest.getOrderCode());
        map.put("info", collectOrderInfoResponse);
        map.put("detail", list);
        map.put("receiver", collectOrderReceiverDetailResponse);
        map.put("logistics", logistics);
        return JsonResponse.generateLocalCommonSuccessResponse(map, "");
    }

    /*待拣货列表*/
    @PostMapping("/outboundList")
    public JSONObject outboundList(HttpServletRequest request, @RequestBody CollectOrderListRequest collectOrderListRequest) {
        collectOrderListRequest.setStatus("" + StatusEnum.FINISHOUTBOUND.getCode());
        if (collectOrderListRequest.getSize() > 100) {
            collectOrderListRequest.setSize(100);
        }
        return JsonResponse.generateLocalCommonSuccessResponse(collectOrderImpl.getList(collectOrderListRequest), "");
    }

    private PddLogisticsCoTrackNotifyRequest.DataObject getDataObject(String code, String newCode) {
        PddLogisticsCoTrackNotifyRequest.DataObject dataObjects = new PddLogisticsCoTrackNotifyRequest.DataObject();
        dataObjects.setTraces(new ArrayList<>());

        List<TraceObjectEntity> list = traceObjectImpl.selectByTrackingNumber(code);
        List<TraceObject> traceObjects = new ArrayList<>();
        for (TraceObjectEntity traceObjectEntity : list) {
            TraceObject obj = TraceObject.createFromTraceEntity(traceObjectEntity);
            obj.setTrackingNumber(newCode);
            dataObjects.getTraces().add(obj);
        }

        return dataObjects;
    }

    public void repairCollectOrderItemMessage(String orderCode) {

    }
}
