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 jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pddserver.entity.*;
import org.ta.pddserver.mapper.TraceObjectMapper;
import org.ta.pddserver.model.pddjy.request.*;
import org.ta.pddserver.model.pddlg.common.TraceObject;
import org.ta.pddserver.model.pddlg.request.LGBaseModel;
import org.ta.pddserver.model.pddlg.request.PddLogisticsCoTrackNotifyRequest;
import org.ta.pddserver.model.pddlg.request.PddLogisticsCoTrackQueryRequest;
import org.ta.pddserver.model.pddlg.request.PddLogisticsCoTrackSubRequest;
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.io.BufferedReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
public class PddFZController {

    @Resource
    LogOrderMailDetailImpl logOrderMailDetailImpl;

    @Resource
    private TraceObjectImpl traceObjectImpl;

    private static String getNowString() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }


    @GetMapping("/notify/{code}")
    public void notify(@PathVariable("code") String code) {
        // code 给拼多多要发的订单code
        // 根据code 查询相应信息组装发给pdd


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

    private PddLogisticsCoTrackNotifyRequest.DataObject getDataObject(String code) {
        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) {
            dataObjects.getTraces().add(TraceObject.createFromTraceEntity(traceObjectEntity));
        }

        return dataObjects;
    }


    @GetMapping("/bizAction/{mailNo}/{action}")
    public void bizAction(@PathVariable("mailNo") String mailNo, @PathVariable("action") String action) {
        LogOrderMailDetailEntity logOrderMailDetailEntity = logOrderMailDetailImpl.getByMailNo(mailNo);
        PddServiceConsoFirstBizActionNotifyRequest notifyRequest = new PddServiceConsoFirstBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setExecuteTime(getNowString());
        notifyRequest.setTimeZone("UTC+8");
        notifyRequest.setLogisticsOrderCode(logOrderMailDetailEntity.getLogisticsOrderCode());
        notifyRequest.setBizAction(action);


        notifyRequest.setMailNo(logOrderMailDetailEntity.getMailNo());
        notifyRequest.setExpressCode(logOrderMailDetailEntity.getExpressCode());
        PddServiceConsoFirstBizActionNotifyRequest.Result notifyResult = new PddServiceConsoFirstBizActionNotifyRequest.Result();
        if (action == "warehouse_sign") {
            notifyRequest.setBizActionDesc("仓库签收");

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


        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.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));
        log.info("requestModel:{}", JSON.toJSONString(requestModel));
//        String resp = PddHttpTool.postRequest(requestModel);
        String resp = PddHttpTool.sendJsonPost(requestModel);
        log.info("resp = {}", resp);
    }


    @GetMapping("/inBound/{mailNo}/{action}")
    public void inBound(@PathVariable("mailNo") String mailNo, @PathVariable("action") String action) {
        LogOrderMailDetailEntity logOrderMailDetailEntity = logOrderMailDetailImpl.getByMailNo(mailNo);
        PddServiceConsoInboundRequest notifyRequest = new PddServiceConsoInboundRequest();


//        PddServiceConsoFirstBizActionNotifyRequest notifyRequest = new PddServiceConsoFirstBizActionNotifyRequest();
        notifyRequest.setProviderCode(PddAPIConfig.PROVIDER_CODE);
        notifyRequest.setLogisticsOrderCode(logOrderMailDetailEntity.getLogisticsOrderCode());
        notifyRequest.setExecuteTime(getNowString());
        notifyRequest.setTimeZone("UTC+8");

        notifyRequest.setStatus("PART_INBOUND");
        notifyRequest.setPackageQuantity(1L);

        notifyRequest.setPackageInfo(new PddServiceConsoInboundRequest.PackageInfo());
        notifyRequest.getPackageInfo().setMailNo(mailNo);
        notifyRequest.getPackageInfo().setExpressCode(logOrderMailDetailEntity.getExpressCode());
        notifyRequest.getPackageInfo().setLength(30L);
        notifyRequest.getPackageInfo().setWidth(30L);
        notifyRequest.getPackageInfo().setHeight(30L);
        notifyRequest.getPackageInfo().setWeight(300L);
        notifyRequest.getPackageInfo().setActualWeight(300L);
        notifyRequest.getPackageInfo().setGoodsType("NORMAL");

        notifyRequest.setResult(new PddServiceConsoInboundRequest.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.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));
        log.info("requestModel:{}", JSON.toJSONString(requestModel));
//        String resp = PddHttpTool.postRequest(requestModel);
        String resp = PddHttpTool.sendJsonPost(requestModel);
        log.info("resp = {}", resp);
    }


}
