package com.ruoyi.hv.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

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.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dimp.domain.DPopulationDataInfo;
import com.ruoyi.dimp.service.IDPopulationDataInfoService;
import com.ruoyi.hv.domain.RzgHighValuePatentInfo;
import com.ruoyi.hv.mapper.RzgHighValueIewStatisticsInfoMapper;
import com.ruoyi.hv.mapper.RzgHighValuePatentInfoMapper;
import com.ruoyi.hv.service.IRzgHighValuePatentInfoService;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.utils.BladeRegionUtils;

/**
 * 高价值专利-万人高价值专利统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-02
 */
@Service
public class RzgHighValuePatentInfoServiceImpl extends ServiceImpl<RzgHighValuePatentInfoMapper, RzgHighValuePatentInfo>
		implements IRzgHighValuePatentInfoService {

	@Autowired
	private RzgHighValueIewStatisticsInfoMapper rzgHighValueIewStatisticsInfoMapper;
	@Autowired
	private IBladeRegionService bladeRegionService;
	@Autowired
	private IDPopulationDataInfoService dPopulationDataInfoService;

	public List<RzgHighValuePatentInfo> getOneYear(RzgHighValuePatentInfo rzgHighValueIewStatisticsInfo, String year) {
		rzgHighValueIewStatisticsInfo.setYear(year);
		rzgHighValueIewStatisticsInfo.setStatus(10L);// 只查有效的
		List<Map> mapList = rzgHighValueIewStatisticsInfoMapper.listByReport2(rzgHighValueIewStatisticsInfo);

		List<RzgHighValuePatentInfo> list = new ArrayList<RzgHighValuePatentInfo>();

		for (Map map : mapList) {
			RzgHighValuePatentInfo vo = new RzgHighValuePatentInfo();
			list.add(vo);
			vo.setYear(getStr(map, "year_batch"));
			String areaCode = getStr(map, "area_code");
			if (StringUtils.isNotBlank(areaCode)) {
				String areaName = BladeRegionUtils.getDistrictShortName(areaCode);
				vo.setAreaName(areaName);
				vo.setCityName(areaName);
			}

//			vo.setCityName(getStr(map, "area_name"));
			vo.setCityCode(getStr(map, "area_code"));
//			vo.setAreaName(getStr(map, "area_name"));
			vo.setAreaCode(getStr(map, "area_code"));
			vo.setIndustryEmergIndustry(getLong(map, "seis"));// 战略性新兴产业
			vo.setOverseasCongenerPatent(getLong(map, "have_overseas"));// 在海外有同族专利
			vo.setMaintenanceTenYear(getLong(map, "keep_10_years"));// 维持年限超十年
			vo.setPledgeRecord(getLong(map, "high_pledge"));// 存在质押记录
			vo.setNationalScienceAward(getLong(map, "technology_award"));// 获得国家科技奖或者中国专利奖

			vo.setEffectiveTotal(getLong(map, "seis") + getInt(map, "have_overseas") + getInt(map, "keep_10_years") + getInt(map, "high_pledge")
					+ getInt(map, "technology_award"));// 高价值发明专利有效量合计
			vo.setGrowth("-");
		}

		// 统计人口信息
		for (RzgHighValuePatentInfo data : list) {
			data.setGrowth("-");
			data.setYearPopulation(0 + "");
			if (StringUtils.isBlank(data.getCityCode())) {
//				TODO	
				BladeRegion bladeRegion = bladeRegionService.selectByCityName(data.getCityName(), "53");
				if (bladeRegion != null) {
					data.setCityCode(bladeRegion.getCityCode());
				}
			}

			DPopulationDataInfo popu = dPopulationDataInfoService.queryPoupation(data.getYear(), data.getCityCode());
			if (popu != null && StringUtils.isNotBlank(popu.getPopulationTotal())) {
				data.setYearPopulation(popu.getPopulationTotal());
				Double popuDouble = Double.parseDouble(popu.getPopulationTotal());
				if (data.getEffectiveTotal() > 0 && popuDouble > 0) {
					Double hvPatentThousandsDouble = data.getEffectiveTotal() / popuDouble;
					String hvPatentThousands = String.format("%.4f", hvPatentThousandsDouble);
					data.setHvPatentThousands(hvPatentThousands);
				} else {
					data.setHvPatentThousands("0");
				}

			}
		}

		// 自定义
//		List<RzgHighValuePatentInfo> currList2= new ArrayList<RzgHighValuePatentInfo>();
//		Map<String,RzgHighValuePatentInfo>map=new HashMap<String,RzgHighValuePatentInfo>();
//		for(RzgHighValuePatentInfo vo:list) {
//			map.put(vo.getAreaCode(), vo);
//		}
//		List<String>keys=BladeRegionUtils.sortedKey(map.keySet());
//		for(String key:keys) {
//			currList2.add(map.get(key));
//			
//			String areaName=BladeRegionUtils.getDistrictShortName(key);
//			if(areaName!=null) {
//				map.get(key).setAreaName(areaName);
//			}
//			
//		}

//		for(RzgHighValuePatentInfo currData:list) {
//			if(StringUtils.isNotBlank(currData.getAreaCode())) {
//				String areaName=BladeRegionUtils.getDistrictShortName(currData.getAreaCode());
//				currData.setAreaName(areaName);
//			}
//			
//			if(StringUtils.isNotBlank(currData.getCityCode())) {
//				String areaName=BladeRegionUtils.getDistrictShortName(currData.getCityCode());
//				currData.setCityName(areaName);
//			}
//		}
		return list;
//		return currList2;
	}

	@Override
	public List<RzgHighValuePatentInfo> listByReport(RzgHighValuePatentInfo rzgHighValueIewStatisticsInfo) {

		boolean retEmpty = false;
		if (StringUtils.isNotBlank(rzgHighValueIewStatisticsInfo.getCityCode()) && !"53".equals(rzgHighValueIewStatisticsInfo.getCityCode())) {
			String cityCode = rzgHighValueIewStatisticsInfo.getCityCode().trim();
			if (SecurityUtils.isNeedFilterByCityCode()) {
				String cc = SecurityUtils.needFilterByCityCode();
				if (!cc.equals(cityCode)) {
					retEmpty = true;
				}
			}
		} else {
			if (SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode = SecurityUtils.needFilterByCityCode();
				rzgHighValueIewStatisticsInfo.setCityCode(cityCode);
			}
		}
		
		if(retEmpty) {
			return new ArrayList<RzgHighValuePatentInfo>();
		}

		// 当年
		String currYear = rzgHighValueIewStatisticsInfo.getYear();

		// 往年
		String lastYear = (Integer.parseInt(currYear) - 1) + "";

		// 高价值信息
		List<RzgHighValuePatentInfo> currList = getOneYear(rzgHighValueIewStatisticsInfo, currYear);
		List<RzgHighValuePatentInfo> lastList = getOneYear(rzgHighValueIewStatisticsInfo, lastYear);

		rzgHighValueIewStatisticsInfo.setYear(currYear);

		// 统计增长率
		for (RzgHighValuePatentInfo currData : currList) {
			RzgHighValuePatentInfo lastData = getLast(lastList, currData.getCityName());
			if (lastData != null) {
				currData.setLastData(lastData);
				if (StringUtils.isBlank(currData.getHvPatentThousands())) {
					currData.setHvPatentThousands("0");
				}
				if (StringUtils.isBlank(lastData.getHvPatentThousands())) {
					lastData.setHvPatentThousands("0");
				}
				Double curr = Double.parseDouble(currData.getHvPatentThousands());
				Double last = Double.parseDouble(lastData.getHvPatentThousands());
				if (last > 0) {
					Double growThDouble = (curr - last) / last * 100;
					String growTh = String.format("%.2f", growThDouble);
					currData.setGrowth(growTh);
				}

			}

		}

		// 排序
		Collections.sort(currList, new Comparator<RzgHighValuePatentInfo>() {

			@Override
			public int compare(RzgHighValuePatentInfo o1, RzgHighValuePatentInfo 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 {
						o1.getHvPatentThousands();
						o2.getHvPatentThousands();
						if (StringUtils.isBlank(o1.getHvPatentThousands()) && StringUtils.isBlank(o2.getHvPatentThousands())) {
							return 0;
						} else {
							if (StringUtils.isBlank(o1.getHvPatentThousands())) {
								return -1;
							} else if (StringUtils.isBlank(o2.getHvPatentThousands())) {
								return 1;
							} else {
								Double hv1 = Double.parseDouble(o1.getHvPatentThousands());
								Double hv2 = Double.parseDouble(o2.getHvPatentThousands());
								return hv2.compareTo(hv1);
							}

						}

					}
				}
			}

		});
		for (int i = 1; i <= currList.size(); i++) {
			currList.get(i - 1).setRanking(i);
		}
		String areaCode = "53";
		String areaName = "云南省";
		if (rzgHighValueIewStatisticsInfo.getCityCode() == null || "null".equals(rzgHighValueIewStatisticsInfo.getCityCode().trim())
				|| "".equals(rzgHighValueIewStatisticsInfo.getCityCode().trim()) || "53".equals(rzgHighValueIewStatisticsInfo.getCityCode().trim())) {
			areaName = "云南省";
			areaCode = "53";
		} else {
			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(rzgHighValueIewStatisticsInfo.getCityCode().trim());
			if (bladeRegion != null) {
				areaName = bladeRegion.getDistrictShortName();
			}
			areaCode = rzgHighValueIewStatisticsInfo.getCityCode().trim();
		}

		// 创建汇总行
		RzgHighValuePatentInfo sum = new RzgHighValuePatentInfo();
		sum.setCityName(areaName);
		sum.setCityCode(areaCode);
		sum.setAreaName(areaName);
		sum.setAreaCode(areaCode);
		sum.setIndustryEmergIndustry(0L);// 战略性新兴产业
		sum.setOverseasCongenerPatent(0L);// 在海外有同族专利
		sum.setMaintenanceTenYear(0L);// 维持年限超十年
		sum.setPledgeRecord(0L);// 存在质押记录
		sum.setNationalScienceAward(0L);// 获得国家科技奖或者中国专利奖
		sum.setEffectiveTotal(0L);// 有效合计

		RzgHighValuePatentInfo lastSum = new RzgHighValuePatentInfo();
		lastSum.setCityName(areaName);
		lastSum.setIndustryEmergIndustry(0L);// 战略性新兴产业
		lastSum.setOverseasCongenerPatent(0L);// 在海外有同族专利
		lastSum.setMaintenanceTenYear(0L);// 维持年限超十年
		lastSum.setPledgeRecord(0L);// 存在质押记录
		lastSum.setNationalScienceAward(0L);// 获得国家科技奖或者中国专利奖
		lastSum.setEffectiveTotal(0L);// 有效合计
		sum.setLastData(lastSum);

		for (int i = 1; i <= currList.size(); i++) {
			RzgHighValuePatentInfo vo = currList.get(i - 1);
			if (vo.getIndustryEmergIndustry() != null) {
				sum.setIndustryEmergIndustry(sum.getIndustryEmergIndustry() + vo.getIndustryEmergIndustry());
			}
			if (vo.getOverseasCongenerPatent() != null) {
				sum.setOverseasCongenerPatent(sum.getOverseasCongenerPatent() + vo.getOverseasCongenerPatent());
			}
			if (vo.getMaintenanceTenYear() != null) {
				sum.setMaintenanceTenYear(sum.getMaintenanceTenYear() + vo.getMaintenanceTenYear());
			}
			if (vo.getPledgeRecord() != null) {
				sum.setPledgeRecord(sum.getPledgeRecord() + vo.getPledgeRecord());
			}
			if (vo.getNationalScienceAward() != null) {
				sum.setNationalScienceAward(sum.getNationalScienceAward() + vo.getNationalScienceAward());
			}
			if (vo.getEffectiveTotal() != null) {
				sum.setEffectiveTotal(sum.getEffectiveTotal() + vo.getEffectiveTotal());
			}

			if (vo.getLastData() != null && vo.getLastData().getEffectiveTotal() != null) {
				lastSum.setEffectiveTotal(lastSum.getEffectiveTotal() + vo.getLastData().getEffectiveTotal());
			}

		}

		DPopulationDataInfo popu = dPopulationDataInfoService.queryPoupation(currYear, "53");
		if (popu != null && StringUtils.isNotBlank(popu.getPopulationTotal())) {
			sum.setYearPopulation(popu.getPopulationTotal());
			Double popuDouble = Double.parseDouble(popu.getPopulationTotal());
			if (sum.getEffectiveTotal() > 0 && popuDouble > 0) {
				Double hvPatentThousandsDouble = sum.getEffectiveTotal() / popuDouble;
				String hvPatentThousands = String.format("%.4f", hvPatentThousandsDouble);
				sum.setHvPatentThousands(hvPatentThousands);
			} else {
				sum.setHvPatentThousands("0");
			}

		} else {
			sum.setHvPatentThousands("0");
		}

//		DPopulationDataInfo lastPopu = dPopulationDataInfoService.queryPoupation(currYear,"53");
		DPopulationDataInfo lastPopu = dPopulationDataInfoService.queryPoupation(lastYear, "53");
		if (lastPopu != null && StringUtils.isNotBlank(lastPopu.getPopulationTotal())) {
			lastSum.setYearPopulation(lastPopu.getPopulationTotal());
			Double popuDouble = Double.parseDouble(lastPopu.getPopulationTotal());
			if (lastSum.getEffectiveTotal() > 0 && popuDouble > 0) {
				Double hvPatentThousandsDouble = lastSum.getEffectiveTotal() / popuDouble;
				String hvPatentThousands = String.format("%.4f", hvPatentThousandsDouble);
				lastSum.setHvPatentThousands(hvPatentThousands);
			} else {
				lastSum.setHvPatentThousands("0");
			}

		} else {
			lastSum.setHvPatentThousands("0");
		}

		Double curr = Double.parseDouble(sum.getHvPatentThousands());
		Double last = Double.parseDouble(lastSum.getHvPatentThousands());
		if (last > 0) {
			Double growThDouble = (curr - last) / last * 100;
			String growTh = String.format("%.2f", growThDouble);
			sum.setGrowth(growTh);
		}

		currList.add(sum);

//		return currList2;
		return currList;
	}

	private RzgHighValuePatentInfo getLast(List<RzgHighValuePatentInfo> lastList, String areaName) {
		if(areaName==null) {
			return null;
		}
		for (RzgHighValuePatentInfo last : lastList) {
			if (areaName.equals(last.getCityName())) {
				return last;
			}
		}
		return null;
	}

	public List<RzgHighValuePatentInfo> listByReport_bak(RzgHighValuePatentInfo rzgHighValueIewStatisticsInfo) {

		List<Map> mapList = rzgHighValueIewStatisticsInfoMapper.listByReport2(rzgHighValueIewStatisticsInfo);
		List<RzgHighValuePatentInfo> list = new ArrayList<RzgHighValuePatentInfo>();

		for (Map map : mapList) {
			RzgHighValuePatentInfo vo = new RzgHighValuePatentInfo();
			list.add(vo);
			vo.setYear(getStr(map, "year_batch"));
			vo.setMonth(getStr(map, "month_batch"));
			vo.setCityName(getStr(map, "area_name"));
			vo.setIndustryEmergIndustry(getLong(map, "seis"));// 战略性新兴产业
			vo.setOverseasCongenerPatent(getLong(map, "have_overseas"));// 在海外有同族专利
			vo.setMaintenanceTenYear(getLong(map, "keep_10_years"));// 维持年限超十年
			vo.setPledgeRecord(getLong(map, "high_pledge"));// 存在质押记录
			vo.setNationalScienceAward(getLong(map, "technology_award"));// 获得国家科技奖或者中国专利奖
			vo.setEffectiveTotal(getLong(map, "total_cnt"));// 高价值发明专利有效量合计
		}

		return list;
	}

	private String getStr(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return "";
		}
		return 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());
	}

	private int getInt(Map map, String key) {
		if (map == null || key == null || !map.containsKey(key)) {
			return 0;
		}
		return Integer.parseInt(map.get(key).toString());
	}

	/**
	 * 查询高价值专利-万人高价值专利统计列表
	 *
	 * @param rzgHighValuePatentInfo 高价值专利-万人高价值专利统计
	 * @return 高价值专利-万人高价值专利统计集合
	 * @date 2023-04-02
	 */
	@Override
	public List<RzgHighValuePatentInfo> queryList(RzgHighValuePatentInfo rzgHighValuePatentInfo) {
		QueryWrapper<RzgHighValuePatentInfo> queryWrapper = Wrappers.query();
		if (StringUtils.isNotNull(rzgHighValuePatentInfo.getCityCode())) {
			queryWrapper.eq("city_code", rzgHighValuePatentInfo.getCityCode());
		}
		if (StringUtils.isNotEmpty(rzgHighValuePatentInfo.getCityName())) {
			queryWrapper.like("city_name", rzgHighValuePatentInfo.getCityName());
		}
		if (StringUtils.isNotEmpty(rzgHighValuePatentInfo.getYear())) {
			queryWrapper.eq("year", rzgHighValuePatentInfo.getYear());
		}
		if (StringUtils.isNotEmpty(rzgHighValuePatentInfo.getMonth())) {
			queryWrapper.eq("month", rzgHighValuePatentInfo.getMonth());
		}
		if (StringUtils.isNotEmpty(rzgHighValuePatentInfo.getSort())) {
			queryWrapper.eq("sort", rzgHighValuePatentInfo.getSort());
		}
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getIndustryEmergIndustry())  ){
//                    queryWrapper.eq("industry_emerg_industry", rzgHighValuePatentInfo.getIndustryEmergIndustry());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getOverseasCongenerPatent())  ){
//                    queryWrapper.eq("overseas_congener_patent", rzgHighValuePatentInfo.getOverseasCongenerPatent());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getMaintenanceTenYear())  ){
//                    queryWrapper.eq("maintenance_ten_year", rzgHighValuePatentInfo.getMaintenanceTenYear());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getPledgeRecord())  ){
//                    queryWrapper.eq("pledge_record", rzgHighValuePatentInfo.getPledgeRecord());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getNationalScienceAward())  ){
//                    queryWrapper.eq("national_science_award", rzgHighValuePatentInfo.getNationalScienceAward());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getEffectiveTotal())  ){
//                    queryWrapper.eq("effective_total", rzgHighValuePatentInfo.getEffectiveTotal());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getYearPopulation())  ){
//                    queryWrapper.eq("year_population", rzgHighValuePatentInfo.getYearPopulation());
//                }
//                if ( StringUtils.isNotEmpty(rzgHighValuePatentInfo.getHighValuePatentOwner())  ){
//                    queryWrapper.eq("high_value_patent_owner", rzgHighValuePatentInfo.getHighValuePatentOwner());
//                }
		if (StringUtils.isNotEmpty(rzgHighValuePatentInfo.getGrowth())) {
			queryWrapper.eq("growth", rzgHighValuePatentInfo.getGrowth());
		}
		if (StringUtils.isNotNull(rzgHighValuePatentInfo.getStatus())) {
			queryWrapper.eq("status", rzgHighValuePatentInfo.getStatus());
		}
		queryWrapper.orderByDesc("effective_total");
		return this.list(queryWrapper);
	}
}
