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.util.ArrayList;
import java.util.List;

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.DHighValueInfoPreDetail;
import com.ruoyi.dimp.domain.DHighValueInfoPreImp;
import com.ruoyi.dimp.mapper.DHighValueInfoPreDetailMapper;
import com.ruoyi.dimp.mapper.DHighValueInfoPreImpMapper;
import com.ruoyi.dimp.service.IDHighValueInfoPreDetailService;
import com.ruoyi.dimp.service.IDHighValueInfoService;

/**
 * 高价值数据导入详情Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DHighValueInfoPreDetailServiceImpl extends ServiceImpl<DHighValueInfoPreDetailMapper, DHighValueInfoPreDetail> implements IDHighValueInfoPreDetailService {
	private static final Logger logger = LoggerFactory.getLogger(DHighValueInfoPreDetailServiceImpl.class);

	
	@Autowired
	private IDHighValueInfoService dHighValueInfoService;
	@Autowired
	private DHighValueInfoPreDetailMapper dHighValueInfoPreDetailMapper;
	
	@Autowired
	private DHighValueInfoPreImpMapper dHighValueInfoPreImpMapper;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	
	
    /**
     * 查询高价值数据导入详情列表
     *
     * @param dHighValueInfoPreDetail 高价值数据导入详情
     * @return 高价值数据导入详情集合
     * @date 2023-03-19
     */
    @Override
    public List<DHighValueInfoPreDetail> queryList(DHighValueInfoPreDetail dHighValueInfoPreDetail) {
        QueryWrapper<DHighValueInfoPreDetail> queryWrapper = Wrappers.query();
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getProvinceCode())  ){
                    queryWrapper.eq("province_code", dHighValueInfoPreDetail.getProvinceCode());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getProvinceName())  ){
                    queryWrapper.like("province_name", dHighValueInfoPreDetail.getProvinceName());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getCityCode())  ){
                    queryWrapper.eq("city_code", dHighValueInfoPreDetail.getCityCode());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getCityName())  ){
                    queryWrapper.like("city_name", dHighValueInfoPreDetail.getCityName());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getAddress())  ){
                    queryWrapper.eq("address", dHighValueInfoPreDetail.getAddress());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getIndustryEmergIndustry())  ){
                    queryWrapper.eq("industry_emerg_industry", dHighValueInfoPreDetail.getIndustryEmergIndustry());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getMaintenanceTenYear())  ){
                    queryWrapper.eq("maintenance_ten_year", dHighValueInfoPreDetail.getMaintenanceTenYear());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getOverseasCongenerPatent())  ){
                    queryWrapper.eq("overseas_congener_patent", dHighValueInfoPreDetail.getOverseasCongenerPatent());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getPledgeRecord())  ){
                    queryWrapper.eq("pledge_record", dHighValueInfoPreDetail.getPledgeRecord());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getNationalScienceAward())  ){
                    queryWrapper.eq("national_science_award", dHighValueInfoPreDetail.getNationalScienceAward());
                }
                if ( StringUtils.isNotEmpty(dHighValueInfoPreDetail.getInventionPatentNumber())  ){
                    queryWrapper.eq("invention_patent_number", dHighValueInfoPreDetail.getInventionPatentNumber());
                }
                if (  StringUtils.isNotNull(dHighValueInfoPreDetail.getStatus())){
                    queryWrapper.eq("status", dHighValueInfoPreDetail.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }

	@Override
	public List<DHighValueInfoPreDetail> doPreImp(DHighValueInfoPreImp imp) {


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

//		//正在解析
//		DHighValueInfoPreImp u1=new DHighValueInfoPreImp();
//		u1.setId(imp.getId());
//		u1.setImpState(PreImpStatus.IMP_ING);
//		uaBranchStaffPreImpMapper.updateDHighValueInfoPreImp(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);
			DHighValueInfoPreImp u2 = new DHighValueInfoPreImp();
			u2.setId(imp.getId());
			u2.setImpState(PreImpStatus.PARSE_ERR);
			dHighValueInfoPreImpMapper.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++) {
			DHighValueInfoPreDetail d = memberPointsDetailList.get(i);
			if(d==null) {
				continue;
			}
			memberPointsDetailList2.add(d);
			logger.debug("开始插入第【" + i + "】行数据（一共【" + memberPointsDetailList.size() + "】行）");
//			DHighValueInfoPreDetail d : memberPointsDetailList
			d.setPreId(imp.getId());
			d.setImpState(ImpStatus.INIT);
			d.setFileName(imp.getFileName());
			d.setImpBatch(imp.getImpBatch());
			dHighValueInfoPreDetailMapper.insert(d);
		}

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

	@Override
	public void doImp(List<DHighValueInfoPreDetail> list, DHighValueInfoPreImp imp) {

		if (list == null || imp == null) {
			return;
		}
		logger.debug("开始处理异步导入数据，imp:" + new Gson().toJson(imp) + ",总记录数:" + list.size());
		
		
		
//		if(StringUtils.isNotBlank(imp.getImpBatch())){
//			dHighValueInfoService.deleteWidthImpBatch(imp.getImpBatch());
//		}
		
		
		List<DHighValueInfoPreDetail> errList = new ArrayList<DHighValueInfoPreDetail>();
		String str = dHighValueInfoService.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());
//		dHighValueInfoService.resetRanking(pointsMonth);
		
		for (int i = 0; i < list.size(); i++) {
			logger.debug("导入完成，向数据库更新状态，当前第[" + i + "]条，一共[" + list.size() + "]条");
			DHighValueInfoPreDetail d = list.get(i);
			DHighValueInfoPreDetail u = new DHighValueInfoPreDetail();
			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);
			}
			dHighValueInfoPreDetailMapper.updateById(u);
		}

		DHighValueInfoPreImp uimp = new DHighValueInfoPreImp();

		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<DHighValueInfoPreDetail> util = new ExcelUtil<DHighValueInfoPreDetail>(DHighValueInfoPreDetail.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);
		}
		
		dHighValueInfoPreImpMapper.updateById(uimp);
		return;
	
	}
}
