package com.ruoyi.dimp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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.adjust.domain.DHighValuePub;
import com.ruoyi.adjust.service.IDHighValuePubService;
import com.ruoyi.common.constant.ImpStatus;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.PojoUtils;
import com.ruoyi.dimp.domain.DHighValueInfo;
import com.ruoyi.dimp.domain.DHighValueInfoPreDetail;
import com.ruoyi.dimp.domain.DHighValueInfoPreImp;
import com.ruoyi.dimp.mapper.DHighValueInfoMapper;
import com.ruoyi.dimp.service.IDHighValueInfoService;
import com.ruoyi.reportpub.domain.DPatentPubInfo;
import com.ruoyi.reportpub.service.IDPatentPubInfoService;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;
import com.ruoyi.utils.BladeRegionUtils;

/**
 * 高价值数据导入Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DHighValueInfoServiceImpl extends ServiceImpl<DHighValueInfoMapper, DHighValueInfo>
		implements IDHighValueInfoService {
	
	@Autowired
	private DHighValueInfoMapper dHighValueInfoMapper;
	@Autowired
	private IBladeRegionService bladeRegionService;
	@Autowired
	private IDPatentPubInfoService dPatentPubInfoService;
	@Autowired
	private IDHighValuePubService dHighValuePubService;
	
	

	public String importData(List<DHighValueInfoPreDetail> dataList, DHighValueInfoPreImp imp) {

//		logger.debug("正在导入[机构积分汇总]数据:" + new Gson().toJson(data));
		long successNum = 0;
		long errorNum = 0;
		long insertNum = 0;
		long updateNum = 0;
		long skipNum = 0;
		long totalNum = dataList.size();
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();

		List<String> failMsgList = new ArrayList<String>();
//		Map<String, UaBranchInfo> branchInfoMap2 = new HashMap<String, UaBranchInfo>();
//		Map<String, AreaCache> areaInfoMap = new HashMap<String, AreaCache>();

//		Map<String, UaMemberActivityRel> activityRelMap = new HashMap<String, UaMemberActivityRel>();

		for (int j = 0; j < dataList.size(); j++) {
			DHighValueInfoPreDetail repd = dataList.get(j);

			
			DHighValueInfo extDHighValueInfo = new DHighValueInfo();
			if(StringUtils.isNotBlank(repd.getProvinceCode())) {
				String provinceCode=repd.getProvinceCode().trim();
				if(provinceCode.length()>2) {
					provinceCode=provinceCode.substring(0, 2);
				}
				extDHighValueInfo.setProvinceCode(provinceCode);
				repd.setProvinceCode(provinceCode);
			}
			if(StringUtils.isNotBlank(repd.getCityCode())) {
				String cityCode=repd.getCityCode();
				if(cityCode.length()>4) {
					cityCode=cityCode.substring(0, 4);
				}
				extDHighValueInfo.setCityCode(cityCode);
				repd.setCityCode(cityCode);
			}
			extDHighValueInfo.setAddress(repd.getAddress());
			
			int i = j + 1;
			DHighValueInfo branchPointsSum = PojoUtils.copyTo(DHighValueInfo.class, repd);
			List<DHighValueInfo> list = queryList(extDHighValueInfo);
			if (list != null && !list.isEmpty()) {
				DHighValueInfo d = list.get(0);
				d.setImpBatch(repd.getImpBatch());
//			BeanUtils.copyBeanProp(d, branchPointsSum);
				branchPointsSum.setId(d.getId());
				branchPointsSum.setUpdateTime(new Date());
				this.updateById(branchPointsSum);
				updateNum++;
				repd.setImpState(ImpStatus.IMP_UPDATE);
			} else {
				branchPointsSum.setCreateTime(new Date());
				
				if(StringUtils.isNotBlank(repd.getProvinceCode())) {
					
					String provinceCode=repd.getProvinceCode().trim();
					if(provinceCode.length()>2) {
						provinceCode=provinceCode.substring(0, 2);
					}
					branchPointsSum.setProvinceCode(provinceCode);
					
					BladeRegion bladeRegion =BladeRegionUtils.selectByCode(provinceCode);
					if(bladeRegion!=null) {
						branchPointsSum.setProvinceName(bladeRegion.getProvinceName());
					}
					
					if(StringUtils.isNotBlank(repd.getCityCode())) {
						String cityCode=repd.getCityCode();
						if(cityCode.length()>4) {
							cityCode=cityCode.substring(0, 4);
						}
						branchPointsSum.setCityCode(cityCode);
						BladeRegion cityBladeRegion =BladeRegionUtils.selectByCode(cityCode);
						if(cityBladeRegion!=null) {
							branchPointsSum.setCityName(cityBladeRegion.getCityName());
						}
								
					}
					
					
					
				}  
				List<DPatentPubInfo> dPatentPubInfoList = null;
				if(StringUtils.isNotBlank(repd.getAddress())) {
					
					dPatentPubInfoList = dPatentPubInfoService.queryByAddress(repd.getAddress());
					if(dPatentPubInfoList==null || dPatentPubInfoList.isEmpty()) {
						dPatentPubInfoList = dPatentPubInfoService.queryByCownerAddress(repd.getAddress());
					}
					if(dPatentPubInfoList!=null && !dPatentPubInfoList.isEmpty()) {
						
						DPatentPubInfo dPatentPubInfo=dPatentPubInfoList.get(0);
						if(dPatentPubInfo!=null) {
							
							if(StringUtils.isBlank(branchPointsSum.getProvinceCode())) {
								if(StringUtils.isNotBlank(dPatentPubInfo.getYunnanModifyAppliProvince())) {
									BladeRegion bladeRegion = bladeRegionService.selectByProvinceName(dPatentPubInfo.getYunnanModifyAppliProvince());
									if(bladeRegion!=null) {
										branchPointsSum.setProvinceName(bladeRegion.getProvinceName());
										branchPointsSum.setProvinceCode(bladeRegion.getProvinceCode());
									}
								}
							}
							
							
							if(StringUtils.isBlank(branchPointsSum.getCityCode())) {
								if(StringUtils.isNotBlank(dPatentPubInfo.getYunnanModifyAppliCity())) {
									BladeRegion cityRegion = bladeRegionService.selectByProvinceName(dPatentPubInfo.getYunnanModifyAppliCity());
									if(cityRegion!=null) {
										branchPointsSum.setCityName(cityRegion.getCityName());
										branchPointsSum.setCityCode(cityRegion.getCityCode());
									}
								}
							}
							
							
							if(StringUtils.isBlank(branchPointsSum.getAreaCode())) {
								if(StringUtils.isNotBlank(dPatentPubInfo.getYunnanModifyAppliCounty())) {
									BladeRegion areaRegion = bladeRegionService.selectByProvinceName(dPatentPubInfo.getYunnanModifyAppliCounty());
									if(areaRegion!=null) {
										branchPointsSum.setAreaName(areaRegion.getName());
										branchPointsSum.setAreaCode(areaRegion.getCode());
									}
								}
							}
							
							
						}
						
						
						
						
						
						
					}
					
				}
				
				
				
				save(branchPointsSum);
				
				
				List<DPatentPubInfo> dPatentPubInfoList2 = new ArrayList<DPatentPubInfo>();
				if(dPatentPubInfoList!=null && !dPatentPubInfoList.isEmpty()) {
					for(DPatentPubInfo pub:dPatentPubInfoList) {
//						if(!("10".equals(pub.getStatus()) || "30".equals(pub.getStatus()) )) {
//							continue;
//						}
						if(!("1".equals(pub.getPatentType()) ||"4".equals(pub.getPatentType()))) {
							continue;
						}
//						20230720 注释
//						if(StringUtils.isBlank(pub.getHighValue())) {
//							continue;
//						}
						dPatentPubInfoList2.add(pub);
					}
				}
				if(dPatentPubInfoList2!=null && !dPatentPubInfoList2.isEmpty()) {
					for(DPatentPubInfo pub:dPatentPubInfoList2) {
						DHighValuePub hvpub=new DHighValuePub();
//						private Long id;
//
//						/** 高价值信息表id */
//						@Excel(name = "高价值信息表id")
//						private Long hvId;
						hvpub.setHvId(branchPointsSum.getId());
//
//						/** 专利公开数据表id */
//						@Excel(name = "专利公开数据表id")
//						private Long pubId;
						hvpub.setPubId(pub.getId());
//
//						/** 申请人 */
//						@Excel(name = "申请人")
//						private String appliPub;
						hvpub.setAppliPub(pub.getAppli());
//
//						/** 申请人类型 */
//						@Excel(name = "申请人类型")
//						private String appliTypePub;
						hvpub.setAppliTypePub(pub.getAppliType());
//
//						/** 删除标识 */
//						private Integer delFlag;
//
//						/** 状态 */
//						@Excel(name = "状态")
//						private Long status;
						dHighValuePubService.save(hvpub);
					}
				}
				repd.setImpState(ImpStatus.IMP_INSERT);
				insertNum++;
			}

			successNum++;

		}

		successMsg.append("导入高价值数据完成，共【" + totalNum + "】条，插入【" + insertNum + "】条");
		if (updateNum > 0) {
			successMsg.append(",更新【" + updateNum + "】条");
		}
		if (errorNum > 0) {
			successMsg.append(",失败条数【" + errorNum + "】条,");
			successMsg.append("<br/>失败原因如下:");

			for (int i = 0; i < failMsgList.size(); i++) {
				if (i < 10) {
					successMsg.append(failMsgList.get(i));
				} else {
					successMsg.append("<br/>还有更多失败，请重新导入试试");
					break;
				}
			}
		}
		imp.setTotalNum(totalNum);
		imp.setInsertNum(insertNum);
		imp.setUpdateNum(updateNum);
		imp.setSkipNum(skipNum);
		imp.setErrorNum(errorNum);
		imp.setErrReason(successMsg.toString());

		successMsg.append("<br/>");
		return successMsg.toString();

	}
	
	public List<DHighValueInfo>doList(DHighValueInfo dHighValueInfo){
		boolean retEmpty=false;
		if (StringUtils.isNotBlank(dHighValueInfo.getCityCode()) && !"53".equals(dHighValueInfo.getCityCode())) {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				dHighValueInfo.setCityCode(cityCode);
			}
		}else {
			if(SecurityUtils.isNeedFilterByCityCode()) {
				String cityCode=SecurityUtils.needFilterByCityCode();
				dHighValueInfo.setCityCode(cityCode);
			}
		}
		
		
    	List<DHighValueInfo> list = queryList(dHighValueInfo);
        for(DHighValueInfo vo:list) {
        	 List<String>appliPubList=new ArrayList<String>();
        	 vo.setAppliPubList(appliPubList);
        }
        if("1".equals(dHighValueInfo.getQueryPub())) {
        	for(DHighValueInfo vo:list) {
        		 List<String>appliPubList=new ArrayList<String>();
        		List<DHighValuePub>pubList=dHighValuePubService.queryListByHvId(vo.getId());
        		Set<String>appliPubSet=new HashSet<String>();
        		
        		if(pubList!=null && !pubList.isEmpty()) {
//        			vo.setPubList(pubList);
        			for(DHighValuePub pub:pubList) {
        				appliPubSet.add(pub.getAppliPub());
        			}
        			
        		}else if(StringUtils.isNotBlank(vo.getAddress())) {
//        			vo.setPubList(new ArrayList<DHighValuePub>());
        			
        			if("云南省曲靖市麒麟区麒麟西路82号".equals(vo.getAddress())) {
        				System.out.println("kkkkk");
        			}
        			

					
        			List<DPatentPubInfo> dPatentPubInfoList = dPatentPubInfoService.queryByAddress(vo.getAddress());
					if(dPatentPubInfoList==null || dPatentPubInfoList.isEmpty()) {
						dPatentPubInfoList = dPatentPubInfoService.queryByCownerAddress(vo.getAddress());
					}
					if(dPatentPubInfoList!=null && !dPatentPubInfoList.isEmpty()) {
						
						DPatentPubInfo dPatentPubInfo=dPatentPubInfoList.get(0);
						if(dPatentPubInfo!=null) {
							
							if(StringUtils.isBlank(vo.getProvinceCode())) {
								if(StringUtils.isNotBlank(dPatentPubInfo.getYunnanModifyAppliProvince())) {
									BladeRegion bladeRegion = bladeRegionService.selectByProvinceName(dPatentPubInfo.getYunnanModifyAppliProvince());
									if(bladeRegion!=null) {
										vo.setProvinceName(bladeRegion.getProvinceName());
										vo.setProvinceCode(bladeRegion.getProvinceCode());
									}
								}
							}
							
							
							if(StringUtils.isBlank(vo.getCityCode())) {
								if(StringUtils.isNotBlank(dPatentPubInfo.getYunnanModifyAppliCity())) {
									BladeRegion cityRegion = bladeRegionService.selectByProvinceName(dPatentPubInfo.getYunnanModifyAppliCity());
									if(cityRegion!=null) {
										vo.setCityName(cityRegion.getCityName());
										vo.setCityCode(cityRegion.getCityCode());
									}
								}
							}
							
							
							if(StringUtils.isBlank(vo.getAreaCode())) {
								if(StringUtils.isNotBlank(dPatentPubInfo.getYunnanModifyAppliCounty())) {
									BladeRegion areaRegion = bladeRegionService.selectByProvinceName(dPatentPubInfo.getYunnanModifyAppliCounty());
									if(areaRegion!=null) {
										vo.setAreaName(areaRegion.getName());
										vo.setAreaCode(areaRegion.getCode());
									}
								}
							}
							
							
						}
						
						
						
						
						
						
					}
					
					
					List<DPatentPubInfo> dPatentPubInfoList2 = new ArrayList<DPatentPubInfo>();
					if(dPatentPubInfoList!=null && !dPatentPubInfoList.isEmpty()) {
						for(DPatentPubInfo pub:dPatentPubInfoList) {
//							if(!("10".equals(pub.getStatus()) || "30".equals(pub.getStatus()) )) {
//								continue;
//							}
							if(!("1".equals(pub.getPatentType()) ||"4".equals(pub.getPatentType()))) {
								continue;
							}
//							if(StringUtils.isBlank(pub.getHighValue())) {
//								continue;
//							}
							dPatentPubInfoList2.add(pub);
						}
					}
					if(dPatentPubInfoList2!=null && !dPatentPubInfoList2.isEmpty()) {
						for(DPatentPubInfo pub:dPatentPubInfoList2) {
							DHighValuePub hvpub=new DHighValuePub();
//							private Long id;
	//
//							/** 高价值信息表id */
//							@Excel(name = "高价值信息表id")
//							private Long hvId;
							hvpub.setHvId(vo.getId());
	//
//							/** 专利公开数据表id */
//							@Excel(name = "专利公开数据表id")
//							private Long pubId;
							hvpub.setPubId(pub.getId());
	//
//							/** 申请人 */
//							@Excel(name = "申请人")
//							private String appliPub;
							hvpub.setAppliPub(pub.getAppli());
	//
//							/** 申请人类型 */
//							@Excel(name = "申请人类型")
//							private String appliTypePub;
							hvpub.setAppliTypePub(pub.getAppliType());
	//
//							/** 删除标识 */
//							private Integer delFlag;
	//
//							/** 状态 */
//							@Excel(name = "状态")
//							private Long status;
							dHighValuePubService.save(hvpub);
							appliPubSet.add(hvpub.getAppliPub());
						}
					}
					
				
					dHighValueInfoMapper.updateById(vo);
					
        			
        			
        			
        		}
        		
        		appliPubList.addAll(appliPubSet);
        		String appli="";
        		int c=0;
        		for(int i=0;i<appliPubList.size();i++) {
        			if(StringUtils.isNotEmpty(appliPubList.get(i))) {
        				if(c>0) {
            				appli=appli+",";
            			}
            			appli=appli+appliPubList.get(i);
            			c++;
        			}
        			
        		}
        		vo.setAppli(appli);
        		vo.setAppliPubList(appliPubList);
        	}
        }
        return list;
    }

	/**
	 * 查询高价值数据导入列表
	 *
	 * @param dHighValueInfo 高价值数据导入
	 * @return 高价值数据导入集合
	 * @date 2023-03-19
	 */
	@Override
	public List<DHighValueInfo> queryList(DHighValueInfo dHighValueInfo) {
		QueryWrapper<DHighValueInfo> queryWrapper = Wrappers.query();
		if (StringUtils.isNotEmpty(dHighValueInfo.getProvinceCode())) {
			queryWrapper.eq("province_code", dHighValueInfo.getProvinceCode());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getProvinceName())) {
			queryWrapper.like("province_name", dHighValueInfo.getProvinceName());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getCityCode())) {
			queryWrapper.eq("city_code", dHighValueInfo.getCityCode());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getYear())) {
			queryWrapper.eq("imp_batch", dHighValueInfo.getYear().trim()+"12");
		}
		
		if (StringUtils.isNotEmpty(dHighValueInfo.getCityName())) {
			queryWrapper.like("city_name", dHighValueInfo.getCityName());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getAddress())) {
			queryWrapper.eq("address", dHighValueInfo.getAddress());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getIndustryEmergIndustry())) {
			queryWrapper.eq("industry_emerg_industry", dHighValueInfo.getIndustryEmergIndustry());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getMaintenanceTenYear())) {
			queryWrapper.eq("maintenance_ten_year", dHighValueInfo.getMaintenanceTenYear());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getOverseasCongenerPatent())) {
			queryWrapper.eq("overseas_congener_patent", dHighValueInfo.getOverseasCongenerPatent());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getPledgeRecord())) {
			queryWrapper.eq("pledge_record", dHighValueInfo.getPledgeRecord());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getNationalScienceAward())) {
			queryWrapper.eq("national_science_award", dHighValueInfo.getNationalScienceAward());
		}
		if (StringUtils.isNotEmpty(dHighValueInfo.getInventionPatentNumber())) {
			queryWrapper.eq("invention_patent_number", dHighValueInfo.getInventionPatentNumber());
		}
		if (StringUtils.isNotNull(dHighValueInfo.getStatus())) {
			queryWrapper.eq("status", dHighValueInfo.getStatus());
		}
		queryWrapper.orderByDesc("id");
		return this.list(queryWrapper);
	}

	@Override
	public void deleteWidthImpBatch(String impBatch) {
		// TODO Auto-generated method stub
		dHighValueInfoMapper.deleteWidthImpBatch(impBatch);
		
	}
}
