package com.ruoyi.indica.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONUtils;
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.google.gson.Gson;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.indica.domain.CIndicationInfo;
import com.ruoyi.indica.mapper.CIndicationInfoMapper;
import com.ruoyi.indica.service.ICIndicationInfoService;
import com.ruoyi.indica.vo.CIndicationInfoDTO;
import com.ruoyi.indica.vo.CIndicationInfoVO;
import com.ruoyi.report.vo.CIndicationLastSumDTO;
import com.ruoyi.report.vo.CIndicationSumItem;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.utils.BladeRegionUtils;

import cn.hutool.core.bean.BeanUtil;

/**
 * 地理标志Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-28
 */
@Service
public class CIndicationInfoServiceImpl extends ServiceImpl<CIndicationInfoMapper, CIndicationInfo> implements ICIndicationInfoService {
	private static final Logger logger = LoggerFactory.getLogger(CIndicationInfoServiceImpl.class);

	@Autowired
	private RuoYiConfig ruoYiConfig;
	@Autowired
	private IBladeRegionService bladeRegionService;
	@Autowired
	private CIndicationInfoMapper cIndicationInfoMapper;
	@Autowired
	private RedisCache redisCache;
	@Autowired
	private ISysConfigService sysConfigService;

	public CIndicationLastSumDTO listForLast() {

		CIndicationLastSumDTO dto = new CIndicationLastSumDTO();
		String lastTimeKey = "indication_last_time";
		String lastTime = sysConfigService.selectConfigByKey(lastTimeKey);
		if (StringUtils.isNotBlank(lastTime)) {
			dto.setLastTime(lastTime);
		}

		CIndicationSumItem totalItem = new CIndicationSumItem();
		totalItem.setAreaCode("53");
		totalItem.setAreaName("云南省");
		totalItem.setAreaShortName("云南省");
		totalItem.setTotalCnt1(0L);
		totalItem.setTotalCnt2(0L);
		totalItem.setTotalCnt3(0L);
		Set<String> citySet = new HashSet<String>();
		List<CIndicationSumItem> itemList = new ArrayList<CIndicationSumItem>();

		List<Map> dataList = cIndicationInfoMapper.listForLast();
//		total_cnt,modify_city,modify_city_code
		for (Map map : dataList) {
			CIndicationSumItem item = new CIndicationSumItem();
			itemList.add(item);
			item.setTotalCnt1(getLong(map, "total_cnt1"));
			item.setTotalCnt2(getLong(map, "total_cnt2"));
			item.setTotalCnt3(getLong(map, "total_cnt3"));
			item.setAreaName(getStr(map, "modify_city"));
			item.setAreaCode(getStr(map, "modify_city_code"));

			totalItem.setTotalCnt1(totalItem.getTotalCnt1() + item.getTotalCnt1());
			totalItem.setTotalCnt2(totalItem.getTotalCnt2() + item.getTotalCnt2());
			totalItem.setTotalCnt3(totalItem.getTotalCnt3() + item.getTotalCnt3());

			citySet.add(item.getAreaCode());

			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(item.getAreaCode());
			if (bladeRegion != null) {
				if (bladeRegion.getCityName().equals(item.getAreaName())) {
					if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
						item.setAreaShortName(bladeRegion.getCityShortName());
					}

				} else {
					logger.warn("数据错误，城市名称与城市代码不匹配,city:" + item.getAreaName() + ",code:" + item.getAreaCode());
				}
			}
		}

		List<BladeRegion> cityList = bladeRegionService.selectAllCityList();
		for (BladeRegion br : cityList) {
			if (!citySet.contains(br.getCityCode())) {
				CIndicationSumItem item = new CIndicationSumItem();
				item.setTotalCnt1(0L);
				item.setTotalCnt2(0L);
				item.setTotalCnt3(0L);
				item.setAreaName(br.getCityName());
				item.setAreaCode(br.getCityCode());
				item.setAreaShortName(br.getCityShortName());
				itemList.add(item);
			}
		}

		Collections.sort(itemList, new Comparator<CIndicationSumItem>() {
			@Override
			public int compare(CIndicationSumItem o1, CIndicationSumItem o2) {
				return (int) ((o2.getTotalCnt1() + o2.getTotalCnt2() + o2.getTotalCnt3()) - (o1.getTotalCnt1() + o1.getTotalCnt2() + o1.getTotalCnt3()));
			}
		});

		itemList.add(0, totalItem);

		dto.setList(itemList);
		return dto;

	}
	@Override
	public CIndicationInfoDTO listReportHzqy(CIndicationInfo cIndicationInfo) {
		CIndicationInfoDTO dto = new CIndicationInfoDTO();
		dto.setList(new ArrayList<CIndicationInfoVO>());
		Map<String, CIndicationInfoVO> alreadyMap = new HashMap<String, CIndicationInfoVO>();

		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(cIndicationInfo.getCityCode()) && !"53".equals(cIndicationInfo.getCityCode())) {
			String cityCode = cIndicationInfo.getCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				cIndicationInfo.setCityCode(cityCode);
			}
		}


//		Set<String> oldyearSet = new HashSet<String>();
//		int currYear2 = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
//		for (int i = 0; i < 6; i++) {
//			oldyearSet.add((currYear2 - 5) +i+ "");
//		}

//		Set<String> yearSet = new HashSet<String>();
//		for (Map map : dataList) {
//			yearSet.add(getStr(map, "pub_year"));
//		}

		List<String> years = new ArrayList<String>();
//		years.addAll(oldyearSet);
//		years.addAll(yearSet);
//		if (years.isEmpty()) {
		if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate()) && StringUtils.isNotBlank(cIndicationInfo.getEndDate())
				&& Integer.parseInt(cIndicationInfo.getBeginDate()) <= Integer.parseInt(cIndicationInfo.getEndDate())) {
			int begin = Integer.parseInt(cIndicationInfo.getBeginDate().substring(0, 4));
			int end = Integer.parseInt(cIndicationInfo.getEndDate().substring(0, 4));
			for (int b = begin; b <= end; b++) {
				years.add(b + "");
			}
		} else {
			int currYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
			for (int i = 0; i < 6; i++) {
				years.add((currYear - 5) + i + "");
			}
		}
//		}

		Collections.sort(years, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return Integer.parseInt(o1) - Integer.parseInt(o2);
			}

		});

		dto.setYears(years);

		List<Map> dataList = new ArrayList<Map>();
		for (String year : years) {
			if(!retEmpty) {
				cIndicationInfo.setEndDate(year+"1231");
				List<Map> yearList = cIndicationInfoMapper.listReportHzqy(cIndicationInfo);
//				pub_year
				for(Map map:yearList) {
					map.put("pub_year", year);
				}
				dataList.addAll(yearList);
			}
		}
//		TODO	汇总	
		CIndicationInfoVO totalVo = new CIndicationInfoVO();
		totalVo.setTotals(new HashMap<String, String>());
		totalVo.setHzqyCounts(new HashMap<String, Long>());
		String cityCode = cIndicationInfo.getCityCode();
		if (StringUtils.isBlank(cityCode)) {
			totalVo.setAreaName("云南省");
		} else {
			String areaName = "---";
			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(cityCode);
			if (bladeRegion != null) {
				String name = bladeRegion.getName();
				if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
					name = bladeRegion.getCityShortName().replace("-", "");
				} else if (StringUtils.isNotBlank(bladeRegion.getDistrictShortName())) {
					name = bladeRegion.getDistrictShortName();
				}
				areaName = name;
			}
			totalVo.setAreaName(areaName);
		}

		for (String year : years) {
			totalVo.getTotals().put(year, "0");
			totalVo.getHzqyCounts().put(year, 0L);
		}
		
		
		

		for (Map map : dataList) {
			String areaName = getStr(map, "area_name");
			String areaCode = getStr(map, "area_code");
			if (!alreadyMap.containsKey(areaCode)) {
				CIndicationInfoVO vo = new CIndicationInfoVO();
				vo.setAreaName(areaName);
				vo.setAreaCode(areaCode);
				alreadyMap.put(areaCode, vo);
				vo.setTotals(new HashMap<String, String>());
				vo.setHzqyCounts(new HashMap<String, Long>());
//				for (String year : yearSet) {
				for (String year : years) {
//					if (!years.contains(year)) {
//						continue;
//					}
					vo.getTotals().put(year, "0");
					vo.getHzqyCounts().put(year, 0L);
				}
			}

			CIndicationInfoVO vo = alreadyMap.get(areaCode);
			String year = getStr(map, "pub_year");

//			if (!years.contains(year)) {
//				continue;
//			}

			long oldCnt = 0L;
			if (vo.getTotals().containsKey(year)) {
				oldCnt = Long.parseLong(vo.getTotals().get(year));
			}
			long newCnt = getLong(map, "total_cnt");
			vo.getTotals().put(year, (oldCnt + newCnt) + "");

			long oldHzqy = 0L;
			if (vo.getHzqyCounts().containsKey(year)) {
				oldHzqy = vo.getHzqyCounts().get(year);
			}
			long hzqyCnt = getLong(map, "hzqy_counts");
			vo.getHzqyCounts().put(year, (oldHzqy + hzqyCnt));

			if (totalVo.getTotals().containsKey(year)) {
				long oldTotalCnt = Long.parseLong(totalVo.getTotals().get(year));
				totalVo.getTotals().put(year, (oldTotalCnt + newCnt) + "");
			}

			if (totalVo.getHzqyCounts().containsKey(year)) {
				long oldTotalHzqy = totalVo.getHzqyCounts().get(year);
				totalVo.getHzqyCounts().put(year, oldTotalHzqy + hzqyCnt);
			}

		}
		if(!alreadyMap.isEmpty()) {
			dto.getList().add(totalVo);
		}
		
//		dto.getList().addAll(alreadyMap.values());
		
		List<String>areaCodes=BladeRegionUtils.sortedKey(alreadyMap.keySet());
		for(String areaCode:areaCodes) {
			dto.getList().add(alreadyMap.get(areaCode));
		}
		

		// 补0 20230710
		for (CIndicationInfoVO vo : alreadyMap.values()) {
			if (vo.getTotals() == null) {
				vo.setTotals(new HashMap<String, String>());
			}
			if (vo.getHzqyCounts() == null) {
				vo.setHzqyCounts(new HashMap<String, Long>());
			}
			
			if(StringUtils.isNotBlank(vo.getAreaCode())) {
				BladeRegion bladeRegion = BladeRegionUtils.selectByCode(vo.getAreaCode());
				if (bladeRegion != null) {
					String name = bladeRegion.getName();
					if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
						name = bladeRegion.getCityShortName().replace("-", "");
					} else if (StringUtils.isNotBlank(bladeRegion.getDistrictShortName())) {
						name = bladeRegion.getDistrictShortName();
					}
					vo.setAreaName(name);
				}
			}
			
			

			for (String year : years) {
				if (!vo.getTotals().containsKey(year)) {
					vo.getTotals().put(year, "0");
				}
				if (!vo.getHzqyCounts().containsKey(year)) {
					vo.getHzqyCounts().put(year, 0L);
				}
			}
		}

		
		
		return dto;
	}
	
	/**
	 * 这个不含累计
	 * @param cIndicationInfo
	 * @return
	 */
	public CIndicationInfoDTO listReportHzqy_bak(CIndicationInfo cIndicationInfo) {
		CIndicationInfoDTO dto = new CIndicationInfoDTO();
		dto.setList(new ArrayList<CIndicationInfoVO>());
		Map<String, CIndicationInfoVO> alreadyMap = new HashMap<String, CIndicationInfoVO>();

		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(cIndicationInfo.getCityCode()) && !"53".equals(cIndicationInfo.getCityCode())) {
			String cityCode = cIndicationInfo.getCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				cIndicationInfo.setCityCode(cityCode);
			}
		}
		List<Map> dataList = new ArrayList<Map>();
		if(!retEmpty) {
			dataList = cIndicationInfoMapper.listReportHzqy(cIndicationInfo);
		}

//		Set<String> oldyearSet = new HashSet<String>();
//		int currYear2 = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
//		for (int i = 0; i < 6; i++) {
//			oldyearSet.add((currYear2 - 5) +i+ "");
//		}

		Set<String> yearSet = new HashSet<String>();
		for (Map map : dataList) {
			yearSet.add(getStr(map, "pub_year"));
		}

		List<String> years = new ArrayList<String>();
//		years.addAll(oldyearSet);
//		years.addAll(yearSet);
//		if (years.isEmpty()) {
		if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate()) && StringUtils.isNotBlank(cIndicationInfo.getEndDate())
				&& Integer.parseInt(cIndicationInfo.getBeginDate()) <= Integer.parseInt(cIndicationInfo.getEndDate())) {
			int begin = Integer.parseInt(cIndicationInfo.getBeginDate().substring(0, 4));
			int end = Integer.parseInt(cIndicationInfo.getEndDate().substring(0, 4));
			for (int b = begin; b <= end; b++) {
				years.add(b + "");
			}
		} else {
			int currYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
			for (int i = 0; i < 6; i++) {
				years.add((currYear - 5) + i + "");
			}
		}
//		}

		Collections.sort(years, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return Integer.parseInt(o1) - Integer.parseInt(o2);
			}

		});

		dto.setYears(years);

//		TODO	汇总	
		CIndicationInfoVO totalVo = new CIndicationInfoVO();
		totalVo.setTotals(new HashMap<String, String>());
		totalVo.setHzqyCounts(new HashMap<String, Long>());
		String cityCode = cIndicationInfo.getCityCode();
		if (StringUtils.isBlank(cityCode)) {
			totalVo.setAreaName("云南省");
		} else {
			String areaName = "---";
			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(cityCode);
			if (bladeRegion != null) {
				String name = bladeRegion.getName();
				if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
					name = bladeRegion.getCityShortName().replace("-", "");
				} else if (StringUtils.isNotBlank(bladeRegion.getDistrictShortName())) {
					name = bladeRegion.getDistrictShortName();
				}
				areaName = name;
			}
			totalVo.setAreaName(areaName);
		}

		for (String year : years) {
			totalVo.getTotals().put(year, "0");
			totalVo.getHzqyCounts().put(year, 0L);
		}

		for (Map map : dataList) {
			String areaName = getStr(map, "area_name");
			String areaCode = getStr(map, "area_code");
			if (!alreadyMap.containsKey(areaCode)) {
				CIndicationInfoVO vo = new CIndicationInfoVO();
				vo.setAreaName(areaName);
				vo.setAreaCode(areaCode);
				alreadyMap.put(areaCode, vo);
				vo.setTotals(new HashMap<String, String>());
				vo.setHzqyCounts(new HashMap<String, Long>());
				for (String year : yearSet) {
					if (!years.contains(year)) {
						continue;
					}
					vo.getTotals().put(year, "0");
					vo.getHzqyCounts().put(year, 0L);
				}
			}

			CIndicationInfoVO vo = alreadyMap.get(areaCode);
			String year = getStr(map, "pub_year");

			if (!years.contains(year)) {
				continue;
			}

			long oldCnt = 0L;
			if (vo.getTotals().containsKey(year)) {
				oldCnt = Long.parseLong(vo.getTotals().get(year));
			}
			long newCnt = getLong(map, "total_cnt");
			vo.getTotals().put(year, (oldCnt + newCnt) + "");

			long oldHzqy = 0L;
			if (vo.getHzqyCounts().containsKey(year)) {
				oldHzqy = vo.getHzqyCounts().get(year);
			}
			long hzqyCnt = getLong(map, "hzqy_counts");
			vo.getHzqyCounts().put(year, (oldHzqy + hzqyCnt));

			if (totalVo.getTotals().containsKey(year)) {
				long oldTotalCnt = Long.parseLong(totalVo.getTotals().get(year));
				totalVo.getTotals().put(year, (oldTotalCnt + newCnt) + "");
			}

			if (totalVo.getHzqyCounts().containsKey(year)) {
				long oldTotalHzqy = totalVo.getHzqyCounts().get(year);
				totalVo.getHzqyCounts().put(year, oldTotalHzqy + hzqyCnt);
			}

		}
//		if(!alreadyMap.isEmpty()) {
//			dto.getList().add(totalVo);
//		}
		
//		dto.getList().addAll(alreadyMap.values());
		
		List<String>areaCodes=BladeRegionUtils.sortedKey(alreadyMap.keySet());
		for(String areaCode:areaCodes) {
			dto.getList().add(alreadyMap.get(areaCode));
		}
		

		// 补0 20230710
		for (CIndicationInfoVO vo : alreadyMap.values()) {
			if (vo.getTotals() == null) {
				vo.setTotals(new HashMap<String, String>());
			}
			if (vo.getHzqyCounts() == null) {
				vo.setHzqyCounts(new HashMap<String, Long>());
			}
			
			if(StringUtils.isNotBlank(vo.getAreaCode())) {
				BladeRegion bladeRegion = BladeRegionUtils.selectByCode(vo.getAreaCode());
				if (bladeRegion != null) {
					String name = bladeRegion.getName();
					if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
						name = bladeRegion.getCityShortName().replace("-", "");
					} else if (StringUtils.isNotBlank(bladeRegion.getDistrictShortName())) {
						name = bladeRegion.getDistrictShortName();
					}
					vo.setAreaName(name);
				}
			}
			
			

			for (String year : years) {
				if (!vo.getTotals().containsKey(year)) {
					vo.getTotals().put(year, "0");
				}
				if (!vo.getHzqyCounts().containsKey(year)) {
					vo.getHzqyCounts().put(year, 0L);
				}
			}
		}

		
//		//20231204
//		//准备求汇总 
//		List<String>yearList=dto.getYears();
//		Collections.sort(yearList,new Comparator<String>() {
//			@Override
//			public int compare(String o1, String o2) {
//				// TODO Auto-generated method stub
//				return Integer.parseInt(o1)-Integer.parseInt(o2);
//			}
//		});
//		
//		for(CIndicationInfoVO vo:dto.getList()) {
//			Map<String,String>oldTotalMap=vo.getTotals();
//			Map<String,String>newTotalMap=new LinkedHashMap<String, String>();
//			
//			Map<String,Long>oldHzqyMap=vo.getHzqyCounts();
//			Map<String,Long>newHzqyMap=new LinkedHashMap<String, Long>();
//			
//			for(String currYear:yearList) {
//				int currYearInt=Integer.parseInt(currYear);
//				int currTotalVal=0;
//				int currHzqyVal=0;
//				for(String year:yearList) {
//					if(Integer.parseInt(year)<=currYearInt ) {
//						if(oldTotalMap.containsKey(year)) {
//							currTotalVal=currTotalVal+Integer.parseInt(oldTotalMap.get(year));
//						}
//						if(oldHzqyMap.containsKey(year)) {
//							currHzqyVal = currHzqyVal+oldHzqyMap.get(year).intValue();
//						}
//					}
//				}
//				
//				newTotalMap.put(currYear, currTotalVal+"");
//				newHzqyMap.put(currYear, (long)currHzqyVal);
//			}
//			vo.setTotals(newTotalMap);
//			vo.setHzqyCounts(newHzqyMap);
//		}
		
		return dto;
	}
	
	

	@Override
	public CIndicationInfoDTO listReportFarm(CIndicationInfo cIndicationInfo) {

		CIndicationInfoDTO dto = new CIndicationInfoDTO();
		dto.setList(new ArrayList<CIndicationInfoVO>());
		Map<String, CIndicationInfoVO> alreadyMap = new HashMap<String, CIndicationInfoVO>();

		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(cIndicationInfo.getCityCode()) && !"53".equals(cIndicationInfo.getCityCode())) {
			String cityCode = cIndicationInfo.getCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				cIndicationInfo.setCityCode(cityCode);
			}
		}
		
		

//		Set<String> yearSet = new HashSet<String>();
//		for (Map map : dataList) {
//			yearSet.add(getStr(map, "pub_year"));
//		}

		List<String> years = new ArrayList<String>();
//		years.addAll(yearSet);
		if (years.isEmpty()) {
			if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate()) && StringUtils.isNotBlank(cIndicationInfo.getEndDate())
					&& Integer.parseInt(cIndicationInfo.getBeginDate()) <= Integer.parseInt(cIndicationInfo.getEndDate())) {
				int begin = Integer.parseInt(cIndicationInfo.getBeginDate().substring(0, 4));
				int end = Integer.parseInt(cIndicationInfo.getEndDate().substring(0, 4));
				for (int b = begin; b <= end; b++) {
					years.add(b + "");
				}
			} else {
				int currYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
				for (int i = 0; i < 6; i++) {
					years.add((currYear - 5) + "");
				}
			}
		}

		Collections.sort(years, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return Integer.parseInt(o1) - Integer.parseInt(o2);
			}

		});
		
		
		List<Map> dataList =new ArrayList<Map>();
		for(String year:years) {
			if(!retEmpty) {
				cIndicationInfo.setEndDate(year+"1231");
				List<Map> yearList = cIndicationInfoMapper.listReportFarm(cIndicationInfo);
				for(Map map:yearList) {
					map.put("pub_year", year);
				}
				dataList.addAll(yearList);
			}
		}
		

		dto.setYears(years);

		CIndicationInfoVO totalVo = new CIndicationInfoVO();
		totalVo.setTotals(new HashMap<String, String>());
		String cityCode = cIndicationInfo.getCityCode();
		if (StringUtils.isBlank(cityCode)) {
			totalVo.setAreaName("云南省");
		} else {
			String areaName = "---";
			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(cityCode);
//			BladeRegion bladeRegion = bladeRegionService.selectByCityName(cityCode, "53");
			if (bladeRegion != null) {
				String name = bladeRegion.getName();
				if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
					name = bladeRegion.getCityShortName().replace("-", "");
				} else if (StringUtils.isNotBlank(bladeRegion.getDistrictShortName())) {
					name = bladeRegion.getDistrictShortName();
				}
				areaName = name;
			}
			totalVo.setAreaName(areaName);
		}

		for (String year : years) {
			totalVo.getTotals().put(year, "0");
		}

		for (Map map : dataList) {

//			String areaName = getStr(map, "area_name");
			String areaName = getStr(map, "area_code");
			if (!alreadyMap.containsKey(areaName)) {
				CIndicationInfoVO vo = new CIndicationInfoVO();
				vo.setAreaName(getStr(map, "area_name"));
				vo.setAreaCode(getStr(map, "area_code"));
				
				if(StringUtils.isNotBlank(vo.getAreaCode())) {
					String areaName2=BladeRegionUtils.getDistrictShortName(vo.getAreaCode());
					if(StringUtils.isNotBlank(areaName2)) {
						vo.setAreaName(areaName2);
					}
				}
				
				alreadyMap.put(areaName, vo);
				vo.setTotals(new HashMap<String, String>());
				for (String year : years) {
					vo.getTotals().put(year, "0");
				}
			}

			CIndicationInfoVO vo = alreadyMap.get(areaName);
			String year = getStr(map, "pub_year");
			long oldCnt = 0L;
			if (vo.getTotals().containsKey(year)) {
				oldCnt = Long.parseLong(vo.getTotals().get(year));
			}
			long newCnt = getLong(map, "total_cnt");
			vo.getTotals().put(year, (oldCnt + newCnt) + "");

			if (totalVo.getTotals().containsKey(year)) {
				long oldTotalCnt = Long.parseLong(totalVo.getTotals().get(year));
				totalVo.getTotals().put(year, (oldTotalCnt + newCnt) + "");
			}

		}
		if(!alreadyMap.isEmpty()) {
			dto.getList().add(totalVo);
		}
		
//		dto.getList().addAll(alreadyMap.values());
		List<String>areaCodes=BladeRegionUtils.sortedKey(alreadyMap.keySet());
		for(String areaCode:areaCodes) {
			dto.getList().add(alreadyMap.get(areaCode));
		}
		
		return dto;

	}

	@Override
	public List<CIndicationInfoVO> listReportMarkRank(CIndicationInfo cIndicationInfo) {
//		http://111.198.99.166:20000/gi/gi_total?project_code=530000&ak=697394359%4020230406
//		String url = ruoYiConfig.getPressApiServer()+"gi/gi_total?project_code=530000&ak=697394359%4020230406";
		String url = ruoYiConfig.getPressApiServer() + "gi/gi_total_pub?project_code=530000&ak=697394359%4020230406";
//		ruoYiConfig
//		http://111.198.99.166:20000/gi/gi_total_pub?project_code=530000&ak=697394359%4020230406&bgn_date=20171202&end_date=20231202
		String key = "CIndicationInfo:listReportMarkRank1";
		if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate())) {
			url = url + "&bgn_date=" + cIndicationInfo.getBeginDate();
			key = key + ":bgn_date:" + cIndicationInfo.getBeginDate();
		}
		if (StringUtils.isNotBlank(cIndicationInfo.getEndDate())) {
			url = url + "&end_date=" + cIndicationInfo.getEndDate();
			key = key + ":end_date:" + cIndicationInfo.getEndDate();
		}
		String res = redisCache.getCacheObject(key);
//		String res =null;
//		if (StringUtils.isBlank(res)) {
			res = HttpUtils.sendGet(url);
			if (StringUtils.isNotBlank(res)) {
				redisCache.setCacheObject(key, res);
			}
//		}
		LinkedHashMap map = (LinkedHashMap) JSONUtils.parse(res);
		List<LinkedHashMap> list = (List<LinkedHashMap>) map.get("results");
		List<CIndicationInfoVO> itemList = getRankingList04(list);
		return itemList;
	}

	@Override
	public List<CIndicationInfoVO> listReportFarmRank(CIndicationInfo cIndicationInfo) {
//		http://111.198.99.166:20000/gi/gi_total?project_code=530000&ak=697394359%402023040
		String url = ruoYiConfig.getPressApiServer() + "gi/gi_total_pub?project_code=530000&ak=697394359%4020230406";
//		ruoYiConfig
		String key = "CIndicationInfo:listReportFarmRank";
		if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate())) {
			url = url + "&bgn_date=" + cIndicationInfo.getBeginDate();
			key = key + ":bgn_date:" + cIndicationInfo.getBeginDate();
		}
		if (StringUtils.isNotBlank(cIndicationInfo.getEndDate())) {
			url = url + "&end_date=" + cIndicationInfo.getEndDate();
			key = key + ":end_date:" + cIndicationInfo.getEndDate();
		}
		String res = redisCache.getCacheObject(key);

//		if (StringUtils.isBlank(res)) {
			res = HttpUtils.sendGet(url);
			if (StringUtils.isNotBlank(res)) {
				redisCache.setCacheObject(key, res);
			}
//		}
		LinkedHashMap map = (LinkedHashMap) JSONUtils.parse(res);
		List<LinkedHashMap> list = (List<LinkedHashMap>) map.get("results");
		List<CIndicationInfoVO> itemList = getRankingList06(list);
		return itemList;
	}

	@Override
	public List<CIndicationInfoVO> listReportAddrRank(CIndicationInfo cIndicationInfo) {
//		http://111.198.99.166:20000/gi/gi_total?project_code=530000&ak=697394359%402023040
		String url = ruoYiConfig.getPressApiServer() + "gi/gi_total_pub?project_code=530000&ak=697394359%4020230406";
//		ruoYiConfig
		String key = "CIndicationInfo:listReportAddrRank";
		if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate())) {
			url = url + "&bgn_date=" + cIndicationInfo.getBeginDate();
			key = key + ":bgn_date:" + cIndicationInfo.getBeginDate();
		}
		if (StringUtils.isNotBlank(cIndicationInfo.getEndDate())) {
			url = url + "&end_date=" + cIndicationInfo.getEndDate();
			key = key + ":end_date:" + cIndicationInfo.getEndDate();
		}
		String res = redisCache.getCacheObject(key);

//		if (StringUtils.isBlank(res)) {
			res = HttpUtils.sendGet(url);
			if (StringUtils.isNotBlank(res)) {
				redisCache.setCacheObject(key, res);
			}
//		}
		LinkedHashMap map = (LinkedHashMap) JSONUtils.parse(res);
		List<LinkedHashMap> list = (List<LinkedHashMap>) map.get("results");
		List<CIndicationInfoVO> itemList = getRankingList05(list);
		return itemList;
	}

	public static List<CIndicationInfoVO> getRankingList06(List<LinkedHashMap> list) {
		List<CIndicationInfoVO> itemList = new ArrayList<CIndicationInfoVO>();
		for (LinkedHashMap<String, Object> map : list) {
			boolean bro = false;
			for (Map.Entry<String, Object> ent : map.entrySet()) {
				if (ent.getKey().contains("全国")) {
					bro = true;
					break;
				}
				if (!ent.getKey().contains("申请人或保护范围为")) {
					continue;
				}
//				
				if (ent.getKey().contains("申请人或保护范围为") && ent.getKey().contains("农产品地理标志量")) {
					CIndicationInfoVO item = new CIndicationInfoVO();
					itemList.add(item);
					String province = ent.getKey().replace("申请人或保护范围为", "");
					province = province.replace("农产品地理标志量", "");
					if (province.endsWith("省")) {
						province = province.substring(0, province.length() - 1);
					}
					item.setAreaName(province);
					item.setNumber(ent.getValue() == null ? 0L : Long.parseLong(ent.getValue() + ""));
					break;
				}
			}
			if (bro) {
				continue;
			}
		}

		Collections.sort(itemList, new Comparator<CIndicationInfoVO>() {
			@Override
			public int compare(CIndicationInfoVO o1, CIndicationInfoVO o2) {
				if (o1 == null && o2 == null) {
					return 0;
				} else if (o1 == null) {
					return -1;
				} else if (o2 == null) {
					return 1;
				} else {
					if (o1.getNumber() == null && o2.getNumber() == null) {
						return 0;
					} else if (o1.getNumber() == null) {
						return -1;
					} else if (o2.getNumber() == null) {
						return 1;
					} else {
						return (int) (o2.getNumber() - o1.getNumber());
					}
				}
			}
		});

		for (int i = 0; i < itemList.size(); i++) {
			itemList.get(i).setRanking(i + 1);
		}
		return itemList;
	}

	public List<CIndicationInfoVO> getRankingList05(List<LinkedHashMap> list) {

		// 查云南用自己的数据 20230927
		CIndicationInfoVO ynItem = null;
		CIndicationInfo qo = new CIndicationInfo();
		qo.setDataType("原产地地理标志");
		List ynList = this.queryList(qo);
		if (ynList != null && ynList.size() > 0) {
			ynItem = new CIndicationInfoVO();
			ynItem.setAreaName("云南");
			ynItem.setNumber(Long.parseLong(ynList.size() + ""));
		}

		List<CIndicationInfoVO> itemList = new ArrayList<CIndicationInfoVO>();
		for (LinkedHashMap<String, Object> map : list) {
			boolean bro = false;
			for (Map.Entry<String, Object> ent : map.entrySet()) {
				if (ent.getKey().contains("全国")) {
					bro = true;
					break;
				}
				if (!ent.getKey().contains("申请人或保护范围为")) {
					continue;
				}
//				
				if (ent.getKey().contains("申请人或保护范围为") && ent.getKey().contains("原产地地理标志量")) {
					String province = ent.getKey().replace("申请人或保护范围为", "");
					province = province.replace("原产地地理标志量", "");
					if (province.endsWith("省")) {
						province = province.substring(0, province.length() - 1);
					}
					
					if ("云南".equals(province) && ynItem!=null) {
						logger.debug("排名接口的云南条数:"+ent.getValue()+",详情中的云南条数:"+ynItem.getNumber());
						itemList.add(ynItem);
						continue;
					}
					
					CIndicationInfoVO item = new CIndicationInfoVO();
					itemList.add(item);
					item.setAreaName(province);
					item.setNumber(ent.getValue() == null ? 0L : Long.parseLong(ent.getValue() + ""));
					break;
				}
			}
			if (bro) {
				continue;
			}
		}

		Collections.sort(itemList, new Comparator<CIndicationInfoVO>() {
			@Override
			public int compare(CIndicationInfoVO o1, CIndicationInfoVO o2) {
				if (o1 == null && o2 == null) {
					return 0;
				} else if (o1 == null) {
					return -1;
				} else if (o2 == null) {
					return 1;
				} else {
					if (o1.getNumber() == null && o2.getNumber() == null) {
						return 0;
					} else if (o1.getNumber() == null) {
						return -1;
					} else if (o2.getNumber() == null) {
						return 1;
					} else {
						return (int) (o2.getNumber() - o1.getNumber());
					}
				}
			}
		});

		for (int i = 0; i < itemList.size(); i++) {
			itemList.get(i).setRanking(i + 1);
		}
		return itemList;
	}

	public static List<CIndicationInfoVO> getRankingList04(List<LinkedHashMap> list) {
		List<CIndicationInfoVO> itemList = new ArrayList<CIndicationInfoVO>();
		if (list == null || list.isEmpty()) {
			return itemList;
		}
		for (LinkedHashMap<String, Object> map : list) {
			boolean bro = false;

			for (Map.Entry<String, Object> ent : map.entrySet()) {
				if (ent.getKey().contains("全国")) {
					bro = true;
					break;
				}
				if (!ent.getKey().contains("申请人或保护范围为")) {
					continue;
				}
//				
				if (ent.getKey().contains("申请人或保护范围为") && ent.getKey().contains("地理标志商标量")) {
					CIndicationInfoVO item = new CIndicationInfoVO();
					itemList.add(item);
					String province = ent.getKey().replace("申请人或保护范围为", "");
					province = province.replace("地理标志商标量", "");
					if (province.endsWith("省")) {
						province = province.substring(0, province.length() - 1);
					}
					item.setAreaName(province);
					item.setNumber(ent.getValue() == null ? 0L : Long.parseLong(ent.getValue() + ""));
					break;
				}
			}
			if (bro) {
				continue;
			}
		}

		Collections.sort(itemList, new Comparator<CIndicationInfoVO>() {
			@Override
			public int compare(CIndicationInfoVO o1, CIndicationInfoVO o2) {
				if (o1 == null && o2 == null) {
					return 0;
				} else if (o1 == null) {
					return -1;
				} else if (o2 == null) {
					return 1;
				} else {
					if (o1.getNumber() == null && o2.getNumber() == null) {
						return 0;
					} else if (o1.getNumber() == null) {
						return -1;
					} else if (o2.getNumber() == null) {
						return 1;
					} else {
						return (int) (o2.getNumber() - o1.getNumber());
					}
				}
			}
		});

		for (int i = 0; i < itemList.size(); i++) {
			itemList.get(i).setRanking(i + 1);
		}
		return itemList;
	}

	public List<CIndicationInfoDTO> listReportGrowth(CIndicationInfo cTrademark) {

		cTrademark.setBeginDate(cTrademark.getBeginDate1());
		cTrademark.setEndDate(cTrademark.getEndDate1());
		Map<String, CIndicationInfoVO> map1 = listReportGrowthOne(cTrademark);

		cTrademark.setBeginDate(cTrademark.getBeginDate2());
		cTrademark.setEndDate(cTrademark.getEndDate2());
		Map<String, CIndicationInfoVO> map2 = listReportGrowthOne(cTrademark);

		String compareRate1 = cTrademark.getBeginDate1() + " 至  " + cTrademark.getEndDate1();
		String compareRate2 = cTrademark.getBeginDate2() + " 至  " + cTrademark.getEndDate2();

		Set<String> areaSet = new HashSet<String>();
		for (Map.Entry<String, CIndicationInfoVO> ent : map2.entrySet()) {
			String key = ent.getKey();
			areaSet.add(key);
			if (!map1.containsKey(key)) {
				CIndicationInfoVO vo = new CIndicationInfoVO();
				vo.setAreaName(key);
				vo.setTotals(new HashMap<String, String>());
				vo.getTotals().put("totalCnt1", "0");
				vo.getTotals().put("totalCnt2", "0");
				vo.getTotals().put("totalCnt3", "0");
				vo.getTotals().put("totalCnt4", "0");
				map1.put(key, vo);
			}
		}

		for (Map.Entry<String, CIndicationInfoVO> ent : map1.entrySet()) {
			String key = ent.getKey();
			areaSet.add(key);
			if (!map2.containsKey(key)) {
				CIndicationInfoVO vo = new CIndicationInfoVO();
				vo.setAreaName(key);
				vo.setTotals(new HashMap<String, String>());
				vo.getTotals().put("totalCnt1", "0");
				vo.getTotals().put("totalCnt2", "0");
				vo.getTotals().put("totalCnt3", "0");
				vo.getTotals().put("totalCnt4", "0");
				map2.put(key, vo);
			}
		}

		List<CIndicationInfoDTO> list = new ArrayList<CIndicationInfoDTO>();
		for (String areaName : areaSet) {

			CIndicationInfoVO item1 = map1.get(areaName);
			CIndicationInfoVO item2 = map2.get(areaName);
			item2.setAreaName(null);

			CIndicationInfoDTO dto = new CIndicationInfoDTO();
			dto.setAreaName(areaName);
			dto.setItem1(item1);
			item1.setCompareRate(compareRate1);

			dto.setItem2(item2);
			item2.setCompareRate(compareRate2);

			CIndicationInfoVO growth = new CIndicationInfoVO();
			growth.setCompareRate("同比增长");

			growth.setTotals(new HashMap<String, String>());
			growth.getTotals().put("totalCnt1", getGrowth(item1.getTotals().get("totalCnt1"), item2.getTotals().get("totalCnt1")));
			growth.getTotals().put("totalCnt2", getGrowth(item1.getTotals().get("totalCnt2"), item2.getTotals().get("totalCnt2")));
			growth.getTotals().put("totalCnt3", getGrowth(item1.getTotals().get("totalCnt3"), item2.getTotals().get("totalCnt3")));
			growth.getTotals().put("totalCnt4", getGrowth(item1.getTotals().get("totalCnt4"), item2.getTotals().get("totalCnt4")));

			dto.setGrowth(growth);

			list.add(dto);
		}

		return list;
	}

	private Map<String, CIndicationInfoVO> listReportGrowthOne(CIndicationInfo cTrademark) {
		List<Map> dataList = cIndicationInfoMapper.listReportGrowth(cTrademark);
//		List<Map> dataList = null;
		Map<String, CIndicationInfoVO> voMap = new HashMap<String, CIndicationInfoVO>();
		for (Map map : dataList) {
			CIndicationInfoVO vo = new CIndicationInfoVO();
			String areaName = getStr(map, "modify_city");
			vo.setAreaName(areaName);

			vo.setTotals(new HashMap<String, String>());
			vo.getTotals().put("totalCnt1", getStr(map, "total_cnt1"));
			vo.getTotals().put("totalCnt2", getStr(map, "total_cnt2"));
			vo.getTotals().put("totalCnt3", getStr(map, "total_cnt3"));
			vo.getTotals().put("totalCnt4", getStr(map, "total_cnt4"));

			voMap.put(areaName, vo);

		}
		return voMap;
	}

	private String getGrowth(String total1str, String total2str) {
		if (StringUtils.isBlank(total1str) || StringUtils.isBlank(total2str)) {
			return "--";
		}
		Long total1 = Long.parseLong(total1str);
		Long total2 = Long.parseLong(total2str);
		if (total1 == null || total1 == 0L || total2 == null || total2 == 0L) {
			return "--";
		}

		Double growth = (total2 - total1 + 0.0) / total1 * 100;
		String growthStr = String.format("%.2f", growth) + "%";
		return growthStr;
	}

	@Override
	public CIndicationInfoDTO listReportMark(CIndicationInfo cIndicationInfo) {

		CIndicationInfoDTO dto = new CIndicationInfoDTO();
		dto.setList(new ArrayList<CIndicationInfoVO>());
		Map<String, CIndicationInfoVO> alreadyMap = new HashMap<String, CIndicationInfoVO>();
		
		
		List<Map> allList = new ArrayList<Map>();
		
		
		for(String year:cIndicationInfo.getPubYears()) {
			CIndicationInfo oneQo=BeanUtil.copyProperties(cIndicationInfo, CIndicationInfo.class);
			oneQo.setSumYear(year);
			if(!oneQo.getSumYearDate().startsWith(year)) {
				oneQo.setSumYearDate(year+"1231");
			}
			boolean retEmpty=false;
			if (StringUtils.isNotBlank(oneQo.getCityCode()) && !"53".equals(oneQo.getCityCode())) {
				String cityCode = oneQo.getCityCode().trim();
				if(SecurityUtils.isNeedFilterByCityCode()) {
					String cc=SecurityUtils.needFilterByCityCode();
					if(!cc.equals(cityCode) ) {
						retEmpty=true;
					}
				}
			}else {
				if(SecurityUtils.isNeedFilterByCityCode()) {
					String cityCode=SecurityUtils.needFilterByCityCode();
					oneQo.setCityCode(cityCode);
				}
			}
			List<Map> dataList = new ArrayList<Map>();
			if(!retEmpty) {
				dataList = cIndicationInfoMapper.listReportMark(oneQo);
			}
			
			for(Map map:dataList) {
				map.put("pub_year", year);
			}
			allList.addAll(dataList);
		}

		

		Set<String> yearSet = new HashSet<String>();
		for (Map map : allList) {
			yearSet.add(getStr(map, "pub_year"));
		}

		List<String> years = new ArrayList<String>();
		years.addAll(yearSet);
		if (years.isEmpty()) {
			if (StringUtils.isNotBlank(cIndicationInfo.getBeginDate()) && StringUtils.isNotBlank(cIndicationInfo.getEndDate())
					&& Integer.parseInt(cIndicationInfo.getBeginDate()) <= Integer.parseInt(cIndicationInfo.getEndDate())) {
				int begin = Integer.parseInt(cIndicationInfo.getBeginDate().substring(0, 4));
				int end = Integer.parseInt(cIndicationInfo.getEndDate().substring(0, 4));
				for (int b = begin; b <= end; b++) {
					years.add(b + "");
				}
			} else {
				int currYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
				for (int i = 0; i < 6; i++) {
					years.add((currYear - 5) + "");
				}
			}
		}

		Collections.sort(years, new Comparator<String>() {
			@Override
			public int compare(String o1, String o2) {
				return Integer.parseInt(o1) - Integer.parseInt(o2);
			}

		});

		dto.setYears(years);

//		TODO	汇总	
		CIndicationInfoVO totalVo = new CIndicationInfoVO();
		totalVo.setTotals(new HashMap<String, String>());
		String cityCode = cIndicationInfo.getCityCode();
		if (StringUtils.isBlank(cityCode)) {
			totalVo.setAreaName("云南省");
		} else {
			String areaName = "---";
			BladeRegion bladeRegion = BladeRegionUtils.selectByCode(cityCode);
//			BladeRegion bladeRegion = bladeRegionService.selectByCityName(cityCode, "53");
			if (bladeRegion != null) {
				String name = bladeRegion.getName();
				if (StringUtils.isNotBlank(bladeRegion.getCityShortName())) {
					name = bladeRegion.getCityShortName().replace("-", "");
				} else if (StringUtils.isNotBlank(bladeRegion.getDistrictShortName())) {
					name = bladeRegion.getDistrictShortName();
				}
				areaName = name;
			}
			totalVo.setAreaName(areaName);
		}
		for (String year : years) {
			totalVo.getTotals().put(year, "0");
		}

		for (Map map : allList) {

//			String areaName = getStr(map, "area_name");
			String areaName = getStr(map, "area_code");
			if (!alreadyMap.containsKey(areaName)) {
				CIndicationInfoVO vo = new CIndicationInfoVO();
				vo.setAreaName(areaName);
				vo.setAreaCode(getStr(map, "area_code"));
				alreadyMap.put(areaName, vo);
				vo.setTotals(new HashMap<String, String>());
				for (String year : yearSet) {
					vo.getTotals().put(year, "0");
				}
			}

			CIndicationInfoVO vo = alreadyMap.get(areaName);
			String year = getStr(map, "pub_year");
			long oldCnt = 0L;
			if (vo.getTotals().containsKey(year)) {
				oldCnt = Long.parseLong(vo.getTotals().get(year));
			}
			long newCnt = getLong(map, "total_cnt");
			vo.getTotals().put(year, (oldCnt + newCnt) + "");

			if (totalVo.getTotals().containsKey(year)) {
				long oldTotalCnt = Long.parseLong(totalVo.getTotals().get(year));
				totalVo.getTotals().put(year, (oldTotalCnt + newCnt) + "");
			}

		}
		
		if(!alreadyMap.isEmpty()) {
			dto.getList().add(totalVo);
		}
		
		
		List<String>areaCodes=BladeRegionUtils.sortedKey(alreadyMap.keySet());
		for(String areaCode:areaCodes) {
			dto.getList().add(alreadyMap.get(areaCode));
		}
		
//		dto.getList().addAll(alreadyMap.values());
		
		
		totalVo.setTotalsBak(totalVo.getTotals());
		
		
		for(CIndicationInfoVO vo:dto.getList()) {
			sumTotoal(vo.getTotals());
			
			if(StringUtils.isNotBlank(vo.getAreaCode())) {
				String areaName=BladeRegionUtils.getDistrictShortName(vo.getAreaCode());
				if(StringUtils.isNotBlank(areaName)) {
					vo.setAreaName(areaName);
				}
			}
		}
		return dto;

	}
	
	/**
	 * 累计
	 */
	private void sumTotoal(Map<String,String>totals) {
		
//		List<String>years=new ArrayList<String>();
//		years.addAll(totals.keySet());
//		years.sort(new Comparator<String>() {
//			@Override
//			public int compare(String o1, String o2) {
//				return Integer.parseInt(o1)-Integer.parseInt(o2);
//			}
//		});
//		for(int i=1;i<years.size();i++) {
//			String currVal=totals.get(years.get(i));
//			String lastVal=totals.get(years.get(i-1));
//			String sumVal=(Integer.parseInt(currVal)+Integer.parseInt(lastVal))+"";
//			totals.put(years.get(i), sumVal);
//		}
		
	}

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

	public CIndicationInfo queryByPid(String pid) {
		CIndicationInfo qo = new CIndicationInfo();
		qo.setPid(pid);
		List<CIndicationInfo> list = queryList(qo);
		if (list != null && !list.isEmpty() && list.get(0) != null) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public void doSyncForIprd(String beginDate, String endDate) {

		// TODO Auto-generated method stub
//		http://111.198.99.166:20000/gi/iprd_gi?project_code=530000&ak=78f39e695%4020230406&time_update=20210101&size=100'
		String baseUrl = ruoYiConfig.getPressApiServer() + "gi/iprd_gi?project_code=530000&ak=78f39e695%4020230406&time_update=" + beginDate + "&size=1000";

		String code = "200";
		String scroll_id = null;
		
		logger.debug("清空地理标志数据");
		cIndicationInfoMapper.clearData();

		int i = 0;
		while ("200".equals(code)) {
			String url = baseUrl;
			if (StringUtils.isNotBlank(scroll_id)) {
				url = baseUrl + "&scroll_id=" + scroll_id;
			}
			i++;
			logger.debug("开始查询第" + i + "页地标基本数据,url:" + url);
			long beginTime = System.currentTimeMillis();
			String res = HttpUtils.sendGet(url);
			logger.debug("第" + i + "页基本数据查询结果,用时:" + (System.currentTimeMillis() - beginTime) + ",res:" + res);
			IndicationInfoMod mod = new Gson().fromJson(res, IndicationInfoMod.class);
			scroll_id = mod.scroll_id;
			code = mod.code;
			if (mod.results == null || mod.results.isEmpty()) {
				break;
			}
			for (IndicationInfoItem ti : mod.results) {

//				CIndicationInfo old = queryByPid(ti._id);
				CIndicationInfo old = null;

				CIndicationInfo t = ti.toCIndicationInfo();

				if (StringUtils.isNotBlank(t.getAppProvince())) {
					BladeRegion bladeRegion = bladeRegionService.selectByProvinceName(t.getAppProvince());
					if (bladeRegion != null) {
						t.setAppProvinceCode(bladeRegion.getCode());
					}
				}

				if (StringUtils.isNotBlank(t.getAppCity()) && StringUtils.isNotBlank(t.getAppProvinceCode())) {
					BladeRegion bladeRegion = bladeRegionService.selectByCityName(t.getAppCity(), t.getAppProvinceCode());
					if (bladeRegion != null) {
						t.setAppCityCode(bladeRegion.getCode());
					}
				}

				if (StringUtils.isNotBlank(t.getAppCounty()) && StringUtils.isNotBlank(t.getAppCityCode())) {
					BladeRegion bladeRegion = bladeRegionService.selectByAreaName(t.getAppCounty(), t.getAppCityCode());
					if (bladeRegion != null) {
						t.setAppCountyCode(bladeRegion.getCode());
					}
				}

				if (StringUtils.isNotBlank(t.getModifyAppProvince())) {
					BladeRegion bladeRegion = bladeRegionService.selectByProvinceName(t.getModifyAppProvince());
					if (bladeRegion != null) {
						t.setModifyAppProvinceCode(bladeRegion.getCode());
					}
				}

				if (StringUtils.isNotBlank(t.getModifyAppCity()) && StringUtils.isNotBlank(t.getModifyAppProvinceCode())) {
					BladeRegion bladeRegion = bladeRegionService.selectByCityName(t.getModifyAppCity(), t.getModifyAppProvinceCode());
					if (bladeRegion != null) {
						t.setModifyAppCityCode(bladeRegion.getCode());
					}
				}

				if (StringUtils.isNotBlank(t.getModifyAppCounty()) && StringUtils.isNotBlank(t.getModifyAppCityCode())) {
					BladeRegion bladeRegion = bladeRegionService.selectByAreaName(t.getModifyAppCounty(), t.getModifyAppCityCode());
					if (bladeRegion != null) {
						t.setModifyAppCountyCode(bladeRegion.getCode());
					}
				}
				if (old != null) {
					t.setId(old.getId());
					t.setUpdateTime(new Date());
					updateById(t);
				} else {
					save(t);
				}
			}

		}

	}

	public static class IndicationInfoMod {
		private String code;
		private Long total;
		private String scroll_id;
		private List<IndicationInfoItem> results;
	}

	public static class IndicationInfoItem {
//		"_id": "5313",
		private String _id;
//	      "zljs": "AGI2014-01-1433",
		private String zljs;
//	      "app_province": "云南省",
		private String app_province;
//	      "bhfw_province": "云南省;",
		private String bhfw_province;
//	      "modify_app_county": "泸西县",
		private String modify_app_county;
//	      "fjig": "",
		private String fjig;
//	      "pub_date": "20140522",
		private String pub_date;
//	      "ssp": "",
		private String ssp;
//	      "time_update": "20230420",
		private String time_update;
//	      "app_county": "泸西县",
		private String app_county;
//	      "pub_type": "登记公告",
		private String pub_type;
//	      "pron": "泸西高原梨",
		private String pron;
//	      "pub_year": "2014",
		private String pub_year;
//	      "modify_app_province": "云南省",
		private String modify_app_province;
//	      "hzqy_counts": "0",
		private Long hzqy_counts;
//	      "fdate": "",
		private String fdate;
//	      "app_city": "红河哈尼族彝族自治州",
		private String app_city;
//	      "modify_app_city": "红河哈尼族彝族自治州",
		private String modify_app_city;
//	      "area": "云南",
		private String area;
//	      "time_create": "20230420",
		private String time_create;
//	      "pub_dw": "农业农村部",
		private String pub_dw;
//	      "zybz": "",
		private String zybz;
//	      "applicant": "泸西县果树站",
		private String applicant;
//	      "anddr": "",
		private String anddr;
//	      "bhfw_city": "红河哈尼族彝族自治州;",
		private String bhfw_city;
//	      "pty": "",
		private String pty;
//	      "bhwj": "",
		private String bhwj;
//	      "bhfw_county": "泸西县;",
		private String bhfw_county;
//	      "data_type": "农产品地理标志",
		private String data_type;
//	      "bhfw": "泸西县中枢镇、舞街镇、白水镇、金马镇、旧城镇、永宁乡、向阳乡、三塘乡8个乡镇，地理坐标为东经103°30′00″～104°03′00″，北纬24°15′00″～24°46′00″。",
		private String bhfw;
//	      "pub_no": "第2105号"
		private String pub_no;

		public CIndicationInfo toCIndicationInfo() {
			CIndicationInfo c = new CIndicationInfo();

//			/** 数据类型 */
//			@Excel(name = "数据类型")
//			private String dataType;
			c.setDataType(data_type);
//
//			private String pid;
			c.setPid(_id);
//			/** 产品名称 */
//			@Excel(name = "产品名称")
//			private String pron;
			c.setPron(pron);
//
//			/** 公告号（注册号） */
//			@Excel(name = "公告号", readConverterExp = "注=册号")
//			private String pubNo;
			c.setPubNo(pub_no);
//
//			/** 公告时间（注册时间） */
//			@Excel(name = "公告时间", readConverterExp = "注=册时间")
//			private String pubDate;
			c.setPubDate(pub_date);
//
//			/** 公告年 */
//			@Excel(name = "公告年")
//			private String pubYear;
			c.setPubYear(pub_year);
//
//			/** 公告类型（权利状态） */
//			@Excel(name = "公告类型", readConverterExp = "权=利状态")
//			private Long pubType;
			c.setPubType(pub_type);
//
//			/** 公告单位 */
//			@Excel(name = "公告单位")
//			private String pubDw;
			c.setPubDw(pub_dw);
//
//			/** 所在地域 */
//			@Excel(name = "所在地域")
//			private String area;
			c.setArea(area);
//
//			/** 保护范围（产地范围） */
//			@Excel(name = "保护范围", readConverterExp = "产=地范围")
//			private String bhfw;
			c.setBhfw(bhfw);
//
//			/** 保护范围界定文件 */
//			@Excel(name = "保护范围界定文件")
//			private String bhwj;
			c.setBhwj(bhwj);
//
//			/** 质量技术要求 */
//			@Excel(name = "质量技术要求")
//			private String zljs;
			c.setZljs(zljs);
//
//			/** 专用标志使用 */
//			@Excel(name = "专用标志使用")
//			private String zybz;
			c.setZybz(zybz);
//
//			/** 申请人 */
//			@Excel(name = "申请人")
//			private String applicant;
			c.setApplicant(applicant);
//
//			/** 申请人地址 */
//			@Excel(name = "申请人地址")
//			private String anddr;
			c.setAnddr(anddr);
//
//			/** 初审机构 */
//			@Excel(name = "初审机构")
//			private String fjig;
			c.setFjig(fjig);
//
//			/** 初审时间 */
//			@Excel(name = "初审时间")
//			private String fdate;
			c.setFdate(fdate);
//
//			/** 使用商品 */
//			@Excel(name = "使用商品")
//			private String ssp;
			c.setSsp(ssp);
//
//			/** 商品组别 */
//			@Excel(name = "商品组别")
//			private String pty;
			c.setPty(pty);
//
//			/** 申请人_省份 */
//			@Excel(name = "申请人_省份")
//			private String appProvince;
			c.setAppProvince(app_province);
//
//			/** 申请人_城市 */
//			@Excel(name = "申请人_城市")
//			private String appCity;
			c.setAppCity(app_city);
//
//			/** 申请人_区县 */
//			@Excel(name = "申请人_区县")
//			private String appCounty;
			c.setAppCounty(app_county);
//
//			/** 修改后申请人_省份 */
//			@Excel(name = "修改后申请人_省份")
//			private String modifyAppProvince;
			c.setModifyAppProvince(modify_app_province);
//
//			/** 修改后申请人_城市 */
//			@Excel(name = "修改后申请人_城市")
//			private String modifyAppCity;
			c.setModifyAppCity(modify_app_city);
//
//			/** 修改后申请人_区县 */
//			@Excel(name = "修改后申请人_区县")
//			private String modifyAppCounty;
			c.setModifyAppCounty(modify_app_county);
//
//			/** 保护范围_省份_多值 */
//			@Excel(name = "保护范围_省份_多值")
//			private String bhfwProvince;
			c.setBhfwProvince(bhfw_province);
//
//			/** 保护范围_城市_多值 */
//			@Excel(name = "保护范围_城市_多值")
//			private String bhfwCity;
			c.setBhfwCity(bhfw_city);
//
//			/** 保护范围_区县_多值 */
//			@Excel(name = "保护范围_区县_多值")
//			private String bhfwCounty;
			c.setBhfwCounty(bhfw_county);
//
//			/** 核准企业数量 */
//			@Excel(name = "核准企业数量")
//			private Long hzqyCounts;
			c.setHzqyCounts(hzqy_counts);
//
//			/** 创建批次号 */
//			@Excel(name = "创建批次号")
//			private String timeCreate;
			c.setTimeCreate(time_create);
//
//			private String appProvinceCode;
//			private String appCityCode;
//			private String appCountyCode;
//			private String modifyAppProvinceCode;
//			private String modifyAppCityCode;
//			private String modifyAppCountyCode;
//
//
//			/** 更新批次号 */
//			@Excel(name = "更新批次号")
//			private String timeUpdate;
			c.setTimeUpdate(time_update);
//
//			/** 删除标识 （0=有效;1=无效） */
//			private Integer delFlag;
//
//			/** 状态 （0=启用;1=禁用） */
//			@Excel(name = "状态   ", readConverterExp = "0==启用;1=禁用")
//			private Long status;
//			/** 附件ID */
//			@Excel(name = "附件ID")
//			private Long sysFileId;
			return c;
		}
	}
	/**
	 * 查询地理标志列表
	 *
	 * @param cIndicationInfo 地理标志
	 * @return 地理标志集合
	 * @date 2023-04-28
	 */
	@Override
	public List<CIndicationInfo> queryList(CIndicationInfo cIndicationInfo) {

//      TODO	20230710 修改逻辑
		if ("地理标志商标".equals(cIndicationInfo.getDataType())) {
			cIndicationInfo.setPubType("已注册");
		}
		if ("农产品地理标志".equals(cIndicationInfo.getDataType())) {
			cIndicationInfo.setPubType("登记公告");
		}
		if ("原产地地理标志".equals(cIndicationInfo.getDataType())) {
			cIndicationInfo.setPubType("批准公告");
		}
		
		
	
		
		if(StringUtils.isNotBlank(cIndicationInfo.getModifyAppCity())) {
//			TODO	
			BladeRegion br=bladeRegionService.selectByCityShortName(cIndicationInfo.getModifyAppCity(), "53");
			if(br!=null) {
				cIndicationInfo.setModifyAppCityCode(br.getCityCode());
				cIndicationInfo.setModifyAppCity(null);
			}
		}
		
		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(cIndicationInfo.getModifyAppCityCode()) && !"53".equals(cIndicationInfo.getModifyAppCityCode())) {
			String cityCode = cIndicationInfo.getModifyAppCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				cIndicationInfo.setModifyAppCityCode(cityCode);
			}
		}
		
		if(retEmpty) {
			return new ArrayList<CIndicationInfo>();
		}
		
		
		

		QueryWrapper<CIndicationInfo> queryWrapper = Wrappers.query();
		if (StringUtils.isNotNull(cIndicationInfo.getPid())) {
			queryWrapper.eq("pid", cIndicationInfo.getPid());
		}
		if (StringUtils.isNotNull(cIndicationInfo.getDataType())) {
			queryWrapper.eq("data_type", cIndicationInfo.getDataType());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getPron())) {
			queryWrapper.eq("pron", cIndicationInfo.getPron());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getPubNo())) {
			queryWrapper.eq("pub_no", cIndicationInfo.getPubNo());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getPubDate())) {
			queryWrapper.eq("pub_date", cIndicationInfo.getPubDate());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getPubYear())) {
			queryWrapper.eq("pub_year", cIndicationInfo.getPubYear());
		}
		if (StringUtils.isNotNull(cIndicationInfo.getPubType())) {
			queryWrapper.eq("pub_type", cIndicationInfo.getPubType());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getPubDw())) {
			queryWrapper.eq("pub_dw", cIndicationInfo.getPubDw());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getArea())) {
			queryWrapper.eq("area", cIndicationInfo.getArea());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getBhfw())) {
			queryWrapper.eq("bhfw", cIndicationInfo.getBhfw());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getBhwj())) {
			queryWrapper.eq("bhwj", cIndicationInfo.getBhwj());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getZljs())) {
			queryWrapper.eq("zljs", cIndicationInfo.getZljs());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getZybz())) {
			queryWrapper.eq("zybz", cIndicationInfo.getZybz());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getApplicant())) {
			queryWrapper.eq("applicant", cIndicationInfo.getApplicant());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getAnddr())) {
			queryWrapper.eq("anddr", cIndicationInfo.getAnddr());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getFjig())) {
			queryWrapper.eq("fjig", cIndicationInfo.getFjig());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getFdate())) {
			queryWrapper.eq("fdate", cIndicationInfo.getFdate());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getSsp())) {
			queryWrapper.eq("ssp", cIndicationInfo.getSsp());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getPty())) {
			queryWrapper.eq("pty", cIndicationInfo.getPty());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getAppProvince())) {
			queryWrapper.eq("app_province", cIndicationInfo.getAppProvince());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getAppCity())) {
			queryWrapper.eq("app_city", cIndicationInfo.getAppCity());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getAppCounty())) {
			queryWrapper.eq("app_county", cIndicationInfo.getAppCounty());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getModifyAppProvince())) {
			queryWrapper.eq("modify_app_province", cIndicationInfo.getModifyAppProvince());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getModifyAppCity())) {
			queryWrapper.eq("modify_app_city", cIndicationInfo.getModifyAppCity());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getModifyAppCityCode())) {
			queryWrapper.eq("modify_app_city_code", cIndicationInfo.getModifyAppCityCode());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getModifyAppCounty())) {
			queryWrapper.eq("modify_app_county", cIndicationInfo.getModifyAppCounty());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getBhfwProvince())) {
			queryWrapper.eq("bhfw_province", cIndicationInfo.getBhfwProvince());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getBhfwCity())) {
			queryWrapper.eq("bhfw_city", cIndicationInfo.getBhfwCity());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getBhfwCounty())) {
			queryWrapper.eq("bhfw_county", cIndicationInfo.getBhfwCounty());
		}
		if (StringUtils.isNotNull(cIndicationInfo.getHzqyCounts())) {
			queryWrapper.eq("hzqy_counts", cIndicationInfo.getHzqyCounts());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getTimeCreate())) {
			queryWrapper.eq("time_create", cIndicationInfo.getTimeCreate());
		}
		if (StringUtils.isNotEmpty(cIndicationInfo.getTimeUpdate())) {
			queryWrapper.eq("time_update", cIndicationInfo.getTimeUpdate());
		}
		if (StringUtils.isNotNull(cIndicationInfo.getStatus())) {
			queryWrapper.eq("status", cIndicationInfo.getStatus());
		}
		if (StringUtils.isNotNull(cIndicationInfo.getSysFileId())) {
			queryWrapper.eq("sys_file_id", cIndicationInfo.getSysFileId());
		}

		queryWrapper.orderByDesc("pub_date", "id");
		return this.list(queryWrapper);
	}

}
