package com.njcn.utils.redis;

import com.njcn.enums.DicDataTypeEnum;
import com.njcn.mapper.configuration.DicDataMapper;
import com.njcn.mapper.configuration.DicDataTypeMapper;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.configuration.DicType;
import com.njcn.utils.UserUtil;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.security.auth.login.AccountException;
import java.util.ArrayList;
import java.util.List;

@Service("redisCacheUtil")
public class RedisCacheUtil {
	// 日志记录
	private static final Logger logger = LoggerFactory.getLogger(RedisCacheUtil.class);

	/**
	 * 数据字典的key
	 */
	final static String DATA_KEY="dataKey";

	final static String TYPE_KEY="typeKey";

	@Autowired
	private DicDataMapper dicDataMapper;

	@Autowired
	private DicDataTypeMapper dicTypeMapper;

	@Autowired
	private JedisManager jedisManager;

	@Autowired
	private UserUtil userUtil;
	/**
	 * 获取数据字典类型数据
	 */
	public List<DicType> getType(){
		List<DicType> dicss=new ArrayList<>();
		try {
//			String valueByKey = jedisManager.getValueByKey(RedisDB.PERSISTENCE_QUERY,TYPE_KEY);
			String valueByKey = "";
			if(StringUtils.isNotBlank(valueByKey)){
				JSONArray value = JSONArray.fromObject(valueByKey);
				dicss=(List<DicType>) JSONArray.toCollection(value,DicType.class);
			}else{
				Example example=new Example(DicType.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("state", "1");
				example.setOrderByClause("DICTYPE_NUMBER desc");
				List<DicType> dics = dicTypeMapper.selectByExample(example);
				//字典表不为空就保存到redis中
//				if(!dics.isEmpty()){
//					JSONArray ja=JSONArray.fromObject(dics);
//					jedisManager.saveValueByKey(RedisDB.PERSISTENCE_QUERY, TYPE_KEY, ja.toString(),-1);
//					userUtil.saveDataKey(TYPE_KEY,RedisDB.PER_KEY,RedisDB.DIC_DATA);
//				}
				dicss.addAll(dics);
			}
		} catch (Exception e) {
			logger.error("保存数据字典表类型异常，异常原因为："+e.toString());
		}
		return dicss;
	}


	/**
	 * 获取数据字典内容
	 */
	public List<DicData> getData(){
		List<DicData> dicss=new ArrayList<>();
		try {
//			String valueByKey = jedisManager.getValueByKey(RedisDB.PERSISTENCE_QUERY, DATA_KEY);
			String valueByKey = "";
			if(StringUtils.isNotBlank(valueByKey)){
				JSONArray value = JSONArray.fromObject(valueByKey);
				dicss=(List<DicData>) JSONArray.toCollection(value,DicData.class);
			}else{
				Example example=new Example(DicData.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("state", "1");
				example.setOrderByClause("DIC_NUMBER desc");
				List<DicData> dics = dicDataMapper.selectByExample(example);
//				//字典表不为空就保存到redis中
//				if(!dics.isEmpty()){
//					JSONArray ja=JSONArray.fromObject(dics);
//					jedisManager.saveValueByKey(RedisDB.PERSISTENCE_QUERY, DATA_KEY, ja.toString(),-1);
//					userUtil.saveDataKey(DATA_KEY,RedisDB.PER_KEY,RedisDB.DIC_DATA);
//				}
				dicss.addAll(dics);
			}
		} catch (Exception e) {
			logger.error("保存数据字典表数据异常，异常原因为："+e.toString());
		}
		return dicss;
	}

	/**
	 * 获取数据字典中的电压等级部分
	 */
	public List<DicData> getVoltageData(){
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("电压等级")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的制造商部分
	 * @return
	 */
	public List<DicData> getDeviceCompanyData() {
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("制造厂商")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}


	/**
	 * 获取数据字典中的暂降原因部分
	 */
	public List<DicData> getVoltageReason() {
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("暂降原因")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的暂降类型部分
	 */
	public List<DicData> getVoltageType() {
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("暂降类型")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的干扰源类型终部分
	 */
	public List<DicData> getLoadType() {
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase(DicDataTypeEnum.payloadEnum.getName())){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的区域部分
	 */
	public List<DicData> getArea(){
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("行政区域")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的接线方式部分
	 */
	public List<DicData> getWring(){
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("变压器接线方式")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的资源类目部分
	 */
	public List<DicData> getManType(){
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("资源类目")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的系统事件类型部分
	 */
	public List<DicData> getSystemEvents() throws AccountException{
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("系统事件类型")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		if(StringUtils.isBlank(typeIndex)){
			throw new AccountException("类型字典表无该数据");
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 获取数据字典中的业务事件类型部分
	 */
	public List<DicData> getBusinessEvents()throws AccountException{
		List<DicData> dics = new ArrayList<>();
		List<DicType> type = getType();
		List<DicData> data = getData();
		String typeIndex="";
		for (DicType dictype : type) {
			if(dictype.getDicTypeName().equalsIgnoreCase("业务事件类型")){
				typeIndex=dictype.getDicTypeIndex();
				break;
			}
		}
		if(StringUtils.isBlank(typeIndex)){
			throw new AccountException("类型字典表无该数据");
		}
		for (DicData dicData : data) {
			if(dicData.getDicType().equalsIgnoreCase(typeIndex)){
				dics.add(dicData);
			}
		}
		return dics;
	}

	/**
	 * 清除缓存
	 * 供电公司/变电站/母线/终端/监测点数据发生改变后，需要清理缓存
	 */
	public  void clearConData(){
		String valueByKey="";
		try {
			valueByKey = jedisManager.getValueByKey(RedisDB.PER_KEY, RedisDB.CON_DATA);
			if(StringUtils.isNotBlank(valueByKey)){
				JSONArray ja=JSONArray.fromObject(valueByKey);
				List<String> keys=(List<String>) JSONArray.toCollection(ja, String.class);
				if(!keys.isEmpty()){
					for (String key : keys) {
						jedisManager.deleteByKey(RedisDB.PERSISTENCE_QUERY, key);
					}
				}
				jedisManager.deleteByKey(RedisDB.PER_KEY, RedisDB.CON_DATA);
			}
		} catch (Exception e) {
			logger.error("清除字典表缓存出错，方法名为：clearConData，key："+valueByKey);
		}
	}

	/**
	 * 清除缓存
	 * 字典表数据更新，需要清理缓存
	 */
	public  void clearDicData(){
		String valueByKey="";
		try {
			valueByKey = jedisManager.getValueByKey(RedisDB.PER_KEY, RedisDB.DIC_DATA);
			if(StringUtils.isNotBlank(valueByKey)){
				JSONArray ja=JSONArray.fromObject(valueByKey);
				List<String> keys=(List<String>) JSONArray.toCollection(ja);
				if(!keys.isEmpty()){
					for (String key : keys) {
						jedisManager.deleteByKey(RedisDB.PERSISTENCE_QUERY, key);
					}
				}
				jedisManager.deleteByKey(RedisDB.PER_KEY, RedisDB.DIC_DATA);
			}
		} catch (Exception e) {
			logger.error("清除字典表缓存出错，方法名为：clearDicData，key："+valueByKey);
		}
	}

	/**
	 * 清除缓存
	 * 用户权限数据更新，需要清理缓存
	 */
	public  void clearRoleData(){
		String valueByKey="";
		try {
			valueByKey = jedisManager.getValueByKey(RedisDB.PER_KEY, RedisDB.ROLE_DATA);
			if(StringUtils.isNotBlank(valueByKey)){
				JSONArray ja=JSONArray.fromObject(valueByKey);
				List<String> keys=(List<String>) JSONArray.toCollection(ja, String.class);
				if(!keys.isEmpty()){
					for (String key : keys) {
						jedisManager.deleteByKey(RedisDB.LONG_TIME_QUERY, key);
					}
				}
				jedisManager.deleteByKey(RedisDB.PER_KEY, RedisDB.ROLE_DATA);
			}
		} catch (Exception e) {
			logger.error("清除字典表缓存出错，方法名为：clearRoleData，key："+valueByKey);
		}
	}


	/**
	 * 清除缓存
	 * 新增用户进行审核时，需要清理缓存
	 */
	public  void clearRolesData(String key){
		String valueByKey;
		try {
			valueByKey = jedisManager.getValueByKey(RedisDB.PER_KEY, key);
			if(StringUtils.isNotBlank(valueByKey)){
				JSONArray ja=JSONArray.fromObject(valueByKey);
				List<String> keys=(List<String>) JSONArray.toCollection(ja, String.class);
				if(!keys.isEmpty()){
					for (String rolekey : keys) {
						jedisManager.deleteByKey(RedisDB.LONG_TIME_QUERY, rolekey);
					}
				}
				jedisManager.deleteByKey(RedisDB.PER_KEY, key);
			}
		} catch (Exception e) {
			logger.error("清除审核缓存出错，方法名为：clearRolesData，key："+key);
		}
	}

}
