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.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.DPctApplyInfoPreDetail;
import com.ruoyi.dimp.domain.DPctApplyInfoPreImp;
import com.ruoyi.dimp.domain.DPctApplyInfoPreDetail;
import com.ruoyi.dimp.domain.DPctApplyInfoPreImp;
import com.ruoyi.dimp.mapper.DPctApplyInfoPreDetailMapper;
import com.ruoyi.dimp.mapper.DPctApplyInfoPreImpMapper;
import com.ruoyi.dimp.mapper.DPctApplyInfoPreDetailMapper;
import com.ruoyi.dimp.service.IDPctApplyInfoService;
import com.ruoyi.dimp.service.IDPctApplyInfoPreDetailService;

/**
 * PCT申请导入详情Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@Service
public class DPctApplyInfoPreDetailServiceImpl extends ServiceImpl<DPctApplyInfoPreDetailMapper, DPctApplyInfoPreDetail> implements IDPctApplyInfoPreDetailService {

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

	@Autowired
	private IDPctApplyInfoService dPctApplyInfoService;
	@Autowired
	private DPctApplyInfoPreDetailMapper dPctApplyInfoPreDetailMapper;
	
	@Autowired
	private DPctApplyInfoPreImpMapper dPctApplyInfoPreImpMapper;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	
    /**
     * 查询PCT申请导入详情列表
     *
     * @param dPctApplyInfoPreDetail PCT申请导入详情
     * @return PCT申请导入详情集合
     * @date 2023-03-19
     */
    @Override
    public List<DPctApplyInfoPreDetail> queryList(DPctApplyInfoPreDetail dPctApplyInfoPreDetail) {
        QueryWrapper<DPctApplyInfoPreDetail> queryWrapper = Wrappers.query();
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getApplyNumber())  ){
                    queryWrapper.eq("apply_number", dPctApplyInfoPreDetail.getApplyNumber());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getReceiptDate())  ){
                    queryWrapper.eq("receipt_date", dPctApplyInfoPreDetail.getReceiptDate());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getMainClassNumber())  ){
                    queryWrapper.eq("main_class_number", dPctApplyInfoPreDetail.getMainClassNumber());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getApplyCountry())  ){
                    queryWrapper.eq("apply_country", dPctApplyInfoPreDetail.getApplyCountry());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getProvinceCode())  ){
                    queryWrapper.eq("province_code", dPctApplyInfoPreDetail.getProvinceCode());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getProvinceName())  ){
                    queryWrapper.like("province_name", dPctApplyInfoPreDetail.getProvinceName());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getCityCode())  ){
                    queryWrapper.eq("city_code", dPctApplyInfoPreDetail.getCityCode());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getCityName())  ){
                    queryWrapper.like("city_name", dPctApplyInfoPreDetail.getCityName());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getApplyStreet())  ){
                    queryWrapper.eq("apply_street", dPctApplyInfoPreDetail.getApplyStreet());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getApplyEnglishCity())  ){
                    queryWrapper.eq("apply_english_city", dPctApplyInfoPreDetail.getApplyEnglishCity());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getApplyEnglishStreet())  ){
                    queryWrapper.eq("apply_english_street", dPctApplyInfoPreDetail.getApplyEnglishStreet());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getInternApplyDay())  ){
                    queryWrapper.eq("intern_apply_day", dPctApplyInfoPreDetail.getInternApplyDay());
                }
                if ( StringUtils.isNotEmpty(dPctApplyInfoPreDetail.getIsPay())  ){
                    queryWrapper.eq("is_pay", dPctApplyInfoPreDetail.getIsPay());
                }
                if (  StringUtils.isNotNull(dPctApplyInfoPreDetail.getStatus())){
                    queryWrapper.eq("status", dPctApplyInfoPreDetail.getStatus());
                }
        queryWrapper.orderByDesc("id");
        return this.list(queryWrapper);
    }




    @Override
	public List<DPctApplyInfoPreDetail> doPreImp(DPctApplyInfoPreImp imp) {


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

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

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

	@Override
	public void doImp(List<DPctApplyInfoPreDetail> list, DPctApplyInfoPreImp imp) {

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

		DPctApplyInfoPreImp uimp = new DPctApplyInfoPreImp();

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