package com.ym.mec.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ym.mec.biz.dal.dao.LiveGoodsMapperDao;
import com.ym.mec.biz.dal.dto.LiveGoodsMapperDto;
import com.ym.mec.biz.dal.dto.RedisKeyConstant;
import com.ym.mec.biz.dal.entity.ImLiveBroadcastRoom;
import com.ym.mec.biz.dal.entity.LiveGoodsMapper;
import com.ym.mec.biz.dal.page.LiveGoodsMapperQueryInfo;
import com.ym.mec.biz.service.ImLiveBroadcastRoomService;
import com.ym.mec.biz.service.LiveGoodsMapperService;
import com.ym.mec.biz.service.LiveGoodsService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.ImRoomMessage;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.collection.MapUtil;
import org.apache.commons.collections.CollectionUtils;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class LiveGoodsMapperServiceImpl extends BaseServiceImpl<Integer, LiveGoodsMapper>  implements LiveGoodsMapperService {
	
	@Autowired
	private LiveGoodsService liveGoodsService;
	@Autowired
	private LiveGoodsMapperDao liveGoodsMapperDao;
	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private ImLiveBroadcastRoomService imLiveBroadcastRoomService;
	@Autowired
	private RedissonClient redissonClient;


	@Override
	public BaseDAO<Integer, LiveGoodsMapper> getDAO() {
		return liveGoodsMapperDao;
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public void add(String liveId, String liveGoodsIds) {
		liveGoodsMapperDao.batchInsert(liveId,liveGoodsIds.split(","));
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void upGoods(Integer liveGoodsId, String liveId) {
		int i = liveGoodsMapperDao.updateStatus(liveId, liveGoodsId, true);
		if (i == 0) {
			return;
		}
		ImLiveBroadcastRoom imLiveBroadcastRoom = Optional
				.of(imLiveBroadcastRoomService.getBaseMapper().selectOne(new QueryWrapper<ImLiveBroadcastRoom>().eq("room_uid_",liveId))).
				orElseThrow(() -> new RuntimeException("直播间不存在"));
		//通知直播间商品信息变更
		this.publishRoomMsg(imLiveBroadcastRoom);
		//商品上架，更新缓存
		liveGoodsService.initGoodsStockCache(liveGoodsId,liveId);
	}

	@Override
	public List<LiveGoodsMapper> findByLiveGoodsIdAndStatus(Integer goodsId, Boolean status) {
		return liveGoodsMapperDao.findByLiveGoodsIdAndStatus(goodsId,status);
	}

    @Override
    public PageInfo<LiveGoodsMapperDto> queryGoodsPage(LiveGoodsMapperQueryInfo queryInfo) {
		PageInfo<LiveGoodsMapperDto> pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List<LiveGoodsMapperDto> dataList = null;
		int count = liveGoodsMapperDao.countLiveGoods(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = liveGoodsMapperDao.queryGoodsPage(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
    }

	@Override
	public List<LiveGoodsMapperDto> getLiveGoodsList(String liveId, Integer liveGoodsId, Boolean status) {
		return liveGoodsMapperDao.getLiveGoodsList(liveId,liveGoodsId,status);
	}

	@Override
	public List<Integer> queryGoodsIdsByLiveId(String liveId) {
		return liveGoodsMapperDao.queryGoodsIdsByLiveId(liveId);
	}

	private void publishRoomMsg(ImLiveBroadcastRoom imLiveBroadcastRoom) {
		ImRoomMessage message = new ImRoomMessage();
		message.setIsIncludeSender(1);
		message.setObjectName(ImRoomMessage.LIVE_GOODS_CHANGE);
		message.setToChatroomId(imLiveBroadcastRoom.getRoomUid());
		message.setFromUserId(imLiveBroadcastRoom.getSpeakerId().toString());
		message.setContent(liveGoodsMapperDao.getLiveGoodsList(imLiveBroadcastRoom.getRoomUid(),null,true));
		imFeignService.publishRoomMsg(message);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void downGoods(String liveId){
		ImLiveBroadcastRoom imLiveBroadcastRoom = Optional
				.of(imLiveBroadcastRoomService.getBaseMapper().selectOne(new QueryWrapper<ImLiveBroadcastRoom>().eq("room_uid_",liveId))).
				orElseThrow(() -> new RuntimeException("直播间不存在"));
		List<LiveGoodsMapperDto> liveGoodsList = liveGoodsMapperDao.getLiveGoodsList(liveId, null, true);
		if (CollectionUtils.isEmpty(liveGoodsList)) {
			return;
		}
		for (LiveGoodsMapperDto liveGoodsMapperDto : liveGoodsList) {
			this.down(liveGoodsMapperDto.getId(), liveId,imLiveBroadcastRoom);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void downGoods(Integer liveGoodsId, String liveId){
		ImLiveBroadcastRoom imLiveBroadcastRoom = Optional
				.of(imLiveBroadcastRoomService.getBaseMapper().selectOne(new QueryWrapper<ImLiveBroadcastRoom>().eq("room_uid_",liveId))).
				orElseThrow(() -> new RuntimeException("直播间不存在"));
		LiveGoodsMapper liveGoodsMapper = Optional.ofNullable(liveGoodsMapperDao.findByLiveIdAndGoodsId(liveId, liveGoodsId)).
				orElseThrow(() -> new RuntimeException("直播间不存在该商品"));
		if(!liveGoodsMapper.getStatus()){
			throw new BizException("该商品已下架");
		}
		this.down(liveGoodsId, liveId,imLiveBroadcastRoom);
	}

	private void down(Integer liveGoodsId, String liveId,ImLiveBroadcastRoom imLiveBroadcastRoom){
		int i = liveGoodsMapperDao.updateStatus(liveId, liveGoodsId, false);
		if (i == 0) {
			return;
		}
		//通知直播间，商品信息变更
		this.publishRoomMsg(imLiveBroadcastRoom);
		//商品下架后，将缓存的库存设置为0
		redissonClient.getBucket(RedisKeyConstant.LIVE_GOODS_STOCK_CACHE_KEY + liveId + liveGoodsId).set(0);
		//如果下架的是免费的直播课商品，清空购买的学员的缓存记录
//		if(liveGoodsId.equals(2) || liveGoodsId.equals(3) || liveGoodsId.equals(4)){
//			//删除当前直播间免费直播课的购买记录缓存
//			StringBuffer sb = new StringBuffer(RedisKeyConstant.LIVE_GOODS_ZERO_CACHE_KEY).append(liveId).
//					append("_").append(liveGoodsId);
//			redissonClient.getBucket(sb.toString()).delete();
//		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void downGoods(Integer liveGoodsId){
		List<LiveGoodsMapper> liveGoodsMappers = liveGoodsMapperDao.findByLiveGoodsIdAndStatus(liveGoodsId,true);
		if(liveGoodsMappers.size()>0){
			//下架直播间商品
			int i = liveGoodsMapperDao.updateStatus(null, liveGoodsId, false);
			if (i == 0) {
				return;
			}
			//通知直播间，商品信息变更
			for (LiveGoodsMapper liveGoodsMapper : liveGoodsMappers) {
				ImLiveBroadcastRoom imLiveBroadcastRoom = Optional
						.of(imLiveBroadcastRoomService.getBaseMapper().selectOne(new QueryWrapper<ImLiveBroadcastRoom>().eq("room_uid_",liveGoodsMapper.getLiveId()))).
						orElseThrow(() -> new RuntimeException("直播间不存在"));
				this.publishRoomMsg(imLiveBroadcastRoom);
			}
		}
	}
}