package com.ruoyi.report.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.domain.RzlIpcStatisticsInfo;
import com.ruoyi.report.mapper.RzlIpcStatisticsInfoMapper;
import com.ruoyi.report.service.IRzlIpcStatisticsInfoService;
import com.ruoyi.report.vo.ClassStatisticsInfoVo;
import com.ruoyi.report.vo.IpcStatisticsInfo;
import com.ruoyi.report.vo.IpcStatisticsInfoVo;
import com.ruoyi.system.service.IDIpcTypeService;

/**
 * 专利有效-主IPC统计Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-26
 */
@Service
public class RzlIpcStatisticsInfoServiceImpl extends ServiceImpl<RzlIpcStatisticsInfoMapper, RzlIpcStatisticsInfo>
		implements IRzlIpcStatisticsInfoService {

	@Autowired
	private RzlIpcStatisticsInfoMapper rzlIpcStatisticsInfoMapper;
	@Autowired
	private IDIpcTypeService dIpcTypeService;

	@Override
	public List<IpcStatisticsInfoVo> listByReport(RzlIpcStatisticsInfo 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();
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cc=SecurityUtils.needFilterByCityCode();
				if(!cc.equals(cityCode)) {
					return new ArrayList<IpcStatisticsInfoVo>();
				}
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				cityCode=SecurityUtils.needFilterByCityCode();
			}
		}
		
		
		ipcStatisticsInfo.setCityCode(cityCode);
		List<RzlIpcStatisticsInfo> 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 (RzlIpcStatisticsInfo 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());
				}
			}

		}
//		queryData=locarno
		// 排序
		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;
	}

	@Override
	public RzlIpcStatisticsInfo queryTotalNum(RzlIpcStatisticsInfo ipcStatisticsInfo) {
		String cityCode = null;
		if (StringUtils.isNotBlank(ipcStatisticsInfo.getCityCode()) && !"53".equals(ipcStatisticsInfo.getCityCode())) {
			cityCode = ipcStatisticsInfo.getCityCode().trim();
		}
		ipcStatisticsInfo.setCityCode(cityCode);

		return rzlIpcStatisticsInfoMapper.queryTotalNum(ipcStatisticsInfo);
	}

	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 rzlIpcStatisticsInfo 专利有效-主IPC统计
	 * @return 专利有效-主IPC统计集合
	 * @date 2023-03-26
	 */
	@Override
	public List<RzlIpcStatisticsInfo> queryList(RzlIpcStatisticsInfo rzlIpcStatisticsInfo) {
		QueryWrapper<RzlIpcStatisticsInfo> queryWrapper = Wrappers.query();
		if (StringUtils.isNotNull(rzlIpcStatisticsInfo.getCityCode())) {
			queryWrapper.eq("city_code", rzlIpcStatisticsInfo.getCityCode());
		}
		if (StringUtils.isNotBlank(rzlIpcStatisticsInfo.getPatentTypes())) {
			String[] types = rzlIpcStatisticsInfo.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);
		}
		queryWrapper.isNotNull("city_name");
		queryWrapper.isNotNull("ipc_type");
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getCityName())) {
			queryWrapper.like("city_name", rzlIpcStatisticsInfo.getCityName());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getYear())) {
			queryWrapper.eq("year", rzlIpcStatisticsInfo.getYear());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getMonth())) {
			queryWrapper.eq("month", rzlIpcStatisticsInfo.getMonth());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getPatentType())) {
			queryWrapper.eq("patent_type", rzlIpcStatisticsInfo.getPatentType());
		}

//      queryData=locarno
		if ("locarno".equals(rzlIpcStatisticsInfo.getQueryData())) {
			queryWrapper.eq("patent_type", "外观设计");
		} else {
			queryWrapper.in("patent_type", "发明", "实用新型");
		}

		if (StringUtils.isNotBlank(rzlIpcStatisticsInfo.getApplicantTypes())) {
			String[] types = rzlIpcStatisticsInfo.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(rzlIpcStatisticsInfo.getApplicantType())) {
			queryWrapper.eq("applicant_type", rzlIpcStatisticsInfo.getApplicantType());
		}
//		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getHigherSchool())) {
//			queryWrapper.eq("higher_school", rzlIpcStatisticsInfo.getHigherSchool());
//		}
//		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getResearchInstitute())) {
//			queryWrapper.eq("research_institute", rzlIpcStatisticsInfo.getResearchInstitute());
//		}
//		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getEnterprise())) {
//			queryWrapper.eq("enterprise", rzlIpcStatisticsInfo.getEnterprise());
//		}
//		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getInstitutions())) {
//			queryWrapper.eq("institutions", rzlIpcStatisticsInfo.getInstitutions());
//		}
//		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getIndividual())) {
//			queryWrapper.eq("individual", rzlIpcStatisticsInfo.getIndividual());
//		}
//		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getNumber())) {
//			queryWrapper.eq("number", rzlIpcStatisticsInfo.getNumber());
//		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getProportion())) {
			queryWrapper.eq("proportion", rzlIpcStatisticsInfo.getProportion());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getCategoryNumber())) {
			queryWrapper.eq("category_number", rzlIpcStatisticsInfo.getCategoryNumber());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getCategoryName())) {
			queryWrapper.like("category_name", rzlIpcStatisticsInfo.getCategoryName());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getDepartClass())) {
			queryWrapper.eq("depart_class", rzlIpcStatisticsInfo.getDepartClass());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getDepartClassName())) {
			queryWrapper.like("depart_class_name", rzlIpcStatisticsInfo.getDepartClassName());
		}
		if (StringUtils.isNotNull(rzlIpcStatisticsInfo.getStatus())) {
			queryWrapper.eq("status", rzlIpcStatisticsInfo.getStatus());
		}
//		if (null != rzlIpcStatisticsInfo.getPubDate()) {
//			queryWrapper.eq("pub_date", rzlIpcStatisticsInfo.getPubDate());
//		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getPubDate())) {
			queryWrapper.eq("pub_date", rzlIpcStatisticsInfo.getPubDate());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getCreateTimeBegin())) {
			queryWrapper.ge("pub_date", rzlIpcStatisticsInfo.getCreateTimeBegin());
		}
		if (StringUtils.isNotEmpty(rzlIpcStatisticsInfo.getCreateTimeEnd())) {
			queryWrapper.le("pub_date", rzlIpcStatisticsInfo.getCreateTimeEnd());
		}

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

}
