package com.ruoyi.growthrate.service.impl;

import java.util.ArrayList;
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.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 com.google.gson.Gson;
import com.ruoyi.common.constant.ApplicantType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.growthrate.mapper.PatentGrowthrateMapper;
import com.ruoyi.growthrate.service.PatentGrowthrateService;
import com.ruoyi.growthrate.vo.PatentGrowthrateDTO;
import com.ruoyi.growthrate.vo.PatentGrowthrateQO;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.utils.BladeRegionUtils;

@Service
public class PatentGrowthrateServiceImpl implements PatentGrowthrateService {

	private static final Logger logger = LoggerFactory.getLogger(PatentGrowthrateServiceImpl.class);
	@Autowired
	private IBladeRegionService bladeRegionService;
	@Autowired
	private PatentGrowthrateMapper patentGrowthrateMapper;

	public static String[] hvs = new String[] { "total_cnt", "hv_seis_press", "hv_have_overseas_press",
			"hv_keep10_press", "hv_high_pledge_press", "hv_technology_award_press" };

	private void putDefaultHv(Map<String, String> map) {
		map.put("all_total_cnt", "0");
		for (String hv : hvs) {
			map.put(hv + "_total_cnt", "0");
			for (ApplicantType at : ApplicantType.getAll()) {
				map.put(hv + "_" + at.getTypeCode(), "0");
			}
		}
	}

	private void putDefaultHv2(Map<String, String> map) {
		map.put("all_total_cnt", "0");
		for (ApplicantType at : ApplicantType.getAll()) {
			for (String hv : hvs) {
				map.put(at.getTypeCode() + "_" + hv, "0");
			}
		}
	}

	private void dealHv(Map<String, Map<String, String>> resMap, List<Map> dataList, String cpContents) {
		if (cpContents.contains("1") && cpContents.contains("2")) {// [{'id':'1',name:'专利类型'},{'id':'2',name:'申请人类型'}],

			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				if (!resMap.containsKey(areaName)) {
					Map<String, String> itm = new LinkedHashMap<String, String>();
					resMap.put(areaName, itm);
					putDefaultHv(itm);
				}

				Map<String, String> alreadyMap = resMap.get(areaName);
				String patentType = getStr(map, "patent_type");
				if (StringUtils.isBlank(patentType)) {
					logger.warn("查到一条没有申请人类型的数据:" + new Gson().toJson(map));
					continue;
				}
				ApplicantType at = ApplicantType.getByName(patentType);
				if (at == null) {
//					logger.warn("查到一条没有申请人类型的数据:" + new Gson().toJson(map));
					continue;
				}
				String att = at.getTypeCode();
				for (String hv : hvs) {

					String key = hv + "_" + att;
					long v = getLong(map, hv);
					long v0 = Long.parseLong(alreadyMap.get(key));
					alreadyMap.put(key, (v + v0) + "");

//					long vt0=Long.parseLong(alreadyMap.get("all_total_cnt"));
//					alreadyMap.put("all_total_cnt", (v + vt0) + "");
//					
					long vtt0 = Long.parseLong(alreadyMap.get(hv + "_total_cnt"));
					alreadyMap.put(hv + "_total_cnt", (v + vtt0) + "");
				}
			}

			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				Map<String, String> alreadyMap = resMap.get(areaName);
				String patentType = getStr(map, "patent_type");
				if (StringUtils.isBlank(patentType)) {
					logger.warn("查到一条没有申请人类型的数据:" + new Gson().toJson(map));
					continue;
				}
				ApplicantType at = ApplicantType.getByName(patentType);
				if (at == null) {
//					logger.warn("查到一条没有申请人类型的数据:" + new Gson().toJson(map));
					continue;
				}
				for (String hv : hvs) {
					if ("total_cnt".equals(hv)) {
						continue;
					}
					long v = getLong(map, hv);
					long vt0 = Long.parseLong(alreadyMap.get("all_total_cnt"));
					alreadyMap.put("all_total_cnt", (v + vt0) + "");
//					System.out.println("开始累加,v:"+v+",key:"+hv+",vt0:"+vt0);
				}

			}
//			System.out.println("----------------------------");

		} else if (cpContents.contains("1")) {// [{'id':'1',name:'专利类型'},{'id':'2',name:'申请人类型'}],
			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				if (!resMap.containsKey(areaName)) {
					Map<String, String> itm = new LinkedHashMap<String, String>();
					resMap.put(areaName, itm);
					for (String hv : hvs) {
						itm.put(hv, "0");
					}

				}

				Map<String, String> alreadyMap = resMap.get(areaName);
				for (String hv : hvs) {
					long v = getLong(map, hv);
					long v0 = Long.parseLong(alreadyMap.get(hv));
					alreadyMap.put(hv, (v + v0) + "");
				}

			}
		} else if (cpContents.contains("2")) {

			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				if (!resMap.containsKey(areaName)) {
					Map<String, String> itm = new LinkedHashMap<String, String>();
					resMap.put(areaName, itm);
					putDefaultHv2(itm);
				}

				Map<String, String> alreadyMap = resMap.get(areaName);
				String patentType = getStr(map, "patent_type");
				if (StringUtils.isBlank(patentType)) {
					logger.warn("查到一条没有申请人类型的数据:" + new Gson().toJson(map));
					continue;
				}
				ApplicantType at = ApplicantType.getByName(patentType);
				if (at == null) {
//					logger.warn("查到一条没有申请人类型的数据:" + new Gson().toJson(map));
					continue;
				}

//				for(ApplicantType att:ApplicantType.getAll()){
				for (String hv : hvs) {
					String key = at.getTypeCode() + "_" + hv;
					long v = getLong(map, hv);
					long v0 = Long.parseLong(alreadyMap.get(key));
					long vv0 = Long.parseLong(alreadyMap.get("all_total_cnt"));
					alreadyMap.put(key, (v + v0) + "");
					if ("total_cnt".equals(hv)) {
						alreadyMap.put("all_total_cnt", (v + vv0) + "");
					}
				}
//				}

//				for(ApplicantType att:ApplicantType.getAll()){
//					for (String hv : hvs) {
//						String key =  att.getTypeCode()+ "_" + hv;
//						long v = getLong(map, hv);
//						long v0 = Long.parseLong(alreadyMap.get(key));
//						long vv0 = Long.parseLong(alreadyMap.get("all_total_cnt"));
//						alreadyMap.put(key, (v + v0) + "");
//						alreadyMap.put("all_total_cnt", (v + vv0) + "");
//					}
//				}

			}

		}
	}

	private void dealPatent(Map<String, Map<String, String>> resMap, List<Map> dataList, String cpContents) {
		// 有效数据

		if (cpContents.contains("1") && cpContents.contains("2")) {// [{'id':'1',name:'专利类型'},{'id':'2',name:'申请人类型'}],
//			List<Map> dataList = patentGrowthrateMapper.listForActAll(patentGrowthrateQO);

			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				if (!resMap.containsKey(areaName)) {
					Map<String, String> itm = new LinkedHashMap<String, String>();
					resMap.put(areaName, itm);
					itm.put("all_total_cnt", "0");
					itm.put("invention_total_cnt", "0");
					itm.put("invention_higher_school", "0");
					itm.put("invention_research_institute", "0");
					itm.put("invention_enterprise", "0");
					itm.put("invention_institutions", "0");
					itm.put("invention_individual", "0");

					itm.put("modelUtility_total_cnt", "0");
					itm.put("modelUtility_higher_school", "0");
					itm.put("modelUtility_research_institute", "0");
					itm.put("modelUtility_enterprise", "0");
					itm.put("modelUtility_institutions", "0");
					itm.put("modelUtility_individual", "0");

					itm.put("appearance_total_cnt", "0");
					itm.put("appearance_higher_school", "0");
					itm.put("appearance_research_institute", "0");
					itm.put("appearance_enterprise", "0");
					itm.put("appearance_institutions", "0");
					itm.put("appearance_individual", "0");
				}
				Map<String, String> alreadyMap = resMap.get(areaName);
				String patentType = getStr(map, "patent_type");
				String keyPrefix = "invention";
				if ("发明".equals(patentType)) {
					keyPrefix = "invention";
				} else if ("实用新型".equals(patentType)) {
					keyPrefix = "modelUtility";
				} else if ("外观设计".equals(patentType)) {
					keyPrefix = "appearance";
				} else {
					logger.warn("查到一条末知专利类型的数据:" + new Gson().toJson(map));
					continue;
				}

				long total_cnt = getLong(map, "total_cnt");
				long higher_school = getLong(map, "higher_school");
				long research_institute = getLong(map, "research_institute");
				long enterprise = getLong(map, "enterprise");
				long institutions = getLong(map, "institutions");
				long individual = getLong(map, "individual");

				long all_total_cnt0 = Long.parseLong(alreadyMap.get("all_total_cnt"));
				long total_cnt0 = Long.parseLong(alreadyMap.get(keyPrefix + "_total_cnt"));
				long higher_school0 = Long.parseLong(alreadyMap.get(keyPrefix + "_higher_school"));
				long research_institute0 = Long.parseLong(alreadyMap.get(keyPrefix + "_research_institute"));
				long enterprise0 = Long.parseLong(alreadyMap.get(keyPrefix + "_enterprise"));
				long institutions0 = Long.parseLong(alreadyMap.get(keyPrefix + "_institutions"));
				long individual0 = Long.parseLong(alreadyMap.get(keyPrefix + "_individual"));

				alreadyMap.put("all_total_cnt", (total_cnt + all_total_cnt0) + "");

				alreadyMap.put(keyPrefix + "_total_cnt", (total_cnt + total_cnt0) + "");
				alreadyMap.put(keyPrefix + "_higher_school", (higher_school + higher_school0) + "");
				alreadyMap.put(keyPrefix + "_research_institute", (research_institute + research_institute0) + "");
				alreadyMap.put(keyPrefix + "_enterprise", (enterprise + enterprise0) + "");
				alreadyMap.put(keyPrefix + "_institutions", (institutions + institutions0) + "");
				alreadyMap.put(keyPrefix + "_individual", (individual + individual0) + "");

			}

		} else if (cpContents.contains("1")) {// 'id':'1',name:'专利类型'
//			List<Map> dataList = patentGrowthrateMapper.listForActPatent(patentGrowthrateQO);
			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				if (!resMap.containsKey(areaName)) {
					Map<String, String> itm = new LinkedHashMap<String, String>();
					resMap.put(areaName, itm);
					itm.put("total_cnt", "0");
					itm.put("invention_cnt", "0");
					itm.put("modelUtility_cnt", "0");
					itm.put("appearance_cnt", "0");
				}
				long total_cnt = getLong(map, "total_cnt");
				long invention_cnt = getLong(map, "invention_cnt");
				long model_utility_cnt = getLong(map, "model_utility_cnt");
				long appearance_cnt = getLong(map, "appearance_cnt");

				Map<String, String> alreadyMap = resMap.get(areaName);

				long total_cnt0 = Long.parseLong(alreadyMap.get("total_cnt"));
				long invention_cnt0 = Long.parseLong(alreadyMap.get("invention_cnt"));
				long model_utility_cnt0 = Long.parseLong(alreadyMap.get("modelUtility_cnt"));
				long appearance_cnt0 = Long.parseLong(alreadyMap.get("appearance_cnt"));

				alreadyMap.put("total_cnt", (total_cnt0 + total_cnt) + "");
				alreadyMap.put("invention_cnt", (invention_cnt0 + invention_cnt) + "");
				alreadyMap.put("modelUtility_cnt", (model_utility_cnt0 + model_utility_cnt) + "");
				alreadyMap.put("appearance_cnt", (appearance_cnt0 + appearance_cnt) + "");

			}

		} else if (cpContents.contains("2")) {// 'id':'2',name:'申请人类型'
//			List<Map> dataList = patentGrowthrateMapper.listForActAppli(patentGrowthrateQO);

			for (Map map : dataList) {
				String areaName = getStr(map, "area_name");
				if (StringUtils.isBlank(areaName)) {
					logger.warn("查到一条没有地区的数据:" + new Gson().toJson(map));
					continue;
				}
				if (!resMap.containsKey(areaName)) {
					Map<String, String> itm = new LinkedHashMap<String, String>();
					resMap.put(areaName, itm);
					itm.put("total_cnt", "0");
					itm.put("higher_school", "0");
					itm.put("research_institute", "0");
					itm.put("enterprise", "0");
					itm.put("institutions", "0");
					itm.put("individual", "0");
				}
				long total_cnt = getLong(map, "total_cnt");
				long higher_school = getLong(map, "higher_school");
				long research_institute = getLong(map, "research_institute");
				long enterprise = getLong(map, "enterprise");
				long institutions = getLong(map, "institutions");
				long individual = getLong(map, "individual");

				Map<String, String> alreadyMap = resMap.get(areaName);

				long total_cnt0 = Long.parseLong(alreadyMap.get("total_cnt"));
				long higher_school0 = Long.parseLong(alreadyMap.get("higher_school"));
				long research_institute0 = Long.parseLong(alreadyMap.get("research_institute"));
				long enterprise0 = Long.parseLong(alreadyMap.get("enterprise"));
				long institutions0 = Long.parseLong(alreadyMap.get("institutions"));
				long individual0 = Long.parseLong(alreadyMap.get("individual"));

				alreadyMap.put("total_cnt", (total_cnt0 + total_cnt) + "");
				alreadyMap.put("higher_school", (higher_school0 + higher_school) + "");
				alreadyMap.put("research_institute", (research_institute0 + research_institute) + "");
				alreadyMap.put("enterprise", (enterprise0 + enterprise) + "");
				alreadyMap.put("institutions", (institutions0 + institutions) + "");
				alreadyMap.put("individual", (individual0 + individual) + "");

			}

		}

	}

	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;
	}

	// key:areaName,<datakey,count>
	private Map<String, Map<String, String>> countOne(PatentGrowthrateQO patentGrowthrateQO) {

		Map<String, Map<String, String>> resMap = new HashMap<String, Map<String, String>>();

		String cpData = patentGrowthrateQO.getCpData();
		String cpContents = patentGrowthrateQO.getCpContents();

		// 处理非本区划
		boolean needSumNotThisArea = false;
		if ("area".equals(patentGrowthrateQO.getSumType())) {
			needSumNotThisArea = true;

		}

		if ("act".equals(cpData)) {
			List<Map> dataList = null;
			if (cpContents.contains("1") && cpContents.contains("2")) {
				dataList = patentGrowthrateMapper.listForActAll(patentGrowthrateQO);

				List<Map> notThisAreaList = new ArrayList<Map>();
				Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
				if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
					BladeRegionUtils.setNotThisArea(dataList, null);
					List<Map> newList = new ArrayList<Map>();
//					List<String>allCodes=bladeRegionService.getAllAreaCode();
//					Map<String,Boolean>alreadyMap=new HashMap<String,Boolean>();
					for (Map map : dataList) {
						String area_code = getStr(map, "area_code");
						String city_code = getStr(map, "city_code");
//						if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
						if (isNotThisArea(map)) {
							// 合并到非本区化
							margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
									new String[] { "patent_type", "city_code" },
									new String[] { "total_cnt", "higher_school", "research_institute", "enterprise",
											"institutions", "individual" });
						} else {
							newList.add(map);// 不是非本区划
						}
					}
					dataList = newList;
					dataList.addAll(notThisAreaList);
				}

			} else if (cpContents.contains("1")) {
				dataList = patentGrowthrateMapper.listForActPatent(patentGrowthrateQO);

//				<if test="sumType == 'area'">modify_area_name area_name ,modify_area_code area_code,modify_city_code city_code</if>
//				,count(*) total_cnt
//				,sum(case when patent_type='发明' then 1 else 0 end ) invention_cnt
//				,sum(case when patent_type='实用新型' then 1 else 0 end ) model_utility_cnt 
//				,sum(case when patent_type='外观设计' then 1 else 0 end ) appearance_cnt
//				from d_patent_effective_info

				List<Map> notThisAreaList = new ArrayList<Map>();
				Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
				if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
					List<Map> newList = new ArrayList<Map>();
					BladeRegionUtils.setNotThisArea(dataList, null);
//					List<String> allCodes = bladeRegionService.getAllAreaCode();
//					Map<String, Boolean> alreadyMap = new HashMap<String, Boolean>();
					for (Map map : dataList) {
						String area_code = getStr(map, "area_code");
						String city_code = getStr(map, "city_code");
//						if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
						if (StringUtils.isNotBlank(city_code) && isNotThisArea(map)) {
							// 合并到非本区化
							margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
									new String[] { "city_code" }, new String[] { "total_cnt", "invention_cnt",
											"model_utility_cnt", "appearance_cnt" });
						} else {
							newList.add(map);// 不是非本区划
						}
					}
					dataList = newList;
					dataList.addAll(notThisAreaList);
				}

			} else if (cpContents.contains("2")) {// 'id':'2',name:'申请人类型'
				dataList = patentGrowthrateMapper.listForActAppli(patentGrowthrateQO);

				List<Map> notThisAreaList = new ArrayList<Map>();
				Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
				if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
					List<Map> newList = new ArrayList<Map>();
//					List<String> allCodes = bladeRegionService.getAllAreaCode();
					BladeRegionUtils.setNotThisArea(dataList, null);

					for (Map map : dataList) {
						String area_code = getStr(map, "area_code");
						String city_code = getStr(map, "city_code");
//						Map<String, Boolean> alreadyMap = new HashMap<String, Boolean>();
//						if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
						if (StringUtils.isNotBlank(city_code) && isNotThisArea(map)) {
							// 合并到非本区化
							margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
									new String[] { "city_code" }, new String[] { "total_cnt", "higher_school",
											"research_institute", "enterprise", "institutions", "individual" });
						} else {
							newList.add(map);// 不是非本区划
						}
					}
					dataList = newList;
					dataList.addAll(notThisAreaList);
				}

			} else {
				throw new RuntimeException("末知的数据对比类型" + cpContents);
			}

			dealPatent(resMap, dataList, cpContents);

		} else if ("auth".equals(cpData)) {

			List<Map> dataList = null;
			if (cpContents.contains("1") && cpContents.contains("2")) {
				dataList = patentGrowthrateMapper.listForAuthAll(patentGrowthrateQO);

				List<Map> notThisAreaList = new ArrayList<Map>();
				Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
				if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
					List<Map> newList = new ArrayList<Map>();
//					List<String> allCodes = bladeRegionService.getAllAreaCode();
					BladeRegionUtils.setNotThisArea(dataList, null);
//					Map<String, Boolean> alreadyMap = new HashMap<String, Boolean>();
					for (Map map : dataList) {
						String area_code = getStr(map, "area_code");
						String city_code = getStr(map, "city_code");
//						if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
						if (StringUtils.isNotBlank(city_code) && isNotThisArea(map)) {
							// 合并到非本区化
							margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
									new String[] { "city_code" }, new String[] { "total_cnt", "higher_school",
											"research_institute", "enterprise", "institutions", "individual" });
						} else {
							newList.add(map);// 不是非本区划
						}
					}
					dataList = newList;
					dataList.addAll(notThisAreaList);
				}

			} else if (cpContents.contains("1")) {
				dataList = patentGrowthrateMapper.listForAuthPatent(patentGrowthrateQO);

				List<Map> notThisAreaList = new ArrayList<Map>();
				Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
				if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
					List<Map> newList = new ArrayList<Map>();
//					List<String> allCodes = bladeRegionService.getAllAreaCode();
//					Map<String, Boolean> alreadyMap = new HashMap<String, Boolean>();
					BladeRegionUtils.setNotThisArea(dataList, null);
					for (Map map : dataList) {
						String area_code = getStr(map, "area_code");
						String city_code = getStr(map, "city_code");
//						if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
						if (StringUtils.isNotBlank(city_code) && isNotThisArea(map)) {
							// 合并到非本区化
							margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
									new String[] { "city_code" }, new String[] { "total_cnt", "invention_cnt",
											"model_utility_cnt", "appearance_cnt" });
						} else {
							newList.add(map);// 不是非本区划
						}
					}
					dataList = newList;
					dataList.addAll(notThisAreaList);
				}

			} else if (cpContents.contains("2")) {// 'id':'2',name:'申请人类型'
				dataList = patentGrowthrateMapper.listForAuthAppli(patentGrowthrateQO);

				List<Map> notThisAreaList = new ArrayList<Map>();
				Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
				if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
					List<Map> newList = new ArrayList<Map>();
					BladeRegionUtils.setNotThisArea(dataList, null);
//					List<String> allCodes = bladeRegionService.getAllAreaCode();
//					Map<String, Boolean> alreadyMap = new HashMap<String, Boolean>();
					for (Map map : dataList) {
						String area_code = getStr(map, "area_code");
						String city_code = getStr(map, "city_code");
//						if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
						if (StringUtils.isNotBlank(city_code) && isNotThisArea(map)) {
							// 合并到非本区化
							margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
									new String[] { "city_code" }, new String[] { "total_cnt", "higher_school",
											"research_institute", "enterprise", "institutions", "individual" });
						} else {
							newList.add(map);// 不是非本区划
						}
					}
					dataList = newList;
					dataList.addAll(notThisAreaList);
				}

			} else {
				throw new RuntimeException("末知的数据对比类型" + cpContents);
			}
			dealPatent(resMap, dataList, cpContents);

		} else if ("hv".equals(cpData)) {// 高价值数据统计
			List<Map> dataList = patentGrowthrateMapper.listForHv(patentGrowthrateQO);
//			System.out.println("数据库查询结果:"+new Gson().toJson(dataList));

			List<Map> notThisAreaList = new ArrayList<Map>();
			Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
			if (needSumNotThisArea && dataList != null && !dataList.isEmpty()) {
				List<Map> newList = new ArrayList<Map>();
//				List<String> allCodes = bladeRegionService.getAllAreaCode();
//				Map<String, Boolean> alreadyMap = new HashMap<String, Boolean>();
				BladeRegionUtils.setNotThisArea(dataList, null);
				for (Map map : dataList) {
					String area_code = getStr(map, "area_code");
					String city_code = getStr(map, "city_code");
//					if (StringUtils.isNotBlank(city_code) && (StringUtils.isBlank(area_code) || !area_code.startsWith(city_code))) {
					if (StringUtils.isNotBlank(city_code) && isNotThisArea(map)) {
						// 合并到非本区化
						margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name",
								new String[] { "city_code" },
								new String[] { "total_cnt", "hv_seis_press", "hv_have_overseas_press",
										"hv_keep10_press", "hv_high_pledge_press", "hv_technology_award_press" });
					} else {
						newList.add(map);// 不是非本区划
					}
				}
				dataList = newList;
				dataList.addAll(notThisAreaList);
			}

			dealHv(resMap, dataList, cpContents);
//			System.out.println("统计结果:"+new Gson().toJson(resMap));
		}

		return resMap;
	}

	private List<PatentGrowthrateDTO> doCountGrowth(PatentGrowthrateQO patentGrowthrateQO) {

		if (StringUtils.isBlank(patentGrowthrateQO.getCpData())) {
			patentGrowthrateQO.setCpData("act");
		}
		if (StringUtils.isBlank(patentGrowthrateQO.getCpContents())) {
			patentGrowthrateQO.setCpContents("1,2");// [{'id':'1',name:'专利类型'},{'id':'2',name:'申请人类型'}],
		}

		String beginTime1 = patentGrowthrateQO.getBeginTime1();
		if (StringUtils.isBlank(beginTime1)) {
			beginTime1 = "202212";
		}
		String endTime1 = patentGrowthrateQO.getEndTime1();
		if (StringUtils.isBlank(endTime1)) {
			endTime1 = "202212";
		}

		String beginTime2 = patentGrowthrateQO.getBeginTime2();
		if (StringUtils.isBlank(beginTime2)) {
			beginTime2 = "202212";
		}

		String endTime2 = patentGrowthrateQO.getEndTime2();
		if (StringUtils.isBlank(endTime2)) {
			endTime2 = "202212";
		}

		String beginTime = beginTime1;
		String endTime = endTime1;
		patentGrowthrateQO.setBeginTime(beginTime);
		patentGrowthrateQO.setEndTime(endTime);
		Map<String, Map<String, String>> map1 = countOne(patentGrowthrateQO);

		beginTime = beginTime2;
		endTime = endTime2;
		patentGrowthrateQO.setBeginTime(beginTime);
		patentGrowthrateQO.setEndTime(endTime);
		Map<String, Map<String, String>> map2 = countOne(patentGrowthrateQO);

		Set<String> areaSet = new HashSet<String>();
		areaSet.addAll(map1.keySet());
		areaSet.addAll(map2.keySet());

		for (String areaName : areaSet) {
			if (!map1.containsKey(areaName) && !map2.containsKey(areaName)) {
				continue;// 这种情况不可能出现
			}
			if (!map1.containsKey(areaName) && map2.containsKey(areaName)) {
				Map<String, String> vo2 = map2.get(areaName);
				Map<String, String> vo1 = getDefault(vo2);
				map1.put(areaName, vo1);
			}
			if (!map2.containsKey(areaName) && map1.containsKey(areaName)) {
				Map<String, String> vo1 = map1.get(areaName);
				Map<String, String> vo2 = getDefault(vo1);
				map2.put(areaName, vo2);
			}
		}

		List<PatentGrowthrateDTO> notThis = new ArrayList<PatentGrowthrateDTO>();

		List<PatentGrowthrateDTO> list = new ArrayList<PatentGrowthrateDTO>();
		for (String areaName : areaSet) {
			PatentGrowthrateDTO dto = new PatentGrowthrateDTO();
			dto.setAreaName(areaName);
			Map<String, String> vo1 = map1.get(areaName);
			Map<String, String> vo2 = map2.get(areaName);
			Map<String, String> vog = countGrowth(vo1, vo2);

			String timeReg1 = timeDiplay(beginTime1) + " 至 " + timeDiplay(endTime1);
			vo1.put("timeReg", timeReg1);

			String timeReg2 = timeDiplay(beginTime2) + " 至 " + timeDiplay(endTime2);
			vo2.put("timeReg", timeReg2);

			vog.put("timeReg", "同比增长");
			dto.setItem1(vo1);
			dto.setItem2(vo2);
			dto.setGrowth(vog);

			if ("非本区划".equals(areaName)) {
				notThis.add(dto);
			} else {
				list.add(dto);
			}

		}

		list.addAll(notThis);// 非本区划的加到最后

		return list;
	}

	private String timeDiplay(String time) {
		return time.substring(0, 4) + "年" + time.substring(4, 6) + "月";
	}

	public List<PatentGrowthrateDTO> countGrowth(PatentGrowthrateQO patentGrowthrateQO) {

		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(patentGrowthrateQO.getAppliCity()) && !"53".equals(patentGrowthrateQO.getAppliCity())) {
			String cityCode = patentGrowthrateQO.getAppliCity().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				patentGrowthrateQO.setAppliCity(cityCode);
			}
		}
		
		List<PatentGrowthrateDTO> list = new ArrayList<PatentGrowthrateDTO>();

		String sumType = "province";
		if (StringUtils.isBlank(patentGrowthrateQO.getProvince())
				|| StringUtils.isBlank(patentGrowthrateQO.getAppliCity())
				|| "null".equals(patentGrowthrateQO.getAppliCity())) {
			sumType = "province";
		} else if (StringUtils.isNotBlank(patentGrowthrateQO.getAppliCity())
				&& "all".equals(patentGrowthrateQO.getAppliCity())) {
			sumType = "city";
		} else if (StringUtils.isNotBlank(patentGrowthrateQO.getAppliCity())
				&& !"all".equals(patentGrowthrateQO.getAppliCity())
				&& !"null".equals(patentGrowthrateQO.getAppliCity())) {
			sumType = "city";
			if (StringUtils.isNotBlank(patentGrowthrateQO.getAppliCounty())
					&& "null".equals(patentGrowthrateQO.getAppliCounty())) {
				sumType = "city";
			} else if (StringUtils.isNotBlank(patentGrowthrateQO.getAppliCounty())
					&& "all".equals(patentGrowthrateQO.getAppliCounty())) {
				sumType = "area";
			}
		}
		patentGrowthrateQO.setSumType(sumType);

		if ("province".equals(sumType)) {
			list.addAll(doCountGrowth(patentGrowthrateQO));
		} else if ("city".equals(sumType)) {
			patentGrowthrateQO.setSumType("province");
			list.addAll(doCountGrowth(patentGrowthrateQO));

			patentGrowthrateQO.setSumType("city");
			list.addAll(doCountGrowth(patentGrowthrateQO));

		} else if ("area".equals(sumType)) {
			patentGrowthrateQO.setSumType("province");
			list.addAll(doCountGrowth(patentGrowthrateQO));

			patentGrowthrateQO.setSumType("city");
			list.addAll(doCountGrowth(patentGrowthrateQO));

			patentGrowthrateQO.setSumType("area");
			list.addAll(doCountGrowth(patentGrowthrateQO));

		}

		return list;

	}

	private Map<String, String> getDefault(Map<String, String> src) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		for (String key : src.keySet()) {
			map.put(key, "0");
		}
		return map;
	}

	private Map<String, String> countGrowth(Map<String, String> map1, Map<String, String> map2) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		for (Map.Entry<String, String> ent1 : map1.entrySet()) {
			String key = ent1.getKey();
			long value1 = Long.parseLong(ent1.getValue());

			long value2 = 0;
			if (map2.containsKey(key)) {
				value2 = Long.parseLong(map2.get(key));
			}

			String growthStr = "--";
			double growth = 0.0;
			if (value1 > 0) {
				growth = (value2 - value1 + 0.0) / value1 * 100;
			}
			growthStr = String.format("%.2f", growth) + "%";

			map.put(key, growthStr);
		}
		return map;
	}

	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 0;
		}
		return Long.parseLong(map.get(key).toString());
	}

}
