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.common.utils.poi.ExcelUtil.CsvContent;
import com.ruoyi.dimp.domain.DPatentEffectiveInfoPreDetail;
import com.ruoyi.dimp.domain.DPatentEffectiveInfoPreImp;
import com.ruoyi.dimp.mapper.DPatentEffectiveInfoPreDetailMapper;
import com.ruoyi.dimp.mapper.DPatentEffectiveInfoPreImpMapper;
import com.ruoyi.dimp.service.IDPatentEffectiveInfoPreDetailService;
import com.ruoyi.dimp.service.IDPatentEffectiveInfoService;

/**
 * 专利有效导入详情Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DPatentEffectiveInfoPreDetailServiceImpl extends ServiceImpl<DPatentEffectiveInfoPreDetailMapper, DPatentEffectiveInfoPreDetail> implements IDPatentEffectiveInfoPreDetailService {
	
	private static final Logger logger = LoggerFactory.getLogger(DPatentEffectiveInfoPreDetailServiceImpl.class);

	@Autowired
	private IDPatentEffectiveInfoService dPatentEffectiveInfoService;
	@Autowired
	private DPatentEffectiveInfoPreDetailMapper dPatentEffectiveInfoPreDetailMapper;
	
	@Autowired
	private DPatentEffectiveInfoPreImpMapper dPatentEffectiveInfoPreImpMapper;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	
    /**
     * 查询专利有效导入详情列表
     *
     * @param dPatentEffectiveInfoPreDetail 专利有效导入详情
     * @return 专利有效导入详情集合
     * @date 2023-03-19
     */
    @Override
    public List<DPatentEffectiveInfoPreDetail> queryList(DPatentEffectiveInfoPreDetail dPatentEffectiveInfoPreDetail) {
        QueryWrapper<DPatentEffectiveInfoPreDetail> queryWrapper = Wrappers.query();
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getAppNumber())  ){
                    queryWrapper.eq("app_number", dPatentEffectiveInfoPreDetail.getAppNumber());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getAuthInboundDate())  ){
                    queryWrapper.eq("auth_inbound_date", dPatentEffectiveInfoPreDetail.getAuthInboundDate());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getAppDate())  ){
                    queryWrapper.eq("app_date", dPatentEffectiveInfoPreDetail.getAppDate());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getInventionName())  ){
                    queryWrapper.like("invention_name", dPatentEffectiveInfoPreDetail.getInventionName());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getAgencyCode())  ){
                    queryWrapper.eq("agency_code", dPatentEffectiveInfoPreDetail.getAgencyCode());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getAgencyName())  ){
                    queryWrapper.like("agency_name", dPatentEffectiveInfoPreDetail.getAgencyName());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getMainClassNumber())  ){
                    queryWrapper.eq("main_class_number", dPatentEffectiveInfoPreDetail.getMainClassNumber());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getPatenteeName())  ){
                    queryWrapper.like("patentee_name", dPatentEffectiveInfoPreDetail.getPatenteeName());
                }
                if (  StringUtils.isNotNull(dPatentEffectiveInfoPreDetail.getPatenteePostcode())){
                    queryWrapper.eq("patentee_postcode", dPatentEffectiveInfoPreDetail.getPatenteePostcode());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getAppliAddress())  ){
                    queryWrapper.eq("appli_address", dPatentEffectiveInfoPreDetail.getAppliAddress());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getPatentType())  ){
                    queryWrapper.eq("patent_type", dPatentEffectiveInfoPreDetail.getPatentType());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getPatenteeType())  ){
                    queryWrapper.eq("patentee_type", dPatentEffectiveInfoPreDetail.getPatenteeType());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getProvinceCode())  ){
                    queryWrapper.eq("province_code", dPatentEffectiveInfoPreDetail.getProvinceCode());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getProvinceName())  ){
                    queryWrapper.like("province_name", dPatentEffectiveInfoPreDetail.getProvinceName());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getCityCode())  ){
                    queryWrapper.eq("city_code", dPatentEffectiveInfoPreDetail.getCityCode());
                }
                if ( StringUtils.isNotEmpty(dPatentEffectiveInfoPreDetail.getCityName())  ){
                    queryWrapper.like("city_name", dPatentEffectiveInfoPreDetail.getCityName());
                }
                if (  StringUtils.isNotNull(dPatentEffectiveInfoPreDetail.getStatus())){
                    queryWrapper.eq("status", dPatentEffectiveInfoPreDetail.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }


    public static void main(String[] args) {
		String file="E:\\9fu\\业务\\云南省知识产权数据统计系统\\数据导入2\\2022年1-12月有效数据(1)\\2022年1-12月有效数据\\33685_202210_有效数据.csv";
		ExcelUtil<DPatentEffectiveInfoPreDetail> util = new ExcelUtil<DPatentEffectiveInfoPreDetail>(DPatentEffectiveInfoPreDetail.class);
//		CsvContent cc=util.readCsv(new File(file));
		try {
			List<DPatentEffectiveInfoPreDetail>list=util.importCsv(new File(file));
			System.out.println("ok");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		System.out.println("ok");
	}
    
    @Override
	public List<DPatentEffectiveInfoPreDetail> doPreImp(DPatentEffectiveInfoPreImp imp) {


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

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

		FileInputStream in = null;
		try {
			
			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);
			DPatentEffectiveInfoPreImp u2 = new DPatentEffectiveInfoPreImp();
			u2.setId(imp.getId());
			u2.setImpState(PreImpStatus.PARSE_ERR);
			dPatentEffectiveInfoPreImpMapper.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++) {
			
			DPatentEffectiveInfoPreDetail d = memberPointsDetailList.get(i);
			if(d==null) {
				continue;
			}
			memberPointsDetailList2.add(d);
			//20230615
			if(StringUtils.isNotBlank(d.getAppNumber())) {
				if(d.getAppNumber().trim().length()==8) {
					d.setAppNumber("0"+d.getAppNumber().trim());
				}
			}
			
			logger.debug("开始插入第【" + i + "】行数据（一共【" + memberPointsDetailList.size() + "】行）");
//			DPatentEffectiveInfoPreDetail d : memberPointsDetailList
			d.setPreId(imp.getId());
			d.setImpState(ImpStatus.INIT);
			d.setFileName(imp.getFileName());
			d.setImpBatch(imp.getImpBatch());
			dPatentEffectiveInfoPreDetailMapper.insert(d);
		}

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

	@Override
	public void doImp(List<DPatentEffectiveInfoPreDetail> list, DPatentEffectiveInfoPreImp imp) {

//		if (list == null || list.isEmpty() || imp == null) {
		if (list == null  || imp == null) {
			return;
		}
		

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

		DPatentEffectiveInfoPreImp uimp = new DPatentEffectiveInfoPreImp();

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