package com.tzy.listener.mq;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.rabbitmq.client.Channel;
import com.tzy.common.constant.MqConstans;
import com.tzy.common.constant.NoticeMsgModel;
import com.tzy.common.dto.notice.ToNoticeUserDTO;
import com.tzy.common.utils.bean.BeanUtils;
import com.tzy.sportcard.api.mapper.AppNotifyConfigMapper;
import com.tzy.system.domain.TzySysNoticeRecord;
import com.tzy.system.mapper.TzySysNoticeRecordMapper;
import com.tzy.util.NoticeType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Component
public class MerchantNotifyConsumer {

	@Resource
	private AppNotifyConfigMapper appNotifyConfigMapper;
	@Resource
	private TzySysNoticeRecordMapper noticeRecordMapper;

	@RabbitHandler
	@RabbitListener(queues = {MqConstans.QUEUE_MERCHANT_NOTIFY})
	public void notifyConsumer(String param, Channel channel, Message message) throws IOException {
		log.debug("商家通知消息:{}", param);
		try {
			//notifyLikeMerchantUser(param);
		} catch (Exception e) {
			log.error("商家通知异常,组团id:{}", param, e);
		}
		channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
	}

	private void notifyLikeMerchantUser(String param) {
		JSONObject notifyJson = JSON.parseObject(param);
		String type = notifyJson.getString("type");
		Integer merchantId = notifyJson.getIntValue("merchantId");
		String merchantName = notifyJson.getString("merchantName");
		Integer groupInfoId = notifyJson.getIntValue("groupInfoId");
		String groupInfoName = notifyJson.getString("groupInfoName");

		List<ToNoticeUserDTO> noticeUsers = appNotifyConfigMapper.selectNotifyUsersByMerchant(type, merchantId);
		if(CollectionUtils.isEmpty(noticeUsers)){
			return;
		}
		String refUrl = "live".equalsIgnoreCase(type) ? NoticeType.group_detail_url + groupInfoId : NoticeType.MERCHANT_SHOP_TOP + merchantId;
		String msg = "live".equalsIgnoreCase(type) ? String.format(NoticeMsgModel.MERCHANT_LIVING_NOTIFY, groupInfoName)
				: String.format(NoticeMsgModel.MERCHANT_SALE_NEW_NOTIFY, merchantName);

		String title = "live".equalsIgnoreCase(type) ? "直播通知" : "开售通知";
		List<TzySysNoticeRecord> records = noticeUsers.stream().filter(u -> checkUserIsNotify(type, u, merchantId))
				.map(u -> buildNoticeRecord(u.getUserId(), type.toUpperCase(), refUrl, msg, title)).collect(Collectors.toList());
		if (CollectionUtils.isEmpty(records)) {
			return;
		}
		List<List<TzySysNoticeRecord>> batchList = BeanUtils.batchList(records, 500);
		batchList.forEach(r -> noticeRecordMapper.batchInsertRecord(r));
	}

	private TzySysNoticeRecord buildNoticeRecord(Long userId, String type, String refUrl, String msg, String title) {
		TzySysNoticeRecord noticeRecord = new TzySysNoticeRecord();
		noticeRecord.setFromUser("HOBBY STOCKS");
		noticeRecord.setTitle(title);
		noticeRecord.setToUserid(userId);
		noticeRecord.setContentUrl(refUrl);
		noticeRecord.setMsg(msg);
		noticeRecord.setType(type);
		noticeRecord.setSubType(type);
		return noticeRecord;
	}

	private boolean checkUserIsNotify(String type, ToNoticeUserDTO noticeUserDTO, Integer merchantId) {
		if ("PRIVATE_MERCHANT".equals(noticeUserDTO.getNotifyType())) {
			JSONObject configJson = JSON.parseObject(noticeUserDTO.getNotifyConfig());
			String merchantIds = configJson.getString("merchantIds");
			if (StringUtils.isNotEmpty(merchantIds)) {
				List<String> merchantIdList = Arrays.asList(merchantIds.split(","));
				return merchantIdList.contains(merchantId.toString());
			}
		}
		if ("live".equals(type) && "BUY".equals(noticeUserDTO.getNotifyType())) {
			return false;
		}
		return true;
	}


}
