package com.hotent.portal.persistence.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gexin.fastjson.JSON;
import com.hotent.base.enums.ResponseErrorEnums;
import com.hotent.base.jms.Notice;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import com.hotent.portal.jms.impl.ExternalHandler;
import com.hotent.portal.model.PortalBizSystem;
import com.hotent.portal.model.PortalMsgSendLog;
import com.hotent.portal.persistence.dao.PortalBizSystemDao;
import com.hotent.portal.persistence.dao.PortalMsgSendLogDao;
import com.hotent.portal.persistence.manager.PortalMsgSendLogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;


/**
 *  外部消息日志管理
 *
 * @company 广州宏天软件股份有限公司
 * @author cola
 * @since 2021-08-31
 */
@Service
public class PortalMsgSendLogManagerImpl extends BaseManagerImpl<PortalMsgSendLogDao, PortalMsgSendLog> implements PortalMsgSendLogManager {

	private final String flowKey="flowKey_";
	private final String actionType="ACTION_TYPE_";
	private final String sysCode="sysCode";
	private final String title="subject_";
	private final String trigNodeId="TRIG_NODE_ID_";
	private final Logger logger= LoggerFactory.getLogger(PortalMsgSendLogManagerImpl.class);

	@Autowired
	PortalMsgSendLogDao portalMsgSendLogDao;
	@Autowired
	PortalBizSystemDao portalBizSystemDao;
	@Autowired
	ExternalHandler externalHandler;
	@Autowired
	PortalMsgSendLogManager portalMsgSendLogManager;


	@Override
	public PortalMsgSendLog getDetail(String id) {
    	PortalMsgSendLog portalMsgSendLog = this.get(id);
    	

		return portalMsgSendLog;
	}
	@Override
	@Transactional
	public void createOrUpdate(PortalMsgSendLog portalMsgSendLog) {
		//新建或更新
		this.saveOrUpdate(portalMsgSendLog);
	}

	// 保存消息日志
	public CommonResult saveExternalMsg(Notice notice) {
		Map<String, Object> vars = notice.getVars();
		PortalMsgSendLog log = new PortalMsgSendLog();
		log.setFlowKey((String) vars.get(flowKey));
		log.setActionType((String) vars.get(actionType));
		log.setSysCode((String)vars.get(sysCode));
		log.setTrigUserId(notice.getSenderId());
		log.setSendTime(LocalDateTime.now());
		log.setTitle((String)vars.get(title));
		log.setContent(JSON.toJSONString(notice));
		log.setStatus("1"); // 0失败，1成功
		log.setTrigNodeId((String)vars.get(trigNodeId));
		int res= portalMsgSendLogDao.insert(log);
		if (res==1){
			return new CommonResult(true, ResponseErrorEnums.SUCCESS_OPTION.getMessage(),log.getId());
		}
		return new CommonResult(false,ResponseErrorEnums.FAIL_OPTION.getMessage(),null);
	}

	@Override
	@Transactional
	public CommonResult sendMsgToExternalQueue(Notice notice, String sysCode) {
		PortalBizSystem bizSystem = portalBizSystemDao.selectOne(new QueryWrapper<PortalBizSystem>().eq("SYS_CODE_", sysCode));
		if (bizSystem==null){
			return new CommonResult(false,ResponseErrorEnums.FAIL_OPTION.getMessage(),null);
		}
		// 该外部系统配置了队列，才发送消息
		if (StringUtil.isNotEmpty(bizSystem.getBpmMsgQueue())){
			CommonResult result = this.saveExternalMsg(notice);
			boolean res = externalHandler.send(notice, bizSystem.getBpmMsgQueue());
			// 发送消息失败，更新默认的成功状态：改为失败
			if(!res){
				String portalMsgSendLogId=(String) result.getValue();
				PortalMsgSendLog portalMsgSendLog = portalMsgSendLogDao.selectById(portalMsgSendLogId);
				portalMsgSendLog.setStatus("0");
				QueryWrapper<PortalMsgSendLog> wrapper = new QueryWrapper<>();
				wrapper.eq("ID_",portalMsgSendLogId);
				portalMsgSendLogDao.update(portalMsgSendLog,wrapper);
			}
		}
		return new CommonResult(true,ResponseErrorEnums.SUCCESS_OPTION.getMessage(),null);
	}

	@Override
	public CommonResult retrySendMsgById(String id) {
		PortalMsgSendLog portalMsgSendLog = portalMsgSendLogDao.selectById(id);
		if (portalMsgSendLog==null){
			return new CommonResult(false,ResponseErrorEnums.NO_RECORD.getMessage(),null);
		}
		// 0失败，1成功
		if (portalMsgSendLog.getStatus().equals("1")){
			return new CommonResult(false,"该条消息已成功发送到队列，请问重复发送",null);
		}
		// 根据sysCode查询对应的队列
		QueryWrapper<PortalBizSystem> portalBizSystemQueryWrapper = new QueryWrapper<>();
		portalBizSystemQueryWrapper.eq("SYS_CODE_", portalMsgSendLog.getSysCode());
		PortalBizSystem portalBizSystem = portalBizSystemDao.selectOne(portalBizSystemQueryWrapper);
		String noticeJson = portalMsgSendLog.getContent();
		Notice notice = JSON.parseObject(noticeJson, Notice.class);
		logger.debug("noticeJson转换后的格式：{}",noticeJson);
		boolean send = externalHandler.send(notice, portalBizSystem.getBpmMsgQueue());
		if (send){
			portalMsgSendLog.setStatus("1");
			portalMsgSendLogDao.updateById(portalMsgSendLog);
			return new CommonResult(true,ResponseErrorEnums.SUCCESS_OPTION.getMessage(),null);
		}
		return new CommonResult(false,"重试失败，失败原因请查看相关日志",null);
	}
}
