package com.pj.feign;

import cn.hutool.log.StaticLog;
import com.alibaba.fastjson.JSON;
import com.pj.api.dto.OrderDto;
import com.pj.api.dto.OrdersDto;
import com.pj.common.core.exception.ServiceException;
import com.pj.dto.DataDto;
import com.pj.rabbitmq.RabbitMQ;
import com.pj.utils.IdWorker;
import com.pj.utils.MD5;
import com.pj.utils.ht.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Mechrevo
 * @Date 2023 08 29 13 08
 **/
@Service
@Slf4j
public class AmqpTemplateFeign {

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 发送对象至航通
     * @param t
     * @param dataType
     */
    public <T> void sendObject(T t, String dataType) {
        StaticLog.info("send data to ht:{},{}", dataType,JSON.toJSONString(t));
        //todo: 数据暂时定死
        DataDto dataDto = new DataDto();
        //msgId
        //使用雪花算法生成,永远不会重复
        Long msgId = new IdWorker().nextId();
        dataDto.setMsgId(msgId + "");
        //appId
        String appId = "sjf01";
        dataDto.setAppId(appId);
        //dataType
        dataDto.setDataType(dataType);
        //data
        //加密
        String jsonString = JSON.toJSONString(t);
        String encryptCBC = AESUtil.encryptCBC(jsonString, RabbitMQ.ACC_KEY);
        dataDto.setData(encryptCBC);
        //msgTime
        String msgTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        dataDto.setMsgTime(msgTime);
        //sign
        String signString = "msgId=" + msgId + "&appId=" + appId + "&dataType=" + dataType + "&msgTime=" + msgTime + "&data=" + encryptCBC + "&" + RabbitMQ.ACC_KEY;
        String sign = MD5.getMd5(signString, 32);
        dataDto.setSign(sign);
        //mq发送信息
        amqpTemplate.convertAndSend(RabbitMQ.TEST_SEND_QUEUE, dataDto);
        StaticLog.info("send mq msg finish:{},{}", dataType,JSON.toJSONString(dataDto));
        StaticLog.info("send mq msg finish:{},{}", dataType,JSON.toJSONString(t));
    }

    /**
     * 获取航通数据时,验证其是否被篡改
     */
    public boolean verifyContent(DataDto dataDto){
        //获取其签名
        String sign = dataDto.getSign();
        String signString = "msgId=" + dataDto.getMsgId() + "&appId=" + dataDto.getAppId() + "&dataType=" + dataDto.getDataType() + "&msgTime=" + dataDto.getMsgTime() + "&data=" + dataDto.getData();
        String md5 = MD5.getMd5(signString, 32);
        if(!sign.equals(md5))
            throw new ServiceException("报文已经被修改。");
        return true;
    }


}
