package com.ruoyi.hv.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
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.constant.ApplicantType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hv.domain.RzgClassifiedStatisticsInfo;
import com.ruoyi.hv.mapper.RzgClassifiedStatisticsInfoMapper;
import com.ruoyi.hv.service.IRzgClassifiedStatisticsInfoService;
import com.ruoyi.hv.vo.RzgClassifiedStatisticsInfoVo;
import com.ruoyi.hv.vo.RzgClassifiedStatisticsInfoVo.Item;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.utils.BladeRegionUtils;

/**
 * 高价值专利-分类统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-02
 */
@Service
public class RzgClassifiedStatisticsInfoServiceImpl extends ServiceImpl<RzgClassifiedStatisticsInfoMapper, RzgClassifiedStatisticsInfo>
		implements IRzgClassifiedStatisticsInfoService {

	@Autowired
	private RzgClassifiedStatisticsInfoMapper rzgClassifiedStatisticsInfoMapper;
	@Autowired
	private IBladeRegionService bladeRegionService;

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

	private List<RzgClassifiedStatisticsInfoVo> getOneYear(RzgClassifiedStatisticsInfo rzgClassifiedStatisticsInfo, String year) {

		String cityCode = null;

		if (StringUtils.isNotBlank(rzgClassifiedStatisticsInfo.getCityCode()) && !"53".equals(rzgClassifiedStatisticsInfo.getCityCode())) {
			cityCode = rzgClassifiedStatisticsInfo.getCityCode().trim();
		}
		rzgClassifiedStatisticsInfo.setCityCode(cityCode);

		rzgClassifiedStatisticsInfo.setYear(year);

		// List<Map> mapList =
		// rzgClassifiedStatisticsInfoMapper.listByReport(rzgClassifiedStatisticsInfo.getCityName());
		List<Map> mapList = rzgClassifiedStatisticsInfoMapper.listByReport(rzgClassifiedStatisticsInfo);

//        ,sum(case when hv_seis_press='1' then 1 else 0 end ) hv_seis_press
//        ,sum(case when hv_keep10_press='1' then 1 else 0 end ) hv_keep10_press
//        ,sum(case when hv_have_overseas_press='1' then 1 else 0 end ) hv_have_overseas_press
//        ,sum(case when hv_high_pledge_press='1' then 1 else 0 end ) hv_high_pledge_press
//        ,sum(case when hv_technology_award_press='1' then 1 else 0 end ) hv_technology_award_press
		// 处理非本区划
		boolean needSumNotThisArea = false;
		if (StringUtils.isNotBlank(cityCode)) {
			needSumNotThisArea = true;
		}
		List<Map> notThisAreaList = new ArrayList<Map>();
		Map<String, Map> alreadyNotThisArea = new HashMap<String, Map>();
		if (needSumNotThisArea && mapList != null && !mapList.isEmpty()) {
			List<Map> newList = new ArrayList<Map>();
			BladeRegionUtils.setNotThisArea(mapList, cityCode);
//					List<String> allCodes=bladeRegionService.getAllAreaCode();
//					Map<String,Boolean>alreadyMap=new HashMap<String,Boolean>();
			for (Map map : mapList) {
				String area_code = getStr(map, "area_code");
//						if (StringUtils.isBlank(area_code) || !area_code.startsWith(cityCode)) {
				if (StringUtils.isNotBlank(cityCode) && isNotThisArea(map)) {
					// 合并到非本区化
					margeNotThisArea(notThisAreaList, map, alreadyNotThisArea, "area_code", "area_name", new String[] { "appli_type" }, new String[] {
							"total_cnt", "hv_seis_press", "hv_keep10_press", "hv_have_overseas_press", "hv_high_pledge_press", "hv_technology_award_press" });
				} else {
					newList.add(map);// 不是非本区划
				}
			}
			mapList = newList;
			mapList.addAll(notThisAreaList);
		}

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

		// key:areaName
		Map<String, RzgClassifiedStatisticsInfoVo> areaMap = new LinkedHashMap<String, RzgClassifiedStatisticsInfoVo>();

		for (Map itemMap : mapList) {

			String appliType = getStr(itemMap, "appli_type");
			ApplicantType at = ApplicantType.getByName(appliType);
			if (at != null) {
				appliType = at.getTypeCode();
			}

			long total = 0;

			RzgClassifiedStatisticsInfoVo.Item item = new RzgClassifiedStatisticsInfoVo.Item();
//			item.setTotalCnt(getInt(itemMap, "hv_total"));
			item.setHvSeisPress(getLong(itemMap, "hv_seis_press"));
			item.setHvHaveOverseasPress(getLong(itemMap, "hv_have_overseas_press"));
			item.setHvKeep10Press(getLong(itemMap, "hv_keep10_press"));
			item.setHvHighPledgePress(getLong(itemMap, "hv_high_pledge_press"));
			item.setHvTechnologyAwardPress(getLong(itemMap, "hv_technology_award_press"));

//			@TableField(exist =false)
//		    private String industryEmergIndustryQ;
			if ("1".equals(rzgClassifiedStatisticsInfo.getIndustryEmergIndustryQ())) {
				total = total + item.getHvSeisPress();
			}
//
//		    /**
//		     * 在海外有同族专利
//		     */
//		@TableField(exist =false)
//		    private String overseasCongenerPatentQ;
			if ("1".equals(rzgClassifiedStatisticsInfo.getOverseasCongenerPatentQ())) {
				total = total + item.getHvHaveOverseasPress();
			}
//
//		    /**
//		     * 维持年限超十年
//		     */
//		@TableField(exist =false)
//		    private String maintenanceTenYearQ;
			if ("1".equals(rzgClassifiedStatisticsInfo.getMaintenanceTenYearQ())) {
				total = total + item.getHvKeep10Press();
			}
//
//		    /**
//		     * 存在质押记录
//		     */
//		@TableField(exist =false)
//		    private String pledgeRecordQ;
			if ("1".equals(rzgClassifiedStatisticsInfo.getPledgeRecordQ())) {
				total = total + item.getHvHighPledgePress();
			}
//
//		    /**
//		     * 获得国家科技奖或者中国专利奖
//		     */
//		@TableField(exist =false)
//		    private String nationalScienceAwardQ;
			if ("1".equals(rzgClassifiedStatisticsInfo.getNationalScienceAwardQ())) {
				total = total + item.getHvTechnologyAwardPress();
			}

			item.setGrowth("-");
			item.setTotalCnt(total);

			String areaName = getStr(itemMap, "area_name");
			String areaCode = getStr(itemMap, "area_code");
			RzgClassifiedStatisticsInfoVo vo = null;
			if (areaMap.containsKey(areaName)) {
				vo = areaMap.get(areaName);
				if (vo.getItems().containsKey(appliType)) {
					Item old = vo.getItems().get(appliType);
					old.setTotalCnt(old.getTotalCnt() + item.getTotalCnt());
					old.setHvSeisPress(old.getHvSeisPress() + item.getHvSeisPress());
					old.setHvHaveOverseasPress(old.getHvHaveOverseasPress() + item.getHvHaveOverseasPress());
					old.setHvKeep10Press(old.getHvKeep10Press() + item.getHvKeep10Press());
					old.setHvHighPledgePress(old.getHvHighPledgePress() + item.getHvHighPledgePress());
					old.setHvTechnologyAwardPress(old.getHvTechnologyAwardPress() + item.getHvTechnologyAwardPress());
				} else {
					vo.getItems().put(appliType, item);
				}

			} else {
				vo = new RzgClassifiedStatisticsInfoVo();
				vo.setItems(new LinkedHashMap<String, RzgClassifiedStatisticsInfoVo.Item>());

//				IME 企业  OT 机关团体  PE 个人SRI科研机构 UC 大专院校   OTH 其他
				vo.getItems().put("IME", new Item());
				vo.getItems().put("OT", new Item());
				vo.getItems().put("PE", new Item());
				vo.getItems().put("SRI", new Item());
				vo.getItems().put("UC", new Item());

				vo.setYear(year);
				vo.setAreaName(areaName);
				vo.setAreaCode(areaCode);
				areaMap.put(areaName, vo);

				vo.getItems().put(appliType, item);

				list.add(vo);

			}

		}

		// 排序
		Map<String, RzgClassifiedStatisticsInfoVo> map = new HashMap<String, RzgClassifiedStatisticsInfoVo>();
		for (RzgClassifiedStatisticsInfoVo vo : list) {
			String areaName = BladeRegionUtils.getDistrictShortName(vo.getAreaCode());
			if (areaName != null) {
				vo.setAreaName(areaName);
			}
			map.put(vo.getAreaCode(), vo);
		}
		List<String> sortedCodes = BladeRegionUtils.sortedKey(map.keySet());
		List<RzgClassifiedStatisticsInfoVo> list2 = new ArrayList<RzgClassifiedStatisticsInfoVo>();
		for (String key : sortedCodes) {
			list2.add(map.get(key));
		}

		return list2;

	}

	@Override
	public List<RzgClassifiedStatisticsInfoVo> listByReport(RzgClassifiedStatisticsInfo rzgClassifiedStatisticsInfo) {
		String year = rzgClassifiedStatisticsInfo.getYear();
		if (StringUtils.isBlank(year)) {
			year = "2022";
		}
		String lastYear = (Integer.parseInt(year) - 1) + "";

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

		List<RzgClassifiedStatisticsInfoVo> curr = getOneYear(rzgClassifiedStatisticsInfo, year);

		List<RzgClassifiedStatisticsInfoVo> last = getOneYear(rzgClassifiedStatisticsInfo, lastYear);

		List<RzgClassifiedStatisticsInfoVo> list = new ArrayList();
		list.addAll(curr);

		for (RzgClassifiedStatisticsInfoVo vo : curr) {
			String areaName = vo.getAreaName();
			for (Map.Entry<String, Item> ent : vo.getItems().entrySet()) {
				String type = ent.getKey();
				Item item = ent.getValue();
				Item lastItem = findItem(areaName, type, last);
				if (lastItem != null && lastItem.getTotalCnt() != null && lastItem.getTotalCnt() > 0) {
					if (item.getTotalCnt() == null) {
						item.setTotalCnt(0L);
					}
					item.setLastTotalCnt(0L);
					double growth = (item.getTotalCnt() - lastItem.getTotalCnt() + 0.0) / lastItem.getTotalCnt() * 100;
					item.setGrowth(String.format("%.2f", growth) + "%");
				}

			}
		}
		return list;

	}

	private Item findItem(String area, String type, List<RzgClassifiedStatisticsInfoVo> list) {
		if (StringUtils.isBlank(type) || StringUtils.isBlank(area) || list == null || list.isEmpty()) {
			return null;
		}

		for (RzgClassifiedStatisticsInfoVo vo : list) {
			if (area.equals(vo.getAreaName())) {
				if (vo.getItems().containsKey(type)) {
					return vo.getItems().get(type);
				}
			}
		}
		return null;
	}

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

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

}
