package cn.gov.customs.wxjy.ibmmq.utils;

import cn.gov.customs.cacp.sdks.hgid.HgidGenerator;
import cn.gov.customs.wxjy.common.utils.DateUtils;
import cn.gov.customs.wxjy.common.utils.StringUtils;
import cn.gov.customs.wxjy.ibmmq.config.PushContext;
import cn.gov.customs.wxjy.ibmmq.enums.PushDataStatusEnum;
import cn.gov.customs.wxjy.ibmmq.enums.PushDataTypeEnum;
import cn.gov.customs.wxjy.ibmmq.model.DataMessage;
import cn.gov.customs.wxjy.ibmmq.pojo.PushLog;
import cn.gov.customs.wxjy.ibmmq.service.IDataHandlerService;
import cn.gov.customs.wxjy.ibmmq.service.IFileHandlerService;
import cn.gov.customs.wxjy.ibmmq.service.IPushLogService;
import com.alibaba.fastjson2.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
public class IbmmqSendUtils {
    static Logger logger = LoggerFactory.getLogger(IbmmqSendUtils.class);

    // 注入ibmq模块的推送服务
    private final IFileHandlerService fileSenderService;
    private final IDataHandlerService dataHandlerService;
    @Autowired
    private IPushLogService pushLogService;
    @Autowired
    private HgidGenerator idHelper;


    @Value("${ibm.mq.file-upload-path:/home/ruoyi/uploadPath}")
    private String fileUploadPath;

    // 静态实例引用
    private static IbmmqSendUtils instance;

    // 使用构造器注入，避免循环依赖
    @Autowired
    public IbmmqSendUtils(IFileHandlerService fileSenderService,
                          IDataHandlerService dataHandlerService) {
        this.fileSenderService = fileSenderService;
        this.dataHandlerService = dataHandlerService;
        // 设置静态实例
        instance = this;
    }

    /**
     * 推送数据，并生成推送日志
     * @param message  推送数据
     * @param <T>
     */
    public static <T> void sendData(DataMessage<T> message, PushContext context) {
        Date nowDate = new Date();
        PushLog pushLog = buildPushLog(context, nowDate);
        pushLog.setPushType(PushDataTypeEnum.PUSH_DATA_INFO.getCode());
        try {
            pushLog.setPushInfo(JSON.toJSONString(message));
            pushLog.setPushTime(DateUtils.getDate());
            message.setMsgId(UUID.randomUUID().toString());
            message.setSendTime(nowDate);
            instance.dataHandlerService.sendDataMessage(message);
            pushLog.setStatus(PushDataStatusEnum.PUSH_STATUS_SUCCESS.getCode());
        } catch (Exception e) {
            logger.error("IBM MQ 推送失败", e);
            pushLog.setStatus(PushDataStatusEnum.PUSH_STATUS_ERROR.getCode());
        } finally {
            if(StringUtils.isNotEmpty(pushLog.getLogId())){
                instance.pushLogService.update(pushLog);
            }else {
                pushLog.setLogId(instance.idHelper.nextId());
                instance.pushLogService.insert(pushLog);
            }

        }
    }


    /**
     * 单个推送文件
     * @param message
     */
    public static void sendFile(String message, PushContext context) {
        Date nowDate = new Date();
        PushLog pushLog = buildPushLog(context,nowDate);
        pushLog.setPushType(PushDataTypeEnum.PUSH_DATA_FILE.getCode());
        try {
            pushLog.setPushInfo(message);
            pushLog.setPushTime(DateUtils.getDate());
            instance.fileSenderService.sendFile(message, instance.fileUploadPath);
            pushLog.setStatus(PushDataStatusEnum.PUSH_STATUS_SUCCESS.getCode());
        } catch (Exception e) {
            logger.info("推送文件到IBMQ失败: {}", e.getMessage(), e);
            pushLog.setStatus(PushDataStatusEnum.PUSH_STATUS_ERROR.getCode());
        } finally {
            if(StringUtils.isNotEmpty(pushLog.getLogId())){
                instance.pushLogService.update(pushLog);
            }else {
                pushLog.setLogId(instance.idHelper.nextId());
                instance.pushLogService.insert(pushLog);
            }
        }
    }

    /**
     * 批量推送文件
     * @param message
     * @param context
     */
    public static void sendFile(List<String> message, PushContext context) {
        Date nowDate = new Date();
        PushLog pushLog = buildPushLog(context,nowDate);
        pushLog.setPushType(PushDataTypeEnum.PUSH_DATA_FILE.getCode());
        try {
            pushLog.setPushInfo(message.toString());
            pushLog.setPushTime(DateUtils.getDate());
            instance.fileSenderService.sendFiles(message);
            pushLog.setStatus(PushDataStatusEnum.PUSH_STATUS_SUCCESS.getCode());
        } catch (Exception e) {
            logger.info("批量推送文件到IBMQ失败: {}", e.getMessage(), e);
            pushLog.setStatus(PushDataStatusEnum.PUSH_STATUS_ERROR.getCode());
        } finally {
            if(StringUtils.isNotEmpty(pushLog.getLogId())){
                instance.pushLogService.update(pushLog);
            }else {
                pushLog.setLogId(instance.idHelper.nextId());
                instance.pushLogService.insert(pushLog);
            }
        }
    }


//    日志对象
    private static PushLog buildPushLog(PushContext ctx, Date time) {
        PushLog log = new PushLog();
        log.setCreateTime(time);
        log.setUpdateTime(time);
        log.setBusType(ctx.getBusType());
        log.setBusId(ctx.getBusId());
        return log;
    }

}