package com.ruoyi.dimp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.google.gson.Gson;
import com.ruoyi.common.constant.ImpStatus;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.PojoUtils;
import com.ruoyi.dimp.domain.DMarketsubDataInfo;
import com.ruoyi.dimp.domain.DMarketsubDataInfoPreDetail;
import com.ruoyi.dimp.domain.DMarketsubDataInfoPreImp;
import com.ruoyi.dimp.mapper.DMarketsubDataInfoMapper;
import com.ruoyi.dimp.service.IDMarketsubDataInfoService;
import com.ruoyi.system.domain.BladeRegion;
import com.ruoyi.system.service.IBladeRegionService;

/**
 * 市场主体数据导入Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DMarketsubDataInfoServiceImpl extends ServiceImpl<DMarketsubDataInfoMapper, DMarketsubDataInfo> implements IDMarketsubDataInfoService {

	@Autowired
	private DMarketsubDataInfoMapper dMarketsubDataInfoMapper;
	
	private static final Logger logger=LoggerFactory.getLogger(DMarketsubDataInfoServiceImpl.class);
	private Boolean useLocalCache = true;
	@Autowired
	private RedisCache redisCache;

	private static ThreadLocal<Map<String, DMarketsubDataInfo>> localVar = new ThreadLocal<Map<String, DMarketsubDataInfo>>();
	
	
	 @Override
	    public DMarketsubDataInfo queryPoupationByCityName(String year, String cityName) {
	    	
	    	String key="queryPoupationByCityName:"+cityName+"_"+year;
	    	logger.debug("准备统计人口信息:"+key);
	    	if (useLocalCache) {
				if(localVar.get()==null) {
					localVar.set(new HashMap<String, DMarketsubDataInfo>());
				}
				DMarketsubDataInfo bladeRegion =localVar.get().get(key);
				if (bladeRegion != null) {
					logger.debug("本地缓存中的人口:"+new Gson().toJson(bladeRegion));
					return bladeRegion;
				}
			}
	    	
	    	DMarketsubDataInfo bladeRegion = redisCache.getCacheObject(key);
			if (bladeRegion != null) {
				logger.debug("redis缓存中的人口:"+new Gson().toJson(bladeRegion));
				return bladeRegion;
			}
			
	    	
	    	
	    	
	        // TODO Auto-generated method stub
	        DMarketsubDataInfo dMarketsubDataInfo = new DMarketsubDataInfo();
	        dMarketsubDataInfo.setCityName(cityName);
	        dMarketsubDataInfo.setYear(year);
	        
	        List<DMarketsubDataInfo> list = queryList(dMarketsubDataInfo);
	        if (list != null && !list.isEmpty()) {
	        	DMarketsubDataInfo data = list.get(0);
	        	logger.debug("数据库中的人口:"+new Gson().toJson(data));
	        	if (useLocalCache) {
					localVar.get().put(key, data);
				}
	        	redisCache.setCacheObject(key, data);
	            return data;
	        }
	        return null;
	    }
	 
    @Override
    public DMarketsubDataInfo queryPoupation(String year, String cityCode) {
    	
    	String key="queryPoupation:"+cityCode+"_"+year;
    	logger.debug("准备统计人口信息:"+key);
    	if (useLocalCache) {
			if(localVar.get()==null) {
				localVar.set(new HashMap<String, DMarketsubDataInfo>());
			}
			DMarketsubDataInfo bladeRegion =localVar.get().get(key);
			if (bladeRegion != null) {
				logger.debug("本地缓存中的人口:"+new Gson().toJson(bladeRegion));
				return bladeRegion;
			}
		}
    	
    	DMarketsubDataInfo bladeRegion = redisCache.getCacheObject(key);
		if (bladeRegion != null) {
			logger.debug("redis缓存中的人口:"+new Gson().toJson(bladeRegion));
			return bladeRegion;
		}
		
    	
    	
    	
        // TODO Auto-generated method stub
        DMarketsubDataInfo dMarketsubDataInfo = new DMarketsubDataInfo();
        dMarketsubDataInfo.setCityCode(cityCode);
        dMarketsubDataInfo.setYear(year);
        
        List<DMarketsubDataInfo> list = queryList(dMarketsubDataInfo);
        if (list != null && !list.isEmpty()) {
        	DMarketsubDataInfo data = list.get(0);
        	logger.debug("数据库中的人口:"+new Gson().toJson(data));
        	if (useLocalCache) {
				localVar.get().put(key, data);
			}
        	redisCache.setCacheObject(key, data);
            return data;
        }
        return null;
    }
    
   
    @Autowired
    private IBladeRegionService bladeRegionService;

    public String importData(List<DMarketsubDataInfoPreDetail> dataList, DMarketsubDataInfoPreImp 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++) {
            DMarketsubDataInfoPreDetail repd = dataList.get(j);


            DMarketsubDataInfo extDMarketsubDataInfo = new DMarketsubDataInfo();
            extDMarketsubDataInfo.setCityName(repd.getCityName());
            if(StringUtils.isNotBlank(repd.getCityCode())) {
            	 extDMarketsubDataInfo.setCityCode(repd.getCityCode());
            }else {
//            	识别州市
            	String cityName=repd.getCityName();
            	
            	BladeRegion br = bladeRegionService.selectByCityName(cityName, "53");
            	if(br==null) {
            		repd.setImpState(ImpStatus.IMP_ERR);
            		StringBuffer sb=new StringBuffer();
            		sb.append("无法识别的州市["+cityName+"],请使用全称");
            		errorNum++;
            		BladeRegion br2 = bladeRegionService.selectByCityShortName(cityName, "53");
            		if(br2!=null) {
            			sb.append(",可能是["+br2.getName()+"]");
            		}
            		repd.setErrReason(sb.toString());
            		failMsgList.add(sb.toString());
            		continue;
            	}else {
            		repd.setCityCode(br.getCityCode());
            	}
            	
            	
            	
            	
            }
            extDMarketsubDataInfo.setYear(repd.getYear());
           

            int i = j + 1;
            DMarketsubDataInfo branchPointsSum = PojoUtils.copyTo(DMarketsubDataInfo.class, repd);
            List<DMarketsubDataInfo> list = queryList(extDMarketsubDataInfo);
            if (list != null && !list.isEmpty()) {
                DMarketsubDataInfo d = list.get(0);
//			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());
                branchPointsSum.setYear(repd.getYear());
                
//                if(StringUtils.isNotBlank(branchPointsSum.getCityName()) && StringUtils.isBlank(branchPointsSum.getCityCode())) {
//                	if(AREA_CODE_MAP.containsKey(branchPointsSum.getCityName())) {
//                		branchPointsSum.setCityCode(AREA_CODE_MAP.get(branchPointsSum.getCityName()));
//                	}
//                }
                branchPointsSum.setCityCode(repd.getCityCode());
                branchPointsSum.setDataYear(repd.getYear());
                save(branchPointsSum);

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

    }

    /**
     * 查询市场主体数据导入列表
     *
     * @param dMarketsubDataInfo 市场主体数据导入
     * @return 市场主体数据导入集合
     * @date 2023-03-19
     */
    @Override
    public List<DMarketsubDataInfo> queryList(DMarketsubDataInfo dMarketsubDataInfo) {
        QueryWrapper<DMarketsubDataInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(dMarketsubDataInfo.getCityCode())) {
            queryWrapper.eq("city_code", dMarketsubDataInfo.getCityCode());
        }
        
        if (StringUtils.isNotEmpty(dMarketsubDataInfo.getYear())) {
            queryWrapper.eq("year", dMarketsubDataInfo.getYear());
        }
        
        if(dMarketsubDataInfo.getMinYear()>0) {
        	queryWrapper.ge("year", dMarketsubDataInfo.getMinYear());
        }
        if(dMarketsubDataInfo.getMaxYear()>0) {
        	queryWrapper.le("year", dMarketsubDataInfo.getMaxYear());
        }
        
        if (StringUtils.isNotEmpty(dMarketsubDataInfo.getCityName())) {
            queryWrapper.eq("city_name", dMarketsubDataInfo.getCityName());
        }
        if (StringUtils.isNotEmpty(dMarketsubDataInfo.getMarketsubTotal())) {
            queryWrapper.eq("marketsub_total", dMarketsubDataInfo.getMarketsubTotal());
        }
        if (StringUtils.isNotNull(dMarketsubDataInfo.getStatus())) {
            queryWrapper.eq("status", dMarketsubDataInfo.getStatus());
        }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

	@Override
	public void deleteByYear(String year) {
		// TODO Auto-generated method stub
		dMarketsubDataInfoMapper.deleteByYear(year);
	}

}
