package com.ruoyi.reportrzs.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.report.vo.ViewStatisticsInfoRep;
import com.ruoyi.report.vo.ViewStatisticsInfoVo;
import com.ruoyi.report.vo.ViewStatisticsInfoVo.Item;
import com.ruoyi.reportrzs.domain.RzsViewStatisticsInfo;
import com.ruoyi.reportrzs.mapper.RzsViewStatisticsInfoMapper;
import com.ruoyi.reportrzs.service.IRzsViewStatisticsInfoService;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.utils.BladeRegionUtils;

/**
 * 专利授权-概况统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-27
 */
@Service
public class RzsViewStatisticsInfoServiceImpl extends ServiceImpl<RzsViewStatisticsInfoMapper, RzsViewStatisticsInfo>
		implements IRzsViewStatisticsInfoService {

	@Autowired
	private RzsViewStatisticsInfoMapper rzsViewStatisticsInfoMapper;
	@Autowired
	private IBladeRegionService bladeRegionService;

	
	public RzsViewStatisticsInfo getLastOne() {
		PageHelper.startPage(1, 1);
		QueryWrapper<RzsViewStatisticsInfo> queryWrapper = Wrappers.query();
		queryWrapper.orderByDesc("year", "month");
		List<RzsViewStatisticsInfo> list = this.list(queryWrapper);
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}
	
	
	private void margeNotThisArea(List<Map> notThisAreaList,Map dataMap,Map<String,Map> alreadyNotThisArea,String areaCodeKey,String areaNameKey,String[]keys,String[]dataKeys) {
		StringBuffer keysb=new StringBuffer();
		
//		String areaCode="000000";
		String areaCode="非本区划";
		String areaName="非本区划";
		keysb.append(areaCode).append("_").append(areaName);
		for(String key:keys) {
			String val=getStr(dataMap, key);
			if(StringUtils.isBlank(val)) {
				val="null";
			}
			keysb.append("_").append(val);
		}
		if(!alreadyNotThisArea.containsKey(keysb.toString())) {
			Map newMap=new HashMap();
			newMap.putAll(dataMap);
			newMap.put(areaCodeKey, areaCode);
			newMap.put(areaNameKey, areaName);
			notThisAreaList.add(newMap);
			alreadyNotThisArea.put(keysb.toString(), newMap);
		}else {
			Map oldMap=alreadyNotThisArea.get(keysb.toString());
			for(String key:dataKeys) {
				long oldVal=getLong(oldMap, key);
				long newVal=getLong(dataMap, key);
				oldMap.put(key, oldVal+newVal);
			}
		}
	}
	private boolean isNotThisArea(Map map){
		Object obj=map.get("not_this_area");
		if(obj!=null) {
			return Boolean.parseBoolean(obj+"");
		}
		return false;
	}
	@Override
	public ViewStatisticsInfoRep listByReport(RzsViewStatisticsInfo rzsViewStatisticsInfo) {

		// TODO Auto-generated method stub

//		List<RzlViewStatisticsInfoVo> typeTotalList = new ArrayList<RzlViewStatisticsInfoVo>();
		ViewStatisticsInfoRep rep = new ViewStatisticsInfoRep();
		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(rzsViewStatisticsInfo.getCityCode()) && !"53".equals(rzsViewStatisticsInfo.getCityCode())) {
			String cityCode = rzsViewStatisticsInfo.getCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				rzsViewStatisticsInfo.setCityCode(cityCode);
			}
		}
		
		
		

		String cityCode = null;
		if (StringUtils.isNotBlank(rzsViewStatisticsInfo.getCityCode())
				&& !"53".equals(rzsViewStatisticsInfo.getCityCode())) {
			cityCode = rzsViewStatisticsInfo.getCityCode().trim();
		}
		rzsViewStatisticsInfo.setCityCode(cityCode);
		String qyear = rzsViewStatisticsInfo.getYear();

		if (StringUtils.isBlank(qyear)) {
//	            qyear = new SimpleDateFormat("yyyy").format(new Date());
			throw new RuntimeException("请指定统计年份");
		}

		String month = rzsViewStatisticsInfo.getMonth();
		if (StringUtils.isBlank(month)) {
			throw new RuntimeException("请指定统计月份");
		}

		if (StringUtils.isNotBlank(qyear)) {
			String minYear = (Integer.parseInt(qyear) - 9) + "";
			rzsViewStatisticsInfo.setMinYear(minYear);
			rzsViewStatisticsInfo.setMaxYear(qyear);
		}
		List<Map> mapList = null;
		if(retEmpty) {
			mapList = new ArrayList<Map>();	
		}else {
			mapList =rzsViewStatisticsInfoMapper.listByReport(rzsViewStatisticsInfo);
		}
		
		
	        
		boolean needSumNotThisArea=false;
		if(StringUtils.isNotBlank(cityCode)) {
			needSumNotThisArea=true;
		}
		List<Map> notThisAreaList=new ArrayList<Map>();
		Map<String,Map> alreadyNotThisArea=new HashMap<String,Map>();
		if(needSumNotThisArea && mapList!=null && !mapList.isEmpty()) {
			List<Map> newList = new ArrayList<Map>();
			
			BladeRegionUtils.setNotThisArea(mapList, cityCode);
//			List<String> allCodes=bladeRegionService.getAllAreaCode();
//			Map<String,Boolean>alreadyMap=new HashMap<String,Boolean>();
			for(Map map:mapList) {
				String area_code=getStr(map, "area_code");
//				if(StringUtils.isBlank(area_code) || !area_code.startsWith(cityCode)) {
				if(isNotThisArea(map)) {
					//合并到本区化
					margeNotThisArea(notThisAreaList,map,alreadyNotThisArea,"area_code","area_name"
							,new String[] {"patent_type","year"},new String[] {"total_cnt","higher_school","research_institute","enterprise","institutions","individual"});
				}else {
					newList.add(map);//不是非本区划
				}
			}
			mapList=newList;
			mapList.addAll(notThisAreaList);
		}
		

		// key: areaName  20231022 key改成 areaCode
		Map<String, List<ViewStatisticsInfoVo>> areaMap = new HashMap<String, List<ViewStatisticsInfoVo>>();

		// key:areaName_type
		Map<String, ViewStatisticsInfoVo> areaTypeMap = new HashMap<String, ViewStatisticsInfoVo>();

		// key: type
		Map<String, ViewStatisticsInfoVo> typeTotalMap = new HashMap<String, ViewStatisticsInfoVo>();

		Set<String> yearSet = new HashSet<String>();

		for (Map itemMap : mapList) {

			String areaName = null;

			StringBuffer sb = new StringBuffer();
//			if (itemMap.containsKey("area_name")) {
//				areaName = itemMap.get("area_name").toString();
//			} else {
//				areaName = "null";
//			}

			if (itemMap.containsKey("area_code")) {
				areaName = itemMap.get("area_code").toString();
			} else {
				areaName = "null";
			}
			
			sb.append(areaName);
			sb.append("_");

			String patentType = null;
			if (itemMap.containsKey("patent_type")) {
				patentType = itemMap.get("patent_type").toString();
			} else {
				patentType = "null";
			}
			sb.append(patentType);

			String alreadyKey = sb.toString();

			ViewStatisticsInfoVo vo = null;
			if (areaTypeMap.containsKey(alreadyKey)) {
				vo = areaTypeMap.get(alreadyKey);
			} else {
				vo = new ViewStatisticsInfoVo();
				// list.add(vo);
				vo.setPatentType(patentType);
				vo.setYearData(new LinkedHashMap<String, ViewStatisticsInfoVo.Item>());
				areaTypeMap.put(alreadyKey, vo);

				if (!areaMap.containsKey(areaName)) {
					List<ViewStatisticsInfoVo> areaList = new ArrayList<ViewStatisticsInfoVo>();
					areaMap.put(areaName, areaList);
					areaList.add(vo);
				} else {
					areaMap.get(areaName).add(vo);
				}

			}

			String year = getStr(itemMap, "year");
			yearSet.add(year);
			ViewStatisticsInfoVo.Item item = new ViewStatisticsInfoVo.Item();
			item.setYear(year);
			item.setTotalCnt(getLong(itemMap, "total_cnt"));
			item.setHigherSchool(getLong(itemMap, "higher_school"));
			item.setResearchInstitute(getLong(itemMap, "research_institute"));
			item.setEnterprise(getLong(itemMap, "enterprise"));
			item.setInstitutions(getLong(itemMap, "institutions"));
			item.setIndividual(getLong(itemMap, "individual"));

			vo.getYearData().put(year, item);
			// 总计
			ViewStatisticsInfoVo typeTotal = null;
			if (typeTotalMap.containsKey(patentType)) {
				typeTotal = typeTotalMap.get(patentType);
			} else {
				typeTotal = new ViewStatisticsInfoVo();

//				if(areaName==null || "null".equals(areaName.trim())  || "".equals(areaName.trim()) ) {
				typeTotal.setPatentType(patentType);
				typeTotal.setYearData(new LinkedHashMap<String, ViewStatisticsInfoVo.Item>());
//				}

				typeTotalMap.put(patentType, typeTotal);
			}
			Item totItem = null;
			Item curr = item;
			if (typeTotal.getYearData().containsKey(year)) {
				totItem = typeTotal.getYearData().get(year);

				totItem.setTotalCnt(totItem.getTotalCnt() + curr.getTotalCnt());
				totItem.setHigherSchool(totItem.getHigherSchool() + curr.getHigherSchool());
				totItem.setResearchInstitute(totItem.getResearchInstitute() + curr.getResearchInstitute());
				totItem.setEnterprise(totItem.getEnterprise() + curr.getEnterprise());
				totItem.setInstitutions(totItem.getInstitutions() + curr.getInstitutions());
				totItem.setIndividual(totItem.getIndividual() + curr.getIndividual());

			} else {
				totItem = new Item();
				totItem.setYear(year);
				typeTotal.getYearData().put(year, totItem);

				totItem.setTotalCnt(curr.getTotalCnt());
				totItem.setHigherSchool(curr.getHigherSchool());
				totItem.setResearchInstitute(curr.getResearchInstitute());
				totItem.setEnterprise(curr.getEnterprise());
				totItem.setInstitutions(curr.getInstitutions());
				totItem.setIndividual(curr.getIndividual());
			}

		}

		// 处理小计
		for (Map.Entry<String, List<ViewStatisticsInfoVo>> ent : areaMap.entrySet()) {
			List<ViewStatisticsInfoVo> areaList = ent.getValue();

			ViewStatisticsInfoVo total = new ViewStatisticsInfoVo();
			total.setAreaName(ent.getKey());
			total.setPatentType("总计");

			total.setYearData(new LinkedHashMap<String, Item>());
			for (ViewStatisticsInfoVo vo : areaList) {
				Map<String, Item> yearData = vo.getYearData();

				for (Map.Entry<String, Item> itemEnt : yearData.entrySet()) {
					String year = itemEnt.getKey();
					if (total.getYearData().containsKey(itemEnt.getKey())) {
						// 累加
						Item item = total.getYearData().get(itemEnt.getKey());
						Item curr = itemEnt.getValue();

						item.setTotalCnt(item.getTotalCnt() + curr.getTotalCnt());
						item.setHigherSchool(item.getHigherSchool() + curr.getHigherSchool());
						item.setResearchInstitute(item.getResearchInstitute() + curr.getResearchInstitute());
						item.setEnterprise(item.getEnterprise() + curr.getEnterprise());
						item.setInstitutions(item.getInstitutions() + curr.getInstitutions());
						item.setIndividual(item.getIndividual() + curr.getIndividual());

						total.getYearData().put(year, item);

					} else {

						Item item = new Item();

						item.setYear(year);
						Item curr = itemEnt.getValue();

						item.setTotalCnt(curr.getTotalCnt());
						item.setHigherSchool(curr.getHigherSchool());
						item.setResearchInstitute(curr.getResearchInstitute());
						item.setEnterprise(curr.getEnterprise());
						item.setInstitutions(curr.getInstitutions());
						item.setIndividual(curr.getIndividual());

						total.getYearData().put(year, item);

					}
				}

			}

			areaList.add(0, total);
		}

		// 结果列表
		List<ViewStatisticsInfoVo> list = new ArrayList<ViewStatisticsInfoVo>();

		// 总的统计
		ViewStatisticsInfoVo allTypeList = new ViewStatisticsInfoVo();
//		list.add(allTypeList);
		allTypeList.setYearData(new LinkedHashMap<String, ViewStatisticsInfoVo.Item>());
		if (rzsViewStatisticsInfo.getCityCode() == null || "null".equals(rzsViewStatisticsInfo.getCityCode().trim())
				|| "".equals(rzsViewStatisticsInfo.getCityCode().trim())) {
			allTypeList.setAreaName("云南省");
		} else {
//			allTypeList.setAreaName(rzlViewStatisticsInfo.getCityName());
			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(rzsViewStatisticsInfo.getCityCode());
			if (bladeRegion != null) {
//				allTypeList.setAreaName(bladeRegion.getName());
				allTypeList.setAreaName(bladeRegion.getDistrictShortName());
			}

		}
		allTypeList.setPatentType("总计");

		// 处理统计
		for (Map.Entry<String, ViewStatisticsInfoVo> ent : typeTotalMap.entrySet()) {
			ViewStatisticsInfoVo vo = ent.getValue();

			list.add(vo);

			Map<String, Item> yearData = vo.getYearData();

			for (Map.Entry<String, Item> itemEnt : yearData.entrySet()) {
				String year = itemEnt.getKey();
				if (allTypeList.getYearData().containsKey(itemEnt.getKey())) {
					// 累加
					Item item = allTypeList.getYearData().get(itemEnt.getKey());
					Item curr = itemEnt.getValue();

					item.setTotalCnt(item.getTotalCnt() + curr.getTotalCnt());
					item.setHigherSchool(item.getHigherSchool() + curr.getHigherSchool());
					item.setResearchInstitute(item.getResearchInstitute() + curr.getResearchInstitute());
					item.setEnterprise(item.getEnterprise() + curr.getEnterprise());
					item.setInstitutions(item.getInstitutions() + curr.getInstitutions());
					item.setIndividual(item.getIndividual() + curr.getIndividual());

					allTypeList.getYearData().put(year, item);

				} else {

					Item item = new Item();

					item.setYear(year);
					Item curr = itemEnt.getValue();

					item.setTotalCnt(curr.getTotalCnt());
					item.setHigherSchool(curr.getHigherSchool());
					item.setResearchInstitute(curr.getResearchInstitute());
					item.setEnterprise(curr.getEnterprise());
					item.setInstitutions(curr.getInstitutions());
					item.setIndividual(curr.getIndividual());

					allTypeList.getYearData().put(year, item);

				}
			}

		}

		// 按专利类型排序
		Collections.sort(list, new ViewStatisticsInfoVo());
		
//		List<List<ViewStatisticsInfoVo>> list1 = new ArrayList<List<ViewStatisticsInfoVo>>();
		
//		// 按专利类型排序
		for (Map.Entry<String, List<ViewStatisticsInfoVo>> ent : areaMap.entrySet()) {
			List<ViewStatisticsInfoVo> areaList = ent.getValue();
			Collections.sort(areaList, new ViewStatisticsInfoVo());
		}
		
		
//		//处理非本区划
//		List<ViewStatisticsInfoVo>notThis=null;
//		for(Map.Entry<String, List<ViewStatisticsInfoVo>>ent:areaMap.entrySet()) {
//			String areaName=ent.getKey();
//			List<ViewStatisticsInfoVo>valList=ent.getValue();
//			if("非本区划".equals(areaName)) {
//				notThis=valList;
//			}else {
//				list1.add(valList);
//			}
//		}
				

		
		boolean has=false;
		// 排序
		for (String area : sortedKey(areaMap)) {
			if(!"非本区划".equals(area)) {
				list.addAll(areaMap.get(area));
			}else {
				has=true;
			}
		}
		
		for(ViewStatisticsInfoVo vo:list) {
			String areaCode=vo.getAreaName();
			if(StringUtils.isNotBlank(areaCode)) {
				BladeRegion br2=BladeRegionUtils.selectByCode(areaCode);
				if(br2!=null) {
					vo.setAreaName(br2.getDistrictShortName());
				}
			}
			
			
		}
		
		if(has) {
			list.addAll(areaMap.get("非本区划"));
		}
		
		if (!list.isEmpty()) {
			list.add(0, allTypeList);
		}
		List<String> yearList = new ArrayList<String>();
		// 确保返回列表中所有年份都有数据
		for (String year : yearSet) {
			for (ViewStatisticsInfoVo vo : list) {
				if (!vo.getYearData().containsKey(year)) {
					Item item = new Item();
					item.setYear(year);
					vo.getYearData().put(year, item);
				}
			}
			yearList.add(year);
		}

		Collections.sort(yearList, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				if (o1 == null && o2 == null) {
					return 0;
				} else {
					if (o1 == null) {
						return -1;
					} else if (o2 == null) {
						return 1;
					} else {
						return o1.compareTo(o2);
					}
				}
			}
		});

		rep.setDataList(list);
		rep.setYearList(yearList);
		return rep;

	}

//	class ComparatorPatentType implements Comparator<ViewStatisticsInfoVo>{
//
//		@Override
//		public int compare(ViewStatisticsInfoVo o1, ViewStatisticsInfoVo o2) {
//
//			// TODO Auto-generated method stub
//			if (o1 == null && o2 == null) {
//				return 0;
//			} else {
//				if (o1 == null) {
//					return -1;
//				} else if (o2 == null) {
//					return 1;
//				} else {
//					PatentType tp1 = PatentType.valueOfByName(o1.getPatentType());
//					PatentType tp2 = PatentType.valueOfByName(o2.getPatentType());
//					if (tp1 == null && tp2 == null) {
//						return 0;
//					} else if (tp1 == null) {
//						return -1;
//					} else if (tp2 == null) {
//						return 1;
//					} else {
//						return Integer.parseInt(tp1.getTypeId()) - Integer.parseInt(tp2.getTypeId());
//					}
//				}
//			}
//
//		
//		}
//
//		
//	}

	private List<String> sortedKey(Map<String, List<ViewStatisticsInfoVo>> areaMap) {
		List<String> list = new ArrayList<String>();
		if (areaMap == null) {
			return list;
		}
		list.addAll(areaMap.keySet());
		Collections.sort(list, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				// TODO Auto-generated method stub
				BladeRegion br1=BladeRegionUtils.selectByCode(o1);
				BladeRegion br2=BladeRegionUtils.selectByCode(o2);
				
				if(br1==null && br2==null) {
					return 0;
				}else if(br1==null) {
					return -1;
				}else if(br2==null) {
					return 1;
				}else {
					return br1.getSort()-br2.getSort();
				}
//				long total1 = ViewStatisticsInfoVo.getTotal(areaMap.get(o1));
//				long total2 = ViewStatisticsInfoVo.getTotal(areaMap.get(o2));
//				return (int)(total2 - total1);
			}

		});
		return list;

	}

	private String getStr(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return "";
		}
		return map.get(key).toString();
	}

	private int getInt(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return 0;
		}
		return Integer.parseInt(map.get(key).toString());
	}
	private long getLong(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return 0L;
		}
		return Long.parseLong(map.get(key).toString());
	}
	/**
	 * 查询专利授权-概况统计列表
	 *
	 * @param rzsViewStatisticsInfo 专利授权-概况统计
	 * @return 专利授权-概况统计集合
	 * @date 2023-03-27
	 */
	@Override
	public List<RzsViewStatisticsInfo> queryList(RzsViewStatisticsInfo rzsViewStatisticsInfo) {
		QueryWrapper<RzsViewStatisticsInfo> queryWrapper = Wrappers.query();
		if (StringUtils.isNotNull(rzsViewStatisticsInfo.getCityCode())) {
			queryWrapper.eq("city_code", rzsViewStatisticsInfo.getCityCode());
		}
		if (StringUtils.isNotEmpty(rzsViewStatisticsInfo.getCityName())) {
			queryWrapper.like("city_name", rzsViewStatisticsInfo.getCityName());
		}
		if (StringUtils.isNotEmpty(rzsViewStatisticsInfo.getYear())) {
			queryWrapper.eq("year", rzsViewStatisticsInfo.getYear());
		}
		if (StringUtils.isNotEmpty(rzsViewStatisticsInfo.getMonth())) {
			queryWrapper.eq("month", rzsViewStatisticsInfo.getMonth());
		}
		if (StringUtils.isNotEmpty(rzsViewStatisticsInfo.getPatentType())) {
			queryWrapper.eq("patent_type", rzsViewStatisticsInfo.getPatentType());
		}
//                if ( StringUtils.isNotEmpty(rzsViewStatisticsInfo.getHigherSchool())  ){
//                    queryWrapper.eq("higher_school", rzsViewStatisticsInfo.getHigherSchool());
//                }
//                if ( StringUtils.isNotEmpty(rzsViewStatisticsInfo.getResearchInstitute())  ){
//                    queryWrapper.eq("research_institute", rzsViewStatisticsInfo.getResearchInstitute());
//                }
//                if ( StringUtils.isNotEmpty(rzsViewStatisticsInfo.getEnterprise())  ){
//                    queryWrapper.eq("enterprise", rzsViewStatisticsInfo.getEnterprise());
//                }
//                if ( StringUtils.isNotEmpty(rzsViewStatisticsInfo.getInstitutions())  ){
//                    queryWrapper.eq("institutions", rzsViewStatisticsInfo.getInstitutions());
//                }
//                if ( StringUtils.isNotEmpty(rzsViewStatisticsInfo.getIndividual())  ){
//                    queryWrapper.eq("individual", rzsViewStatisticsInfo.getIndividual());
//                }
		if (StringUtils.isNotNull(rzsViewStatisticsInfo.getStatus())) {
			queryWrapper.eq("status", rzsViewStatisticsInfo.getStatus());
		}
		queryWrapper.orderByDesc("id");
		return this.list(queryWrapper);
	}


}
