package com.ruoyi.reportrzs.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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.constant.IpcType;
import com.ruoyi.common.constant.PatentType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.report.vo.IpcStatisticsInfo;
import com.ruoyi.report.vo.IpcStatisticsInfoVo;
import com.ruoyi.reportrzs.domain.RzsIpcStatisticsInfo;
import com.ruoyi.reportrzs.mapper.RzsIpcStatisticsInfoMapper;
import com.ruoyi.reportrzs.service.IRzsIpcStatisticsInfoService;
import com.ruoyi.system.domain.DIpcType;
import com.ruoyi.system.service.IDIpcTypeService;

/**
 * 专利授权-主IPC统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-27
 */
@Service
public class RzsIpcStatisticsInfoServiceImpl extends ServiceImpl<RzsIpcStatisticsInfoMapper, RzsIpcStatisticsInfo> implements IRzsIpcStatisticsInfoService {

	@Autowired
	private IDIpcTypeService dIpcTypeService;
	
	@Override
	public List<IpcStatisticsInfoVo> listByReport(RzsIpcStatisticsInfo ipcStatisticsInfo) {

        // TODO Auto-generated method stub
//		rzlIpcStatisticsInfo.setQueryIpc("ipc");

		
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(ipcStatisticsInfo.getCityCode()) && !"53".equals(ipcStatisticsInfo.getCityCode())) {
			String cityCode = ipcStatisticsInfo.getCityCode().trim();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode) ) {
					retEmpty=true;
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				ipcStatisticsInfo.setCityCode(cityCode);
			}
		}
		
		
        String cityCode = null;
        if (StringUtils.isNotBlank(ipcStatisticsInfo.getCityCode()) && !"53".equals(ipcStatisticsInfo.getCityCode())) {
            cityCode = ipcStatisticsInfo.getCityCode().trim();
        }
        ipcStatisticsInfo.setCityCode(cityCode);
        
        
        List<RzsIpcStatisticsInfo> dataList =new ArrayList<RzsIpcStatisticsInfo>();
        if(!retEmpty) {
        	dataList = queryList(ipcStatisticsInfo);
        }
        
        for(RzsIpcStatisticsInfo data:dataList) {
        	if(StringUtils.isBlank(data.getYear()) && StringUtils.isNotBlank(data.getImpBatch())) {
        		data.setYear(data.getImpBatch().trim().substring(0, 4));
        	}
        }

        // key:type
        Map<String, IpcStatisticsInfoVo> typeMap = new LinkedHashMap<String, IpcStatisticsInfoVo>();

//		String queryData:'locarno',
        String queryData = ipcStatisticsInfo.getQueryData();

        // patentTypeCode,val:total
//        Map<String, Integer> typeCodePatentTotal = new LinkedHashMap<String, Integer>();

        List<IpcStatisticsInfoVo> list = new ArrayList<IpcStatisticsInfoVo>();
        for (RzsIpcStatisticsInfo data : dataList) {
            String patentType = data.getPatentType();
            String patentTypeCode = getPatentTypeCode(patentType);
            String type = "ipc".equals(ipcStatisticsInfo.getQueryIpc()) ? data.getIpcType() : data.getIpcSubType();
            if (StringUtils.isBlank(type)) {
                continue;
            }
            if ("ipc".equals(queryData) && "ipc".equals(ipcStatisticsInfo.getQueryIpc())) {
                if (IpcType.valueOf(data.getIpcType()) == null) {
                    continue;
                }
            }

            data.setType(type);

            IpcStatisticsInfoVo vo = null;
            if (!typeMap.containsKey(type)) {
                vo = new IpcStatisticsInfoVo(type);

                if ("locarno".equals(queryData) && StringUtils.isNotBlank(type)) {
                    vo.setTypeName(data.getIpcTypeName());
                }
                if ("ipc".equals(queryData)) {
                    if (!"ipc".equals(ipcStatisticsInfo.getQueryIpc()) && StringUtils.isNotBlank(data.getIpcSubTypeName())) {
                        vo.setTypeName(data.getIpcSubTypeName());
                    }
//					if(!"ipc".equals(ipcStatisticsInfo.getQueryIpc()) && StringUtils.isNotBlank(type)) {
//						vo.setTypeName(type);
//						DIpcType dIpcType=dIpcTypeService.getDIpcTypeByCode(type);
//						if(dIpcType!=null) {
//							vo.setTypeName(dIpcType.getName());
//						}
//					}
                }

                typeMap.put(type, vo);
            } else {
                vo = typeMap.get(type);
            }
            String key = type + "_" + patentTypeCode;
//			typePatentMap.put(key, data);

//            if (!typeCodePatentTotal.containsKey(key)) {
//                typeCodePatentTotal.put(key, 0);
//            }
//
//            int total = typeCodePatentTotal.get(key);

//            data.setNumber(0);
//            if (data.getHigherSchool() != null) {
//                data.setNumber(data.getNumber() + data.getHigherSchool());
//            }
//            if (data.getResearchInstitute() != null) {
//                data.setNumber(data.getNumber() + data.getResearchInstitute());
//            }
//            if (data.getEnterprise() != null) {
//                data.setNumber(data.getNumber() + data.getEnterprise());
//            }
//            if (data.getInstitutions() != null) {
//                data.setNumber(data.getNumber() + data.getInstitutions());
//            }
//            if (data.getIndividual() != null) {
//                data.setNumber(data.getNumber() + data.getIndividual());
//            }

//            total = total + data.getNumber();

//			if (!"ipc".equals(rzlIpcStatisticsInfo.getQueryIpc())) {
//				vo.getDatas().put(patentType, data);
//			} else {

            IpcStatisticsInfo dataSum = null;
            if (vo.getDatas().containsKey(patentTypeCode)) {
                dataSum = vo.getDatas().get(patentTypeCode);

//                dataSum.setNumber(dataSum.getNumber() + data.getNumber());
                dataSum.setHigherSchool(dataSum.getHigherSchool() + data.getHigherSchool());
                dataSum.setResearchInstitute(dataSum.getResearchInstitute() + data.getResearchInstitute());
                dataSum.setEnterprise(dataSum.getEnterprise() + data.getEnterprise());
                dataSum.setInstitutions(dataSum.getInstitutions() + data.getInstitutions());
                dataSum.setIndividual(dataSum.getIndividual() + data.getIndividual());

            } else {
                dataSum = new IpcStatisticsInfo();

                dataSum.setType(type);
                dataSum.setPatentType(patentType);
                dataSum.setNumber(0L);
                dataSum.setHigherSchool(0L);
                dataSum.setResearchInstitute(0L);
                dataSum.setEnterprise(0L);
                dataSum.setInstitutions(0L);
                dataSum.setIndividual(0L);

                vo.getDatas().put(patentTypeCode, dataSum);
            }

//            dataSum.setNumber(dataSum.getNumber() + data.getNumber());

//			}

//			typeCodePatentTotal.put(patentTypeCode, total);

//            typeCodePatentTotal.put(key, total);

        }

        // 计算总数
//        for (IpcStatisticsInfoVo vo : typeMap.values()) {
//            for (RzlIpcStatisticsInfo d : vo.getDatas().values()) {
//                d.setNumber(0L);
//                if (d.getHigherSchool() != null) {
//                    d.setNumber(d.getNumber() + d.getHigherSchool());
//                }
//                if (d.getResearchInstitute() != null) {
//                    d.setNumber(d.getNumber() + d.getResearchInstitute());
//                }
//                if (d.getEnterprise() != null) {
//                    d.setNumber(d.getNumber() + d.getEnterprise());
//                }
//                if (d.getInstitutions() != null) {
//                    d.setNumber(d.getNumber() + d.getInstitutions());
//                }
//                if (d.getIndividual() != null) {
//                    d.setNumber(d.getNumber() + d.getIndividual());
//                }
//            }
//        }

        // 计算占比
//        int allTotile = 0;
//        for (IpcStatisticsInfoVo vo : typeMap.values()) {
//            for (RzlIpcStatisticsInfo d : vo.getDatas().values()) {
//                allTotile = allTotile + d.getNumber();
//            }
//        }
        for (IpcStatisticsInfoVo vo : typeMap.values()) {
            for (IpcStatisticsInfo d : vo.getDatas().values()) {
                d.setProportion("0%");
//				String patentTypeCode=getPatentTypeCode(d.getPatentType());
//				String key = d.getType() + "_" + patentTypeCode;
//				int allTotile = 0;
//				if (typeCodePatentTotal.containsKey(key)) {
//					total = typeCodePatentTotal.get(key);
//				}

//				if (typeCodePatentTotal.containsKey(key)) {
//					total = typeCodePatentTotal.get(key);
//				}
//                if (allTotile > 0) {
////					if (d.getNumber() != null) {
////						double prop = (d.getNumber() * 100 + 0.0) / total;
////						d.setProportion(String.format("%.2f", prop) + "%");
////					}
//                    if (d.getNumber() != null) {
//                        double prop = (d.getNumber() * 100 + 0.0) / allTotile;
//                        d.setProportion(String.format("%.2f", prop) + "%");
//                    }
//                }
            }
        }

        list.addAll(typeMap.values());

//        IpcStatisticsInfoVo sum = new IpcStatisticsInfoVo();
//        sum.setType("total");
//        if ("ipc".equals(queryData)) {
//            sum.setTypeName("A-H总计");
//        } else {
//            sum.setTypeName("总计");
//        }
//        Map<String, RzlIpcStatisticsInfo> datas = new HashMap<String, RzlIpcStatisticsInfo>();
//        sum.setDatas(datas);

        for (IpcStatisticsInfoVo vo : list) {
        	if(vo.getDatas()==null || vo.getDatas().isEmpty()) {
        		continue;
        	}
        	for(IpcStatisticsInfo d:vo.getDatas().values()) {
              d.setNumber(0L);
              if (d.getHigherSchool() != null) {
                  d.setNumber(d.getNumber() + d.getHigherSchool());
              }
              if (d.getResearchInstitute() != null) {
                  d.setNumber(d.getNumber() + d.getResearchInstitute());
              }
              if (d.getEnterprise() != null) {
                  d.setNumber(d.getNumber() + d.getEnterprise());
              }
              if (d.getInstitutions() != null) {
                  d.setNumber(d.getNumber() + d.getInstitutions());
              }
              if (d.getIndividual() != null) {
                  d.setNumber(d.getNumber() + d.getIndividual());
              }
        	}

        }
        // 排序
//        Collections.sort(list, new Comparator<IpcStatisticsInfoVo>() {
//            @Override
//            public int compare(IpcStatisticsInfoVo o1, IpcStatisticsInfoVo o2) {
//                // TODO Auto-generated method stub
//                return o1.getType().compareTo(o2.getType());
//            }
//        });
    	Collections.sort(list, new Comparator<IpcStatisticsInfoVo>() {
			@Override
			public int compare(IpcStatisticsInfoVo o1, IpcStatisticsInfoVo o2) {
				if("locarno".equals(queryData)) {
					try {
						return Integer.parseInt(o1.getType())-Integer.parseInt(o2.getType());
					} catch (Exception e) {
						return o1.getType().compareTo(o2.getType());
					}
				}else {
					return o1.getType().compareTo(o2.getType());
				}
			
			}
		});
        return list;
    
	}
	public List<IpcStatisticsInfoVo> listByReport_bak(RzsIpcStatisticsInfo ipcStatisticsInfo) {
		// TODO Auto-generated method stub
//		rzlIpcStatisticsInfo.setQueryIpc("ipc");
		
		String cityCode = null;
        if (StringUtils.isNotBlank(ipcStatisticsInfo.getCityCode()) && !"53".equals(ipcStatisticsInfo.getCityCode())) {
            cityCode = ipcStatisticsInfo.getCityCode().trim();
        }
        ipcStatisticsInfo.setCityCode(cityCode);
        
        
		List<RzsIpcStatisticsInfo> dataList = queryList(ipcStatisticsInfo);
		

		// key:type
		Map<String, IpcStatisticsInfoVo> typeMap = new LinkedHashMap<String, IpcStatisticsInfoVo>();

		// patentTypeCode,val:total
		Map<String, Integer> typeCodePatentTotal = new LinkedHashMap<String, Integer>();

		List<IpcStatisticsInfoVo> list = new ArrayList<IpcStatisticsInfoVo>();
		for (RzsIpcStatisticsInfo data : dataList) {
			String patentType = data.getPatentType();
			String patentTypeCode=getPatentTypeCode(patentType);
			String type = "ipc".equals(ipcStatisticsInfo.getQueryIpc()) ? data.getIpcType() : data.getIpcSubType();
			
			if("ipc".equals(ipcStatisticsInfo.getQueryIpc())) {
				if(IpcType.valueOf(data.getIpcType())==null) {
					continue;
				}
			}
			
			data.setType(type);
			
			IpcStatisticsInfoVo vo = null;
			if (!typeMap.containsKey(type)) {
				vo = new IpcStatisticsInfoVo(type);
				
				if(!"ipc".equals(ipcStatisticsInfo.getQueryIpc()) && StringUtils.isNotBlank(type)) {
					if(!"ABCDEFGH".contains(type.charAt(0)+"")) {
						continue;
					}
					DIpcType dIpcType=dIpcTypeService.getDIpcTypeByCode(type);
					if(dIpcType!=null) {
						vo.setTypeName(dIpcType.getName());
					}
					
					
				}
				
				typeMap.put(type, vo);
			} else {
				vo = typeMap.get(type);

			}
			String key = type + "_" + patentTypeCode;
//			typePatentMap.put(key, data);

			if (!typeCodePatentTotal.containsKey(patentTypeCode)) {
				typeCodePatentTotal.put(patentTypeCode, 0);
			}

			int total = typeCodePatentTotal.get(patentTypeCode);

			data.setNumber(0);
			if (data.getHigherSchool() != null) {
				data.setNumber(data.getNumber() + data.getHigherSchool());
			}
			if (data.getResearchInstitute() != null) {
				data.setNumber(data.getNumber() + data.getResearchInstitute());
			}
			if (data.getEnterprise() != null) {
				data.setNumber(data.getNumber() + data.getEnterprise());
			}
			if (data.getInstitutions() != null) {
				data.setNumber(data.getNumber() + data.getInstitutions());
			}
			if (data.getIndividual() != null) {
				data.setNumber(data.getNumber() + data.getIndividual());
			}

			total = total + data.getNumber();

//			if (!"ipc".equals(rzlIpcStatisticsInfo.getQueryIpc())) {
//				vo.getDatas().put(patentType, data);
//			} else {

			IpcStatisticsInfo dataSum = null;
				if (vo.getDatas().containsKey(patentTypeCode)) {
					dataSum = vo.getDatas().get(patentTypeCode);
					
					dataSum.setNumber(dataSum.getNumber()+data.getNumber());
					dataSum.setHigherSchool(dataSum.getHigherSchool()+data.getHigherSchool());
					dataSum.setResearchInstitute(dataSum.getResearchInstitute()+data.getResearchInstitute());
					dataSum.setEnterprise(dataSum.getEnterprise()+data.getEnterprise());
					dataSum.setInstitutions(dataSum.getInstitutions()+data.getInstitutions());
					dataSum.setIndividual(dataSum.getIndividual()+data.getIndividual());
					
				} else {
					dataSum = new IpcStatisticsInfo();

					dataSum.setType(type);
					dataSum.setPatentType(patentType);
					dataSum.setNumber(0L);
					dataSum.setHigherSchool(0L);
					dataSum.setResearchInstitute(0L);
					dataSum.setEnterprise(0L);
					dataSum.setInstitutions(0L);
					dataSum.setIndividual(0L);

					vo.getDatas().put(patentTypeCode, dataSum);
				}

				dataSum.setNumber(dataSum.getNumber() + data.getNumber());

//			}

			typeCodePatentTotal.put(patentTypeCode, total);

		}
		
		//计算占比
		for (IpcStatisticsInfoVo vo : typeMap.values()) {
			for (IpcStatisticsInfo d : vo.getDatas().values()) {
				d.setProportion("0%");
				String patentTypeCode=getPatentTypeCode(d.getPatentType());
				String key = d.getType() + "_" + patentTypeCode;
				int total = 0;
				if (typeCodePatentTotal.containsKey(patentTypeCode)) {
					total = typeCodePatentTotal.get(patentTypeCode);
				}
				if (total > 0) {
					if (d.getNumber() != null) {
						double prop = (d.getNumber() * 100 + 0.0) / total;
						d.setProportion(String.format("%.2f", prop) + "%");
					}
				}
			}
		}
		
		
		list.addAll(typeMap.values());
		
		//排序
		Collections.sort(list, new Comparator<IpcStatisticsInfoVo>() {
			@Override
			public int compare(IpcStatisticsInfoVo o1, IpcStatisticsInfoVo o2) {
				// TODO Auto-generated method stub
				return o1.getType().compareTo(o2.getType());
			}
		});
		return list;
	}
	
	private String getPatentTypeCode(String patentName) {
		if(patentName.contains("发明")) {
			return PatentType.INVENTION_PATENT.getTypeCode();
		}else if(patentName.contains("实用")) {
			return PatentType.MODEL_UTILITY.getTypeCode();
		}else if(patentName.contains("外观")) {
			return PatentType.APPEARANCE_PATENT.getTypeCode();
		}
		return "unknow";
	}

	
	
    /**
     * 查询专利授权-主IPC统计列表
     *
     * @param rzsIpcStatisticsInfo 专利授权-主IPC统计
     * @return 专利授权-主IPC统计集合
     * @date 2023-03-27
     */
    @Override
    public List<RzsIpcStatisticsInfo> queryList(RzsIpcStatisticsInfo rzsIpcStatisticsInfo) {
        QueryWrapper<RzsIpcStatisticsInfo> queryWrapper = Wrappers.query();
                if (  StringUtils.isNotNull(rzsIpcStatisticsInfo.getCityCode())){
                    queryWrapper.eq("city_code", rzsIpcStatisticsInfo.getCityCode());
                }
                
//              queryData=locarno
        		if ("locarno".equals(rzsIpcStatisticsInfo.getQueryData())) {
        			queryWrapper.eq("patent_type", "外观设计");
        		} else {
        			queryWrapper.in("patent_type", "发明", "实用新型");
        		}
        		if (StringUtils.isNotBlank(rzsIpcStatisticsInfo.getPatentTypes())) {
        			String[] types = rzsIpcStatisticsInfo.getPatentTypes().split(",");
        			List<String> typeList = new ArrayList<String>();
        			for (String tp : types) {
        				if (StringUtils.isNotBlank(tp)) {
        					PatentType patentType = PatentType.valueOf(tp.trim());
        					if (patentType != null) {
        						typeList.add(patentType.getTypeName());
        					}

        				}
        			}
        			queryWrapper.in("patent_type", typeList);
        		}
        		 if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getCreateTimeBegin())  ){
                     queryWrapper.ge("imp_batch", rzsIpcStatisticsInfo.getCreateTimeBegin());
                 } 
        		 if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getCreateTimeEnd())  ){
                     queryWrapper.le("imp_batch", rzsIpcStatisticsInfo.getCreateTimeEnd());
                 }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getCityName())  ){
                    queryWrapper.like("city_name", rzsIpcStatisticsInfo.getCityName());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getYear())  ){
                    queryWrapper.eq("year", rzsIpcStatisticsInfo.getYear());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getMonth())  ){
                    queryWrapper.eq("month", rzsIpcStatisticsInfo.getMonth());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getPatentType())  ){
                    queryWrapper.eq("patent_type", rzsIpcStatisticsInfo.getPatentType());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getApplicantType())  ){
                    queryWrapper.eq("applicant_type", rzsIpcStatisticsInfo.getApplicantType());
                }
                
                if (StringUtils.isNotBlank(rzsIpcStatisticsInfo.getApplicantTypes())) {
        			String[] types = rzsIpcStatisticsInfo.getApplicantTypes().split(",");
        			List<String> typeList = new ArrayList<String>();
        			for (String tp : types) {
        				if (StringUtils.isNotBlank(tp)) {
        					ApplicantType patentType = ApplicantType.valueOf(tp.trim());
        					if (patentType != null) {
        						typeList.add(patentType.getTypeName());
        					}
        				}
        			}
        			queryWrapper.in("applicant_type", typeList);
        		}
//                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getHigherSchool())  ){
//                    queryWrapper.eq("higher_school", rzsIpcStatisticsInfo.getHigherSchool());
//                }
//                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getResearchInstitute())  ){
//                    queryWrapper.eq("research_institute", rzsIpcStatisticsInfo.getResearchInstitute());
//                }
//                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getEnterprise())  ){
//                    queryWrapper.eq("enterprise", rzsIpcStatisticsInfo.getEnterprise());
//                }
//                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getInstitutions())  ){
//                    queryWrapper.eq("institutions", rzsIpcStatisticsInfo.getInstitutions());
//                }
//                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getIndividual())  ){
//                    queryWrapper.eq("individual", rzsIpcStatisticsInfo.getIndividual());
//                }
//                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getNumber())  ){
//                    queryWrapper.eq("number", rzsIpcStatisticsInfo.getNumber());
//                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getProportion())  ){
                    queryWrapper.eq("proportion", rzsIpcStatisticsInfo.getProportion());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getCategoryNumber())  ){
                    queryWrapper.eq("category_number", rzsIpcStatisticsInfo.getCategoryNumber());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getCategoryName())  ){
                    queryWrapper.like("category_name", rzsIpcStatisticsInfo.getCategoryName());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getDepartClass())  ){
                    queryWrapper.eq("depart_class", rzsIpcStatisticsInfo.getDepartClass());
                }
                if ( StringUtils.isNotEmpty(rzsIpcStatisticsInfo.getDepartClassName())  ){
                    queryWrapper.like("depart_class_name", rzsIpcStatisticsInfo.getDepartClassName());
                }
                if (  StringUtils.isNotNull(rzsIpcStatisticsInfo.getStatus())){
                    queryWrapper.eq("status", rzsIpcStatisticsInfo.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

}
