package com.platform.modules.live.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.platform.common.utils.ConverterUtils;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.RedisContants;
import com.platform.common.utils.RedisUtils;
import com.platform.modules.live.dao.LiveChannelDao;
import com.platform.modules.live.entity.LiveChannelEntity;
import com.platform.modules.live.service.LiveChannelService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.transaction.annotation.Transactional;

@Service("liveChannelService")
@Transactional
public class LiveChannelServiceImpl extends ServiceImpl<LiveChannelDao, LiveChannelEntity> implements LiveChannelService {

	@Autowired
	private RedisUtils redisUtils;

	@Override
	@Transactional(readOnly = true)
	public PageUtils page(Map<String, Object> params){
		//检索记录
		int current = ConverterUtils.parseInt(params.get("page"));
	    int limit = ConverterUtils.parseInt(params.get("limit"));
	    Page<Map<String, Object>> page = new Page<>(current, limit);
	    List<LiveChannelEntity> pageList = this.baseMapper.queryPageMap(page, params);
	    List<Map<String, Object>> list = new ArrayList<>();
		if(pageList!=null && pageList.size()>0){
			for(int i=0;i<pageList.size();i++){
				Map<String, Object> map = new HashMap<>();
				LiveChannelEntity bean = pageList.get(i);
				if(bean==null){
					continue;
				}
				map.put("id", bean.getId());
				map.put("name", bean.getName());
				map.put("priority", bean.getPriority());
				map.put("identify", bean.getIdentify());
				map.put("isDisplay", bean.getIsDisplay());
				map.put("creatorUserName", bean.getCreatorUserName());
				map.put("lastUpdateUserName", bean.getLastUpdateUserName());
				list.add(map);
			}
		}
	    page.setRecords(list);
		return new PageUtils(page);
	}

	@Override
	@Transactional(readOnly = true)
	public JSONArray getAllList(){
		// 20200227_Mxy
		// String str = redisUtils.hasKey(RedisContants.CHANNEL_LIST)? null : redisUtils.get(RedisContants.CHANNEL_LIST);
		String str = redisUtils.hasKey(RedisContants.CHANNEL_LIST) ? redisUtils.get(RedisContants.CHANNEL_LIST) : null;
		if(StringUtils.isBlank(str)){
			EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<LiveChannelEntity>(new LiveChannelEntity());
			wrapper.eq("is_delete", 0);
			wrapper.eq("is_display", 1);
			wrapper.orderBy("priority", false).orderBy("id", false);
			List<LiveChannelEntity> list = this.baseMapper.selectList(wrapper);
			JSONArray jsonArray = new JSONArray();
			// 20200227_Mxy
			// if(list==null || list.size()>0){
			if (null != list && list.size() > 0){
				for(LiveChannelEntity bean : list){
					JSONObject json = new JSONObject();
					json.put("id", bean.getId());
					json.put("name", bean.getName());
					jsonArray.add(json);
				}
				redisUtils.delete(RedisContants.CHANNEL_LIST);
				if(jsonArray!=null && jsonArray.size()>0){
					redisUtils.set(RedisContants.CHANNEL_LIST, jsonArray.toString(),-1);
				}
			}
			return jsonArray;
		}else{
			return JSONArray.fromObject(str);
		}
	}
	@Override
	public void save(LiveChannelEntity liveChannel, Long userId){
		liveChannel.setCreatorId(userId);
		liveChannel.setCreateDate(new Date());

		this.baseMapper.insert(liveChannel);
		if(liveChannel.getIsDisplay()==1 || liveChannel.getIsDisplay().equals(1)){
			freshRedisCache();
		}
	}

	@Override
	public void update(LiveChannelEntity liveChannel, Long userId){
		if (null == liveChannel || null == liveChannel.getId()) {
			throw new NullPointerException();
		}
		LiveChannelEntity dbChannel = this.baseMapper.selectById(liveChannel.getId());
		if (null == dbChannel) {
			throw new NullPointerException();
		}
		liveChannel.setLastUpdateDate(new Date());
		liveChannel.setLastUpdateUser(userId);
		Integer i = this.baseMapper.updateById(liveChannel);
		if(i>0){
			freshRedisCache();
		}
	}

	@Override
	public void deleteBatch(Integer[] ids, Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		LiveChannelEntity entity = new LiveChannelEntity();
		entity.setIsDelete(1);
		entity.setLastUpdateDate(new Date());
		entity.setLastUpdateUser(userId);

		EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<LiveChannelEntity>(new LiveChannelEntity());
		wrapper.in("id", ids);
		Integer i = this.baseMapper.update(entity, wrapper);
		if(i>0){
			freshRedisCache();
		}
	}

	@Override
	public void displayBatch(Integer[] ids, Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		LiveChannelEntity entity = new LiveChannelEntity();
		entity.setIsDisplay(1);
		entity.setLastUpdateDate(new Date());
		entity.setLastUpdateUser(userId);

		EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<LiveChannelEntity>(new LiveChannelEntity());
		wrapper.in("id", ids);
		Integer i = this.baseMapper.update(entity, wrapper);
		if(i>0){
			freshRedisCache();
		}
	}

	@Override
	public void cancelDisplayBatch(Integer[] ids, Long userId){
		if(ids==null || ids.length==0){
			return;
		}
		LiveChannelEntity entity = new LiveChannelEntity();
		entity.setIsDisplay(0);
		entity.setLastUpdateDate(new Date());
		entity.setLastUpdateUser(userId);

		EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<LiveChannelEntity>(new LiveChannelEntity());
		wrapper.in("id", ids);
		Integer i = this.baseMapper.update(entity, wrapper);
		if(i>0){
			freshRedisCache();
		}
	}

	@Override
	public void priority(Integer[] ids,Integer[] prioritys,Long userId){
		if(ids==null || ids.length==0 || prioritys==null || prioritys.length==0 || ids.length!=prioritys.length){
			return;
		}
		int count = 0;
		for(int i=0;i<ids.length;i++){
			if(ids[i]!=null && prioritys[i]!=null){
				LiveChannelEntity entity = new LiveChannelEntity();
				entity.setPriority(prioritys[i]);
				entity.setLastUpdateDate(new Date());
				entity.setLastUpdateUser(userId);
				entity.setId(ids[i]);
				count += this.baseMapper.updateById(entity);
			}
		}
		if(count>0){
			freshRedisCache();
		}
	}

	private void freshRedisCache() {
		EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<LiveChannelEntity>(new LiveChannelEntity());
		wrapper.eq("is_delete", 0);
		wrapper.eq("is_display", 1);
		wrapper.orderBy("priority", false).orderBy("id", false);
		List<LiveChannelEntity> list = this.baseMapper.selectList(wrapper);
		// 20200319_Mxy
//		if(list==null || list.size()>0){
		if(null != list && list.size() > 0){
			JSONArray jsonArray = new JSONArray();
			for(LiveChannelEntity bean : list){
				JSONObject json = new JSONObject();
				json.put("id", bean.getId());
				json.put("name", bean.getName());
				jsonArray.add(json);
			}
			redisUtils.delete(RedisContants.CHANNEL_LIST);
			if(jsonArray!=null && jsonArray.size()>0){
				redisUtils.set(RedisContants.CHANNEL_LIST, jsonArray.toString(), -1);
			}
		}else{
			redisUtils.delete(RedisContants.CHANNEL_LIST);
		}
	}


	@Override
	@Transactional(readOnly = true)
	public JSONArray getRedisCache(){

		String str = redisUtils.get(RedisContants.CHANNEL_LIST);

		// 20200319_Mxy 缓存中没有则查库
		if(StringUtils.isBlank(str)){

			EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<>();

			wrapper.eq("is_delete", 0);
			wrapper.eq("is_display", 1);
			wrapper.orderBy("priority", false).orderBy("id", false);

			List<LiveChannelEntity> channels = this.baseMapper.selectList(wrapper);

			if (null == channels || channels.size() == 0)
				return null;

			JSONArray jsonArray = new JSONArray();

			channels.forEach(channel -> {
				JSONObject json = new JSONObject();
				json.put("id", channel.getId());
				json.put("name", channel.getName());
				jsonArray.add(json);
			});

			redisUtils.delete(RedisContants.CHANNEL_LIST);
			// 存入Redis
			if (jsonArray.size() > 0){
				redisUtils.set(RedisContants.CHANNEL_LIST, jsonArray.toString(), -1);
			}

			return jsonArray;
		}

		return JSONArray.fromObject(str);
	}

	@Override
	public JSONArray getAllChannel() {

		EntityWrapper<LiveChannelEntity> wrapper = new EntityWrapper<>();
		wrapper.eq("is_delete", 0);
		wrapper.orderBy("priority", false).orderBy("id", false);

		List<LiveChannelEntity> channels = this.baseMapper.selectList(wrapper);

		if (null == channels || channels.size() == 0)
			return null;

        JSONArray jsonArray = new JSONArray();

        channels.forEach(channel -> {
			JSONObject json = new JSONObject();
			json.put("id", channel.getId());
			json.put("name", channel.getName());
			jsonArray.add(json);
		});

		return jsonArray;
	}
}
