package com.ruoyi.reportpub.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.reportpub.domain.RzgIpcStatisticsInfo;
import com.ruoyi.reportpub.mapper.RzgIpcStatisticsInfoMapper;
import com.ruoyi.reportpub.service.IRzgIpcStatisticsInfoService;
import com.ruoyi.system.service.IDIpcTypeService;

/**
 * 专利公开-主IPC统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-27
 */
@Service
public class RzgIpcStatisticsInfoServiceImpl extends ServiceImpl<RzgIpcStatisticsInfoMapper, RzgIpcStatisticsInfo> implements IRzgIpcStatisticsInfoService {

	@Autowired
	private IDIpcTypeService dIpcTypeService;
	@Override
	public List<IpcStatisticsInfoVo> listByReport(RzgIpcStatisticsInfo ipcStatisticsInfo) {
		
//		if(StringUtils.isBlank(ipcStatisticsInfo.getYear())) {
//			ipcStatisticsInfo.setYear("2022");
//		}
//		if(StringUtils.isBlank(ipcStatisticsInfo.getMonth())) {
//			ipcStatisticsInfo.setMonth("12");
//		}
        // TODO Auto-generated method stub
//		rzgIpcStatisticsInfo.setQueryIpc("ipc");

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

        // 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 (RzgIpcStatisticsInfo 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(rzgIpcStatisticsInfo.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 (IpcStatisticsInfo d : vo.getDatas().values()) {
                d.setProportion("0%");
            }
        }

        list.addAll(typeMap.values());


        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;
    
	}
	
	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 rzgIpcStatisticsInfo 专利公开-主IPC统计
     * @return 专利公开-主IPC统计集合
     * @date 2023-03-27
     */
    @Override
    public List<RzgIpcStatisticsInfo> queryList(RzgIpcStatisticsInfo rzgIpcStatisticsInfo) {
        QueryWrapper<RzgIpcStatisticsInfo> queryWrapper = Wrappers.query();
                if (  StringUtils.isNotNull(rzgIpcStatisticsInfo.getCityCode())){
                    queryWrapper.eq("city_code", rzgIpcStatisticsInfo.getCityCode());
                }
                
//                queryData=locarno
                if("locarno".equals(rzgIpcStatisticsInfo.getQueryData())) {
                	 queryWrapper.eq("patent_type", "外观设计");
                }else {
                	queryWrapper.in("patent_type", "发明","实用新型");
                }
                
                if (StringUtils.isNotBlank(rzgIpcStatisticsInfo.getPatentTypes())) {
        			String[] types = rzgIpcStatisticsInfo.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("ipc".equals(rzgIpcStatisticsInfo.getQueryData())) {
                	if( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getCreateTimeBegin())  ) {
                		queryWrapper.ge("imp_batch",rzgIpcStatisticsInfo.getCreateTimeBegin());
                	}
                	if( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getCreateTimeEnd())  ) {
                		queryWrapper.le("imp_batch",rzgIpcStatisticsInfo.getCreateTimeEnd());
                	}
                }
                
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getCityName())  ){
                    queryWrapper.eq("city_name", rzgIpcStatisticsInfo.getCityName());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getYear())  ){
                    queryWrapper.eq("year", rzgIpcStatisticsInfo.getYear());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getMonth())  ){
                    queryWrapper.eq("month", rzgIpcStatisticsInfo.getMonth());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getPatentType())  ){
                    queryWrapper.eq("patent_type", rzgIpcStatisticsInfo.getPatentType());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getApplicantType())  ){
                    queryWrapper.eq("applicant_type", rzgIpcStatisticsInfo.getApplicantType());
                }
                
                if (StringUtils.isNotBlank(rzgIpcStatisticsInfo.getApplicantTypes())) {
        			String[] types = rzgIpcStatisticsInfo.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(rzgIpcStatisticsInfo.getHigherSchool())  ){
//                    queryWrapper.eq("higher_school", rzgIpcStatisticsInfo.getHigherSchool());
//                }
//                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getResearchInstitute())  ){
//                    queryWrapper.eq("research_institute", rzgIpcStatisticsInfo.getResearchInstitute());
//                }
//                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getEnterprise())  ){
//                    queryWrapper.eq("enterprise", rzgIpcStatisticsInfo.getEnterprise());
//                }
//                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getInstitutions())  ){
//                    queryWrapper.eq("institutions", rzgIpcStatisticsInfo.getInstitutions());
//                }
//                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getIndividual())  ){
//                    queryWrapper.eq("individual", rzgIpcStatisticsInfo.getIndividual());
//                }
//                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getNumber())  ){
//                    queryWrapper.eq("number", rzgIpcStatisticsInfo.getNumber());
//                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getProportion())  ){
                    queryWrapper.eq("proportion", rzgIpcStatisticsInfo.getProportion());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getCategoryNumber())  ){
                    queryWrapper.eq("category_number", rzgIpcStatisticsInfo.getCategoryNumber());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getCategoryName())  ){
                    queryWrapper.like("category_name", rzgIpcStatisticsInfo.getCategoryName());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getDepartClass())  ){
                    queryWrapper.eq("depart_class", rzgIpcStatisticsInfo.getDepartClass());
                }
                if ( StringUtils.isNotEmpty(rzgIpcStatisticsInfo.getDepartClassName())  ){
                    queryWrapper.like("depart_class_name", rzgIpcStatisticsInfo.getDepartClassName());
                }
                if (  StringUtils.isNotNull(rzgIpcStatisticsInfo.getStatus())){
                    queryWrapper.eq("status", rzgIpcStatisticsInfo.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }
}
