package com.ruoyi.dimp.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
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.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.ImpStatus;
import com.ruoyi.common.constant.PreImpStatus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreDetail;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreImp;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreDetail;
import com.ruoyi.dimp.domain.DPopulationDataInfoPreImp;
import com.ruoyi.dimp.mapper.DPopulationDataInfoPreDetailMapper;
import com.ruoyi.dimp.mapper.DPopulationDataInfoPreImpMapper;
import com.ruoyi.dimp.mapper.DPopulationDataInfoPreDetailMapper;
import com.ruoyi.dimp.service.IDPopulationDataInfoService;
import com.ruoyi.dimp.service.IDPopulationDataInfoPreDetailService;

/**
 * 云南人口数据导入详情Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DPopulationDataInfoPreDetailServiceImpl extends ServiceImpl<DPopulationDataInfoPreDetailMapper, DPopulationDataInfoPreDetail> implements IDPopulationDataInfoPreDetailService {

	private static final Logger logger = LoggerFactory.getLogger(DPopulationDataInfoPreDetailServiceImpl.class);

	
	@Autowired
	private IDPopulationDataInfoService dPopulationDataInfoService;
	@Autowired
	private DPopulationDataInfoPreDetailMapper dPopulationDataInfoPreDetailMapper;
	
	@Autowired
	private DPopulationDataInfoPreImpMapper dPopulationDataInfoPreImpMapper;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	
	 private static final Map<String,String>AREA_CODE_MAP=new HashMap<String,String>();
	    static {
	    	

	    	AREA_CODE_MAP.put("全省","53");
	    	AREA_CODE_MAP.put("昆明","5301");
	    	AREA_CODE_MAP.put("曲靖","5303");
	    	AREA_CODE_MAP.put("玉溪","5304");
	    	AREA_CODE_MAP.put("保山","5305");
	    	AREA_CODE_MAP.put("昭通","5306");
	    	AREA_CODE_MAP.put("丽江","5307");
	    	AREA_CODE_MAP.put("普洱","5308");
	    	AREA_CODE_MAP.put("临沧","5309");
	    	AREA_CODE_MAP.put("楚雄","5323");
	    	AREA_CODE_MAP.put("红河","5325");
	    	AREA_CODE_MAP.put("文山","5326");
	    	AREA_CODE_MAP.put("西双版纳","5328");
	    	AREA_CODE_MAP.put("大理","5329");
	    	AREA_CODE_MAP.put("德宏","5331");
	    	AREA_CODE_MAP.put("怒江","5333");
	    	AREA_CODE_MAP.put("迪庆","5334");

	    	
	    	
	    }
	
    /**
     * 查询云南人口数据导入详情列表
     *
     * @param dPopulationDataInfoPreDetail 云南人口数据导入详情
     * @return 云南人口数据导入详情集合
     * @date 2023-03-19
     */
    @Override
    public List<DPopulationDataInfoPreDetail> queryList(DPopulationDataInfoPreDetail dPopulationDataInfoPreDetail) {
        QueryWrapper<DPopulationDataInfoPreDetail> queryWrapper = Wrappers.query();
                if ( StringUtils.isNotEmpty(dPopulationDataInfoPreDetail.getCityCode())  ){
                    queryWrapper.eq("city_code", dPopulationDataInfoPreDetail.getCityCode());
                }
                if ( StringUtils.isNotEmpty(dPopulationDataInfoPreDetail.getCityName())  ){
                    queryWrapper.like("city_name", dPopulationDataInfoPreDetail.getCityName());
                }
                if ( StringUtils.isNotEmpty(dPopulationDataInfoPreDetail.getPopulationTotal())  ){
                    queryWrapper.eq("population_total", dPopulationDataInfoPreDetail.getPopulationTotal());
                }
                if (  StringUtils.isNotNull(dPopulationDataInfoPreDetail.getStatus())){
                    queryWrapper.eq("status", dPopulationDataInfoPreDetail.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }



    @Override
	public List<DPopulationDataInfoPreDetail> doPreImp(DPopulationDataInfoPreImp imp) {


		String fielPath2 = imp.getFilePath();
		ExcelUtil<DPopulationDataInfoPreDetail> util = new ExcelUtil<DPopulationDataInfoPreDetail>(DPopulationDataInfoPreDetail.class);
		List<DPopulationDataInfoPreDetail> memberPointsDetailList;
		List<DPopulationDataInfoPreDetail> memberPointsDetailList2=new ArrayList<DPopulationDataInfoPreDetail>();

//		//正在解析
//		DPopulationDataInfoPreImp u1=new DPopulationDataInfoPreImp();
//		u1.setId(imp.getId());
//		u1.setImpState(PreImpStatus.IMP_ING);
//		uaBranchStaffPreImpMapper.updateDPopulationDataInfoPreImp(u1);

		FileInputStream in = null;
		try {
//			in = new FileInputStream(new File(fielPath2));
//			memberPointsDetailList = util.importExcel(null, in);
			
			if(fielPath2.toLowerCase().trim().endsWith("csv")) {
				memberPointsDetailList=util.importCsv(new File(fielPath2));
			}else {
				in = new FileInputStream(new File(fielPath2));
				memberPointsDetailList = util.importExcel(null, in);
			}
			
			
		} catch (Exception e) {
			logger.error("高价值专利数据读取失败," + e.getMessage(), e);
			DPopulationDataInfoPreImp u2 = new DPopulationDataInfoPreImp();
			u2.setId(imp.getId());
			u2.setImpState(PreImpStatus.PARSE_ERR);
			dPopulationDataInfoPreImpMapper.updateById(u2);
			return null;
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}

		}

		if (memberPointsDetailList == null || memberPointsDetailList.isEmpty()) {
			logger.warn("没有读取到高价值专利数据信息，直接返回");
			return null;
		}
		for (int i = 0; i < memberPointsDetailList.size(); i++) {
			DPopulationDataInfoPreDetail d = memberPointsDetailList.get(i);
			if(d==null || StringUtils.isBlank(d.getPopulationTotal())) {
				continue;
			}
			
			memberPointsDetailList2.add(d);
			logger.debug("开始插入第【" + i + "】行数据（一共【" + memberPointsDetailList.size() + "】行）");
//			DPopulationDataInfoPreDetail d : memberPointsDetailList
			d.setPreId(imp.getId());
			d.setImpState(ImpStatus.INIT);
			d.setFileName(imp.getFileName());
			d.setYear(imp.getYear());
			
			if(StringUtils.isNotBlank(d.getCityName())) {
				if(AREA_CODE_MAP.containsKey(d.getCityName())) {
					d.setCityCode(AREA_CODE_MAP.get(d.getCityName()));
				}
				
			}
			
			dPopulationDataInfoPreDetailMapper.insert(d);
		}

		// 开始导入
		logger.debug("插入完成，准备更新状态");
		DPopulationDataInfoPreImp u3 = new DPopulationDataInfoPreImp();
		u3.setId(imp.getId());
		u3.setImpState(PreImpStatus.IMP_ING);
		dPopulationDataInfoPreImpMapper.updateById(u3);
//		TODO	
		return memberPointsDetailList2;
	
	}

	@Override
	public void doImp(List<DPopulationDataInfoPreDetail> list, DPopulationDataInfoPreImp imp) {

		if (list == null  || imp == null) {
			return;
		}
		logger.debug("开始处理异步导入数据，imp:" + new Gson().toJson(imp) + ",总记录数:" + list.size());
		
		
		if(StringUtils.isNotBlank(imp.getYear()) && !list.isEmpty()) {
			dPopulationDataInfoService.deleteByYear(imp.getYear());
		}
		
		List<DPopulationDataInfoPreDetail> errList = new ArrayList<DPopulationDataInfoPreDetail>();
		String str = dPopulationDataInfoService.importData(list, imp);
		
//		logger.debug("导入机构汇总数据完成，开始重新计算排名");
////		String pointsMonth = new SimpleDateFormat("yyyy-MM").format(new Date());
//		Calendar c=Calendar.getInstance();
//		c.set(Calendar.DAY_OF_YEAR, c.get(Calendar.DAY_OF_YEAR)-1);
//		String pointsMonth = new SimpleDateFormat("yyyy-MM").format(c.getTime());
//		dPopulationDataInfoService.resetRanking(pointsMonth);
		
		for (int i = 0; i < list.size(); i++) {
			logger.debug("导入完成，向数据库更新状态，当前第[" + i + "]条，一共[" + list.size() + "]条");
			DPopulationDataInfoPreDetail d = list.get(i);
			DPopulationDataInfoPreDetail u = new DPopulationDataInfoPreDetail();
			u.setId(d.getId());
			u.setImpState(d.getImpState());
			u.setErrReason(d.getErrReason());

			if (ImpStatus.IMP_SKIP.equals(d.getImpState()) || ImpStatus.IMP_ERR.equals(d.getImpState())) {
				errList.add(d);
			}
			dPopulationDataInfoPreDetailMapper.updateById(u);
		}

		DPopulationDataInfoPreImp uimp = new DPopulationDataInfoPreImp();

		String fileName = imp.getFileName();

		String filePath = imp.getFilePath();

		File path = new File(filePath).getParentFile();

		String resFileName = fileName.substring(0, fileName.lastIndexOf(".")) + "_impres"
				+ fileName.substring(fileName.lastIndexOf("."), fileName.length());

		File resFile = new File(path, resFileName);

		ExcelUtil<DPopulationDataInfoPreDetail> util = new ExcelUtil<DPopulationDataInfoPreDetail>(DPopulationDataInfoPreDetail.class);

//		String impres = FileUploadUtils.upload(RuoYiConfig.getMemberPointsDtail(), file);

		FileOutputStream out = null;

		try {
			out = new FileOutputStream(resFile);

			util.exportExcel(out, errList, "高价值专利数据");

			uimp.setErrReason(str);
		} catch (FileNotFoundException e) {
			logger.error(e.getMessage(), e);
			uimp.setErrReason("没有生成导入结果文件," + e.getMessage());
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
			}

		}

		uimp.setId(imp.getId());
		uimp.setInsertNum(imp.getInsertNum() == null ? 0 : imp.getInsertNum());
		uimp.setUpdateNum(imp.getUpdateNum() == null ? 0 : imp.getUpdateNum());
		uimp.setSkipNum(imp.getSkipNum() == null ? 0 : imp.getSkipNum());
		uimp.setErrorNum(imp.getErrorNum() == null ? 0 : imp.getErrorNum());
		
		uimp.setTotalNum(imp.getTotalNum()==null?0:imp.getTotalNum());

		uimp.setResFileName(resFileName);

		int dirLastIndex = RuoYiConfig.getProfile().length() + 1;
		String currentDir = StringUtils.substring(path.getAbsolutePath(), dirLastIndex);
		String res = Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + resFileName;

		uimp.setResFileUrl(ruoYiConfig.getFilePath() + res);

		if (errList.isEmpty()) {
			uimp.setImpState(PreImpStatus.IMP_ED);
		} else {
			uimp.setImpState(PreImpStatus.PART_SUCC);
		}
		
		if(imp.getCreateTime()!=null) {
			uimp.setUseTime((System.currentTimeMillis()-imp.getCreateTime().getTime())/1000);
		}
		dPopulationDataInfoPreImpMapper.updateById(uimp);
		return;
	
	}
}
