package org.ta.pddserver.rabbit;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import org.ta.pddserver.config.PddAPIConfig;
import org.ta.pddserver.entity.TraceObjectEntity;
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.TraceObjectImpl;
import org.ta.pddserver.utils.PddHttpTool;
import org.ta.pddserver.utils.PddSignTool;
import org.ta.pddserver.utils.WorldexUtil;

import java.util.ArrayList;
import java.util.List;

//@Component
@Slf4j
public class RabbitSender {
    /**
     * 1、出库成功异步通知Worldex
     * 2、Worldex回传快递轨迹异步推送给拼多多
     * 3、异步生成快递面单，同步下载打印
     */

    private static final String TO_WORLDEX_OUTBOUND_NOTICE_QUEUE = "OUTBOUND_NOTICE_QUEUE";
    private static final String TO_PDD_TRACE_NOTICE_QUEUE = "TRACE_NOTICE_QUEUE";
    private static final String GENERATE_MAIL_LABEL = "GENERATE_MAIL_LABEL";

    @Resource
    AmqpAdmin amqpAdmin;

    @Resource
    RabbitTemplate rabbitTemplate;

    @Resource
    TraceObjectImpl traceObjectImpl;

    @PostConstruct
    public void init() {
        // 声明QUEUE
        amqpAdmin.declareQueue(new Queue(TO_WORLDEX_OUTBOUND_NOTICE_QUEUE));
        amqpAdmin.declareQueue(new Queue(TO_PDD_TRACE_NOTICE_QUEUE));
        amqpAdmin.declareQueue(new Queue(GENERATE_MAIL_LABEL));
    }


    /**
     * 发送出库通知
     *
     * @param orderCode 订单编号
     */
    public void mqSendOutboundNotice(String orderCode) {
        rabbitTemplate.convertAndSend(TO_WORLDEX_OUTBOUND_NOTICE_QUEUE, orderCode);
    }

    /**
     * 发送轨迹通知
     *
     * @param traceUid 轨迹UID
     */
    public void mqSendTraceUpdate(String traceUid) {
        rabbitTemplate.convertAndSend(TO_PDD_TRACE_NOTICE_QUEUE, traceUid);
    }

    /**
     * 创建快递面单
     *
     * @param mailNo 快递单号
     */
    public void mqGenerateMailLabel(String mailNo) {
        rabbitTemplate.convertAndSend(GENERATE_MAIL_LABEL, mailNo);
    }

    /**
     * 出库通知queue
     * @param message 消息信息
     */
    @RabbitListener(queues = TO_WORLDEX_OUTBOUND_NOTICE_QUEUE)
    public void handleToWorldexOutboundNotice(Message message) {
        String orderCode = new String(message.getBody());
        log.info("向Worldex下发单号 {} 出库", orderCode);
        for (int i = 0; i < 5; i ++) {
            if (WorldexUtil.noticePddOrderOut(orderCode)){
                return;
            }
        }
        log.error("RABBITMQ 通知Worldex失败");
    }

    /**
     * 轨迹推送
     * @param message 消息信息
     */
    @RabbitListener(queues = TO_PDD_TRACE_NOTICE_QUEUE)
    public void handleToPddTraceNotice(Message message) {
        String traceUid = new String(message.getBody());
        log.info("向拼多多发送轨迹更新信息 {}", traceUid);
        for (int i = 0; i < 5; i ++) {
            if (this.sendTraceUpdate(traceUid)){
                return;
            }
        }
        log.error("RABBITMQ 轨迹发送失败");
    }

    public boolean sendTraceUpdate(String traceUid) {
        TraceObjectEntity traceObjectEntity = traceObjectImpl.getById(traceUid);
        //推送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 dataObjects = new PddLogisticsCoTrackNotifyRequest.DataObject();
        dataObjects.setTraces(new ArrayList<>());
        dataObjects.getTraces().add(TraceObject.createFromTraceEntity(traceObjectEntity));
        requests.setDataObject(dataObjects);
        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 true;
    }

    /**
     * 制作面单
     * @param message 消息信息
     */
    @RabbitListener(queues = GENERATE_MAIL_LABEL)
    public void handleGenerateMailLabel(Message message) {
        String mailNo = new String(message.getBody());
        log.info("制作面单 {}", mailNo);
        for (int i = 0; i < 5; i ++) {
            if (this.generateMailLabel(mailNo)){
                return;
            }
        }
        log.error("RABBITMQ 制作快递面单失败");
    }

    public boolean generateMailLabel(String mailNo) {
        return true;
    }


}
