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.DPatentAuthInfoPreDetail;
import com.ruoyi.dimp.domain.DPatentAuthInfoPreImp;
import com.ruoyi.dimp.mapper.DPatentAuthInfoPreDetailMapper;
import com.ruoyi.dimp.mapper.DPatentAuthInfoPreImpMapper;
import com.ruoyi.dimp.service.IDPatentAuthInfoPreDetailService;
import com.ruoyi.dimp.service.IDPatentAuthInfoService;

/**
 * 专利授权导入详情Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DPatentAuthInfoPreDetailServiceImpl extends ServiceImpl<DPatentAuthInfoPreDetailMapper, DPatentAuthInfoPreDetail> implements IDPatentAuthInfoPreDetailService {

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

	
	@Autowired
	private IDPatentAuthInfoService dPatentAuthInfoService;
	@Autowired
	private DPatentAuthInfoPreDetailMapper dPatentAuthInfoPreDetailMapper;
	
	@Autowired
	private DPatentAuthInfoPreImpMapper dPatentAuthInfoPreImpMapper;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	
    /**
     * 查询专利授权导入详情列表
     *
     * @param dPatentAuthInfoPreDetail 专利授权导入详情
     * @return 专利授权导入详情集合
     * @date 2023-03-19
     */
    @Override
    public List<DPatentAuthInfoPreDetail> queryList(DPatentAuthInfoPreDetail dPatentAuthInfoPreDetail) {
        QueryWrapper<DPatentAuthInfoPreDetail> queryWrapper = Wrappers.query();
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getApplyNumber())  ){
                    queryWrapper.eq("apply_number", dPatentAuthInfoPreDetail.getApplyNumber());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getAuthInboundDate())  ){
                    queryWrapper.eq("auth_inbound_date", dPatentAuthInfoPreDetail.getAuthInboundDate());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getApplyDate())  ){
                    queryWrapper.eq("apply_date", dPatentAuthInfoPreDetail.getApplyDate());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getInventionName())  ){
                    queryWrapper.like("invention_name", dPatentAuthInfoPreDetail.getInventionName());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getAgencyCode())  ){
                    queryWrapper.eq("agency_code", dPatentAuthInfoPreDetail.getAgencyCode());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getAgencyName())  ){
                    queryWrapper.like("agency_name", dPatentAuthInfoPreDetail.getAgencyName());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getPrincipalClassNumber())  ){
                    queryWrapper.eq("principal_class_number", dPatentAuthInfoPreDetail.getPrincipalClassNumber());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getPatenteeName())  ){
                    queryWrapper.like("patentee_name", dPatentAuthInfoPreDetail.getPatenteeName());
                }
                if (  StringUtils.isNotNull(dPatentAuthInfoPreDetail.getPatenteePostcode())){
                    queryWrapper.eq("patentee_postcode", dPatentAuthInfoPreDetail.getPatenteePostcode());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getPatenteeAddress())  ){
                    queryWrapper.eq("patentee_address", dPatentAuthInfoPreDetail.getPatenteeAddress());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getPatentType())  ){
                    queryWrapper.eq("patent_type", dPatentAuthInfoPreDetail.getPatentType());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getPatenteeType())  ){
                    queryWrapper.eq("patentee_type", dPatentAuthInfoPreDetail.getPatenteeType());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getProvinceName())  ){
                    queryWrapper.like("province_name", dPatentAuthInfoPreDetail.getProvinceName());
                }
                if ( StringUtils.isNotEmpty(dPatentAuthInfoPreDetail.getCityName())  ){
                    queryWrapper.like("city_name", dPatentAuthInfoPreDetail.getCityName());
                }
                if (  StringUtils.isNotNull(dPatentAuthInfoPreDetail.getStatus())){
                    queryWrapper.eq("status", dPatentAuthInfoPreDetail.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }


	@Override
	public List<DPatentAuthInfoPreDetail> doPreImp(DPatentAuthInfoPreImp imp) {

		String fielPath2 = imp.getFilePath();
		ExcelUtil<DPatentAuthInfoPreDetail> util = new ExcelUtil<DPatentAuthInfoPreDetail>(DPatentAuthInfoPreDetail.class);
		List<DPatentAuthInfoPreDetail> memberPointsDetailList;
		List<DPatentAuthInfoPreDetail> memberPointsDetailList2=new ArrayList<DPatentAuthInfoPreDetail>();
//		//正在解析
//		DPatentAuthInfoPreImp u1=new DPatentAuthInfoPreImp();
//		u1.setId(imp.getId());
//		u1.setImpState(PreImpStatus.IMP_ING);
//		uaBranchStaffPreImpMapper.updateDPatentAuthInfoPreImp(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);
			}
			
//			in = new FileInputStream(new File(fielPath2));
//			memberPointsDetailList = util.importExcel(null, in);
		} catch (Exception e) {
			logger.error("授权专利数据读取失败," + e.getMessage(), e);
			DPatentAuthInfoPreImp u2 = new DPatentAuthInfoPreImp();
			u2.setId(imp.getId());
			u2.setImpState(PreImpStatus.PARSE_ERR);
			dPatentAuthInfoPreImpMapper.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++) {
			DPatentAuthInfoPreDetail d = memberPointsDetailList.get(i);
			if(d==null) {
				continue;
			}
			memberPointsDetailList2.add(d);
			
			//20230615
			if(StringUtils.isNotBlank(d.getApplyNumber())) {
				if(d.getApplyNumber().trim().length()==8) {
					d.setApplyNumber("0"+d.getApplyNumber().trim());
				}
			}
			
			logger.debug("开始插入第【" + i + "】行数据（一共【" + memberPointsDetailList.size() + "】行）");
//			DPatentAuthInfoPreDetail d : memberPointsDetailList
			d.setPreId(imp.getId());
			d.setImpState(ImpStatus.INIT);
			d.setFileName(imp.getFileName());
			d.setImpBatch(imp.getImpBatch());
			dPatentAuthInfoPreDetailMapper.insert(d);
		}

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

	@Override
	public void doImp(List<DPatentAuthInfoPreDetail> list, DPatentAuthInfoPreImp imp) {

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

		DPatentAuthInfoPreImp uimp = new DPatentAuthInfoPreImp();

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