package cn.gov.customs.wxjy.ibmmq.service.impl;

import cn.gov.customs.wxjy.ibmmq.enums.MessageType;
import cn.gov.customs.wxjy.ibmmq.model.DataMessage;
import cn.gov.customs.wxjy.ibmmq.service.IDataHandlerService;
import cn.gov.customs.wxjy.ibmmq.service.IFileHandlerService;
import cn.gov.customs.wxjy.ibmmq.service.ISendMsgService;
import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

@Service
@RequiredArgsConstructor
@Slf4j
public class SendMsgServiceImpl implements ISendMsgService {

    private final IFileHandlerService fileHandlerService;

    private final IDataHandlerService dataHandlerService;

    @Override
    @Async
    public <T> Boolean sendDataAndFiles(String methodName, Class<?>[] methodParamTypes, String propertyName,String mapperClass, List<T> dataList, Map<String, String> fileMap) {
        DataMessage dataMessage = new DataMessage();
        dataMessage.setType(MessageType.DATA);
        dataMessage.setMsgId(UUID.randomUUID().toString());
        dataMessage.setSendTime(new Date());
        dataMessage.setMethodName(methodName);
        dataMessage.setMethodParamTypes(methodParamTypes);
        dataMessage.setPropertyName(propertyName);
        dataMessage.setMapperClassName(mapperClass);
        dataMessage.setDataList(dataList);
        try {
            log.debug("com.rongji.ibmmq.service.impl.SendMsgServiceImpl.sendDataAndFiles:"+ JSON.toJSONString(dataMessage));
            dataHandlerService.sendDataMessage(dataMessage);

            if(!CollectionUtils.isEmpty(fileMap)){
                log.debug("com.rongji.ibmmq.service.impl.SendMsgServiceImpl.fileMap:"+ JSON.toJSONString(fileMap));
                for (String path : fileMap.keySet()) {
                    fileHandlerService.sendFile(path,fileMap.get(path));
                }
            }
        }catch (Exception e){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }
}
