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.DPopulationDataInfo;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreDetail;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreImp;
import com.ruoyi.dimp.mapper.DPopulationDataInfoMapper;
import com.ruoyi.dimp.service.IDPopulationDataInfoService;

/**
 * 云南人口数据导入Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DPopulationDataInfoServiceImpl extends ServiceImpl<DPopulationDataInfoMapper, DPopulationDataInfo> implements IDPopulationDataInfoService {

	@Autowired
	private DPopulationDataInfoMapper dPopulationDataInfoMapper;
	
	private static final Logger logger=LoggerFactory.getLogger(DPopulationDataInfoServiceImpl.class);
//	private Boolean useLocalCache = false;
	@Autowired
	private RedisCache redisCache;

//	private static ThreadLocal<Map<String, DPopulationDataInfo>> localVar = new ThreadLocal<Map<String, DPopulationDataInfo>>();
	
	
	 @Override
	    public DPopulationDataInfo queryPoupationByCityName(String year, String cityName) {
	    	
	    	String key="queryPoupationByCityName:"+cityName+"_"+year;
	    	logger.debug("准备统计人口信息:"+key);
//	    	if (useLocalCache) {
//				if(localVar.get()==null) {
//					localVar.set(new HashMap<String, DPopulationDataInfo>());
//				}
//				DPopulationDataInfo bladeRegion =localVar.get().get(key);
//				if (bladeRegion != null) {
//					logger.debug("本地缓存中的人口:"+new Gson().toJson(bladeRegion));
//					return bladeRegion;
//				}
//			}
//	    	
//	    	DPopulationDataInfo bladeRegion = redisCache.getCacheObject(key);
//			if (bladeRegion != null) {
//				logger.debug("redis缓存中的人口:"+new Gson().toJson(bladeRegion));
//				return bladeRegion;
//			}
			
	    	
	    	
	    	
	        // TODO Auto-generated method stub
	        DPopulationDataInfo dPopulationDataInfo = new DPopulationDataInfo();
	        dPopulationDataInfo.setCityName(cityName);
	        dPopulationDataInfo.setYear(year);
	        
	        List<DPopulationDataInfo> list = queryList(dPopulationDataInfo);
	        if (list != null && !list.isEmpty()) {
	        	DPopulationDataInfo 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 DPopulationDataInfo queryPoupation(String year, String cityCode) {
    	
    	String key="queryPoupation:"+cityCode+"_"+year;
    	logger.debug("准备统计人口信息:"+key);
//    	if (useLocalCache) {
//			if(localVar.get()==null) {
//				localVar.set(new HashMap<String, DPopulationDataInfo>());
//			}
//			DPopulationDataInfo bladeRegion =localVar.get().get(key);
//			if (bladeRegion != null) {
//				logger.debug("本地缓存中的人口:"+new Gson().toJson(bladeRegion));
//				return bladeRegion;
//			}
//		}
//    	DPopulationDataInfo bladeRegion = redisCache.getCacheObject(key);
//		if (bladeRegion != null) {
//			logger.debug("redis缓存中的人口:"+new Gson().toJson(bladeRegion));
//			return bladeRegion;
//		}
		
    	
    	
    	
        // TODO Auto-generated method stub
        DPopulationDataInfo dPopulationDataInfo = new DPopulationDataInfo();
        dPopulationDataInfo.setCityCode(cityCode);
        dPopulationDataInfo.setYear(year);
        
        List<DPopulationDataInfo> list = queryList(dPopulationDataInfo);
        if (list != null && !list.isEmpty()) {
        	DPopulationDataInfo 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;
    }
    
   

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


            DPopulationDataInfo extDPopulationDataInfo = new DPopulationDataInfo();
            extDPopulationDataInfo.setCityName(repd.getCityName());
            if(StringUtils.isNotBlank(repd.getCityCode())) {
            	 extDPopulationDataInfo.setCityCode(repd.getCityCode());
            }
            extDPopulationDataInfo.setYear(repd.getYear());

            int i = j + 1;
            DPopulationDataInfo branchPointsSum = PojoUtils.copyTo(DPopulationDataInfo.class, repd);
            List<DPopulationDataInfo> list = queryList(extDPopulationDataInfo);
            if (list != null && !list.isEmpty()) {
                DPopulationDataInfo 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()));
//                	}
//                }
                
                if("全省".equals(branchPointsSum.getCityName()) || "云南省".equals(branchPointsSum.getCityName())) {
                	//跳过全省的
                	 repd.setImpState(ImpStatus.IMP_SKIP);
                     skipNum++;
                }else {
                	 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 dPopulationDataInfo 云南人口数据导入
     * @return 云南人口数据导入集合
     * @date 2023-03-19
     */
    @Override
    public List<DPopulationDataInfo> queryList(DPopulationDataInfo dPopulationDataInfo) {
        QueryWrapper<DPopulationDataInfo> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(dPopulationDataInfo.getCityCode())) {
            queryWrapper.eq("city_code", dPopulationDataInfo.getCityCode());
        }
        
        if (StringUtils.isNotEmpty(dPopulationDataInfo.getYear())) {
            queryWrapper.eq("year", dPopulationDataInfo.getYear());
        }
        
        if(dPopulationDataInfo.getMinYear()>0) {
        	queryWrapper.ge("year", dPopulationDataInfo.getMinYear());
        }
        if(dPopulationDataInfo.getMaxYear()>0) {
        	queryWrapper.le("year", dPopulationDataInfo.getMaxYear());
        }
        
        if (StringUtils.isNotEmpty(dPopulationDataInfo.getCityName())) {
            queryWrapper.eq("city_name", dPopulationDataInfo.getCityName());
        }
        if (StringUtils.isNotEmpty(dPopulationDataInfo.getPopulationTotal())) {
            queryWrapper.eq("population_total", dPopulationDataInfo.getPopulationTotal());
        }
        if (StringUtils.isNotNull(dPopulationDataInfo.getStatus())) {
            queryWrapper.eq("status", dPopulationDataInfo.getStatus());
        }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

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

}
