package com.ruoyi.adjust.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.adjust.domain.AsynchExpLog;
import com.ruoyi.adjust.domain.DAdjustSyncLog;
import com.ruoyi.adjust.domain.DPatentDataCollationInfo;
import com.ruoyi.adjust.domain.DPatentDataCollationInfoExp;
import com.ruoyi.adjust.model.batchUpdatePatentDataQO;
import com.ruoyi.adjust.service.IAsynchExpLogService;
import com.ruoyi.adjust.service.IDAdjustSyncLogService;
import com.ruoyi.adjust.service.IDPatentDataCollationInfoService;
import com.ruoyi.adjust.service.IDPatentDataCollationLogService;
import com.ruoyi.adjust.service.impl.AsynchExpLogServiceImpl;
import com.ruoyi.adjust.service.impl.DAdjustSyncLogServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.ApplicantType;
import com.ruoyi.common.constant.HighValue;
import com.ruoyi.common.constant.PatentType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.PojoUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.reportpub.domain.DPatentPubInfo;
import com.ruoyi.reportpub.service.IDPatentPubInfoService;

/**
 * 专利数据整理Controller
 *
 * @author ruoyi
 * @date 2023-03-26
 */
@RestController
@RequestMapping("/adjust/dPatentDataCollationInfo")
public class DPatentDataCollationInfoController extends BaseController {
	private final IDPatentDataCollationInfoService dPatentDataCollationInfoService;

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

	@Autowired
	private RedisCache redisCache;

	@Autowired
	private IAsynchExpLogService asynchExpLogService;;

	private final static String SYNC_KEY = "LAST-SYNC";
	@Autowired
	private IDPatentDataCollationLogService dPatentDataCollationLogService;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	@Autowired
	private IDAdjustSyncLogService dAdjustSyncLogService;
	@Autowired
	private IDPatentPubInfoService dPatentPubInfoService;

	public DPatentDataCollationInfoController(IDPatentDataCollationInfoService dPatentDataCollationInfoService) {
		this.dPatentDataCollationInfoService = dPatentDataCollationInfoService;
	}

	public static class SyncResMode {
		public String syncRes;
		public String syncMsg;
	}

	@GetMapping(value = "/doSync")
	public AjaxResult doSync() {

		DAdjustSyncLog qo = new DAdjustSyncLog();
		qo.setStatus("1");// 同步中
		List<DAdjustSyncLog> list = dAdjustSyncLogService.queryList(qo);
		if (list != null && !list.isEmpty()) {
			SyncResMode res = new SyncResMode();
			res.syncRes = "500";
			res.syncMsg = "正在同步专利统计数据。";
			return AjaxResult.success(res);
		}

		DAdjustSyncLog dAdjustSyncLog = new DAdjustSyncLog();
		dAdjustSyncLog.setBeginSyncTime(new Date());
		dAdjustSyncLog.setStatus("1");// 同步中
		dAdjustSyncLogService.save(dAdjustSyncLog);

		DAdjustSyncLogServiceImpl dAdjustSyncLogServiceImpl = (DAdjustSyncLogServiceImpl) dAdjustSyncLogService;
		DAdjustSyncLogServiceImpl.SynThread synThread = dAdjustSyncLogServiceImpl.newSynThread(dAdjustSyncLog);
		synThread.start();
		SyncResMode res = new SyncResMode();
		res.syncRes = "200";
		res.syncMsg = "系统已接收，请稍后留意数据变化";
		return AjaxResult.success(res);
	}

	@GetMapping(value = "/getLastTime")
	public AjaxResult getLastTime() {

		DAdjustSyncLog qo = new DAdjustSyncLog();
		List<DAdjustSyncLog> list = dAdjustSyncLogService.queryList(qo);
		if (list != null && !list.isEmpty()) {

			if ("1".equals(list.get(0).getStatus())) {
				return AjaxResult.success("成功", "正在同步专利统计数据。");
			} else if ("2".equals(list.get(0).getStatus()) && list.get(0).getEndSyncTime() != null) {
				String lastTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(list.get(0).getEndSyncTime());
				return AjaxResult.success("成功", lastTime);
			} else {
				return AjaxResult.success("成功", "上次同步失败，请重新同步");
			}

		} else {
			return AjaxResult.success("成功", "从末同步");
		}

	}

	/**
	 * 查询专利数据整理列表
	 *
	 * @param dPatentDataCollationInfo 专利数据整理
	 * @return 专利数据整理集合
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:list')")
	@GetMapping("/list")
	public TableDataInfo list(DPatentDataCollationInfo dPatentDataCollationInfo) {

		if (StringUtils.isNotBlank(dPatentDataCollationInfo.getDataType())) {
			dPatentDataCollationInfo.setQueryActive("0");
			dPatentDataCollationInfo.setQueryPub("0");
			dPatentDataCollationInfo.setQueryAuth("0");
			if ("act".equals(dPatentDataCollationInfo.getDataType())) {
				dPatentDataCollationInfo.setQueryActive("1");
			} else if ("pub".equals(dPatentDataCollationInfo.getDataType())) {
				dPatentDataCollationInfo.setQueryPub("1");
			} else {
				dPatentDataCollationInfo.setQueryAuth("1");
			}
		} else {
			dPatentDataCollationInfo.setQueryActive("1");
			dPatentDataCollationInfo.setQueryPub("1");
			dPatentDataCollationInfo.setQueryAuth("1");
		}

//		
		if (StringUtils.isNotBlank(dPatentDataCollationInfo.getAuthInboundDate())) {
			String authInboundDate = dPatentDataCollationInfo.getAuthInboundDate();
			dPatentDataCollationInfo.setAuthInboundDate(authInboundDate.replaceAll("-", ""));
		}

		dPatentDataCollationInfo.setExportNumBegin(null); // 防止和导出的分页冲突
		dPatentDataCollationInfo.setExportNumEnd(null); // 防止和导出的分页冲突
//		if (StringUtils.isNotEmpty(dPatentDataCollationInfo.getTimeValue())) {
//			dPatentDataCollationInfo.setTimeValue(dPatentDataCollationInfo.getTimeValue() + "-00");
//		}
		if (StringUtils.isNotBlank(dPatentDataCollationInfo.getNotThisArea())) {
			if (!"1".equals(dPatentDataCollationInfo.getNotThisArea())) {
				dPatentDataCollationInfo.setNotThisArea(null);
			}
		}
//		notThisArea
		if (StringUtils.isNotBlank(dPatentDataCollationInfo.getAppliCounty()) && "notThisArea".equals(dPatentDataCollationInfo.getAppliCounty())) {
			dPatentDataCollationInfo.setAppliCounty(null);
			dPatentDataCollationInfo.setNotThisArea("1");
		}

		dPatentDataCollationInfo.setAppliTypeCode(dPatentDataCollationInfo.getAppliType());
		if (StringUtils.isNotBlank(dPatentDataCollationInfo.getAppliType())) {
			ApplicantType at = ApplicantType.getByCode(dPatentDataCollationInfo.getAppliType());
			if (at != null) {
				dPatentDataCollationInfo.setAppliType(at.getTypeName());
			}
		}
		dPatentDataCollationInfo.setPatentTypeId(dPatentDataCollationInfo.getPatentType());
		if (StringUtils.isNotBlank(dPatentDataCollationInfo.getPatentType())) {

			PatentType at = PatentType.valueOfById(dPatentDataCollationInfo.getPatentType());
			if (at != null) {
				dPatentDataCollationInfo.setPatentType(at.getTypeName());
			}
		}

//		if(StringUtils.isNotBlank(dPatentDataCollationInfo.getTimeValue())  ) {
//			dPatentDataCollationInfo.setTimeValue(dPatentDataCollationInfo.getTimeValue().replace("-", ""));
//		}

		
		
		startPage();
		List<DPatentDataCollationInfo> list = dPatentDataCollationInfoService.listForAdj(dPatentDataCollationInfo);
//		List<DPatentDataCollationInfo> list = dPatentDataCollationInfoService.queryList(dPatentDataCollationInfo);

		for (DPatentDataCollationInfo data : list) {
			data.setIdStr(data.getDataType() + data.getId());
			if ("act".equals(data.getDataType())) {
				data.setDataTypeStr("有效");
			} else if ("pub".equals(data.getDataType())) {
				data.setDataTypeStr("公开");
			} else if ("auth".equals(data.getDataType())) {
				data.setDataTypeStr("授权");
			}
			if (StringUtils.isNotBlank(data.getAppliAddress()) && data.getAppliAddress().trim().contains("云南省")) {
				data.setAppliAddress(data.getAppliAddress().trim().substring(data.getAppliAddress().indexOf("云南省")));
			}
			if (StringUtils.isNotBlank(data.getModifyAppliAddress()) && data.getModifyAppliAddress().trim().contains("云南省")) {
				data.setModifyAppliAddress(data.getModifyAppliAddress().trim().substring(data.getModifyAppliAddress().indexOf("云南省")));
			}

			// 高价值
			data.setHighValueStr(getHightValueStr(data.getHighValue()));

			ApplicantType appliTypeSrc = ApplicantType.getByCode(data.getAppliTypeSrc());
			if (appliTypeSrc != null) {
				data.setAppliTypeSrcStr(appliTypeSrc.getTypeName());
				data.setAppliTypeSrc(appliTypeSrc.getTypeName());
			} else {
				data.setAppliTypeSrcStr(data.getAppliTypeSrc());
			}
			data.setInboundDate(data.getCreateTime());// 入库时间
			ApplicantType appliType = ApplicantType.getByCode(data.getAppliType());
			if (appliType != null) {
				data.setAppliTypeStr(appliType.getTypeName());
				data.setAppliType(appliType.getTypeName());
			} else {
				data.setAppliTypeStr(data.getAppliType());
			}

//			<el-table-column label="申请人类型（原始）" align="center" prop="appliTypeSrc" />
//	        <el-table-column label="申请人类型" align="center" prop="appliType" />
		}
		return getDataTable(list);
	}

	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:export')")
	// @Log(title = "专利数据整理", businessType = BusinessType.EXPORT)
	@PostMapping("/syncExport")
	public void syncExport(@RequestBody DPatentDataCollationInfo dPatentDataCollationInfo, HttpServletResponse response) {
		logger.debug("收到异步导出请求," + new Gson().toJson(dPatentDataCollationInfo));
		doDxport(dPatentDataCollationInfo, response, true);
	}

	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:export')")
	// @Log(title = "专利数据整理", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(DPatentDataCollationInfo dPatentDataCollationInfo, HttpServletResponse response) {
		logger.debug("收到同步导出请求," + new Gson().toJson(dPatentDataCollationInfo));
		doDxport(dPatentDataCollationInfo, response, false);
	}

	private void doDxport(DPatentDataCollationInfo dPatentDataCollationInfo, HttpServletResponse response, boolean sync) {
		long startTime = System.currentTimeMillis();
		try {
			String username = getUsername();
			if (StringUtils.isNotBlank(dPatentDataCollationInfo.getAppliType())) {
				ApplicantType at = ApplicantType.getByCode(dPatentDataCollationInfo.getAppliType());
				if (at != null) {
					dPatentDataCollationInfo.setAppliType(at.getTypeName());
				}
			}

			dPatentDataCollationInfo.setAppliTypeCode(dPatentDataCollationInfo.getAppliType());

			dPatentDataCollationInfo.setPatentTypeId(dPatentDataCollationInfo.getPatentType());
			if (StringUtils.isNotBlank(dPatentDataCollationInfo.getPatentType())) {
				PatentType at = PatentType.valueOfById(dPatentDataCollationInfo.getPatentType());
				if (at != null) {
					dPatentDataCollationInfo.setPatentType(at.getTypeName());
				}
			}

//			if(StringUtils.isNotBlank(dPatentDataCollationInfo.getTimeValue())  ) {
//				dPatentDataCollationInfo.setTimeValue(dPatentDataCollationInfo.getTimeValue().replace("-", ""));
//			}

			if (StringUtils.isNotBlank(dPatentDataCollationInfo.getAuthInboundDate())) {
				String authInboundDate = dPatentDataCollationInfo.getAuthInboundDate();
				dPatentDataCollationInfo.setAuthInboundDate(authInboundDate.replaceAll("-", ""));
			}

			if (StringUtils.isNotBlank(dPatentDataCollationInfo.getDataType())) {
				dPatentDataCollationInfo.setQueryActive("0");
				dPatentDataCollationInfo.setQueryPub("0");
				dPatentDataCollationInfo.setQueryAuth("0");
				if ("act".equals(dPatentDataCollationInfo.getDataType())) {
					dPatentDataCollationInfo.setQueryActive("1");
				} else if ("pub".equals(dPatentDataCollationInfo.getDataType())) {
					dPatentDataCollationInfo.setQueryPub("1");
				} else {
					dPatentDataCollationInfo.setQueryAuth("1");
				}
			} else {
				dPatentDataCollationInfo.setQueryActive("1");
				dPatentDataCollationInfo.setQueryPub("1");
				dPatentDataCollationInfo.setQueryAuth("1");
			}
//			if (StringUtils.isNotEmpty(dPatentDataCollationInfo.getTimeValue())) {
//				dPatentDataCollationInfo.setTimeValue(dPatentDataCollationInfo.getTimeValue() + "-00");
//			}
			if (StringUtils.isNotBlank(dPatentDataCollationInfo.getNotThisArea())) {
				if (!"1".equals(dPatentDataCollationInfo.getNotThisArea())) {
					dPatentDataCollationInfo.setNotThisArea(null);
				}
			}
//			notThisArea
			if (StringUtils.isNotBlank(dPatentDataCollationInfo.getAppliCounty()) && "notThisArea".equals(dPatentDataCollationInfo.getAppliCounty())) {
				dPatentDataCollationInfo.setAppliCounty(null);
				dPatentDataCollationInfo.setNotThisArea("1");
			}

			// 前端传了要导出的字段列表过来
			String expFields = dPatentDataCollationInfo.getExpFields();
			if (expFields == null) {
				expFields = "";
			}
			// 申请人类型（原始）
			if (expFields.contains("appliTypeSrc")) {
				expFields = expFields.replace("appliTypeSrc", "appli55TypeSrcStr");
			}
			// 申请人类型
			if (expFields.contains("appliType")) {
				expFields = expFields.replace("appliType", "appliTypeStr");
			}
			if (expFields.contains("appli55TypeSrcStr")) {
				expFields = expFields.replace("appli55TypeSrcStr", "appliTypeSrcStr");
			}
			if (expFields.contains("highValue")) {
				expFields = expFields.replace("highValue", "highValueStr");
			}
			if (expFields.contains("patentType")) {
				expFields = expFields.replace("patentType", "patentTypeStr");
			}
			if (expFields.contains("currPatentStatus")) {
				expFields = expFields.replace("currPatentStatus", "currPatentStatusStr");
			}
			// 是否为勾选导出
			if (dPatentDataCollationInfo.getExportFlag() == null) {
				dPatentDataCollationInfo.setExportFlag(false);
			}
			
			
			
			if (dPatentDataCollationInfo.getExportFlag()) {
				String[] expFieldArr = null;
				if (StringUtils.isNotBlank(expFields)) {
					expFieldArr = expFields.trim().split(",");// 按逗号分隔为数组
				}

				List<DPatentDataCollationInfoExp> list = new ArrayList<DPatentDataCollationInfoExp>();
				Type type = new TypeToken<ArrayList<DPatentDataCollationInfoExp>>() {
				}.getType();
				list = new Gson().fromJson(dPatentDataCollationInfo.getPatentData(), type);

				for (DPatentDataCollationInfoExp exp : list) {
					HighValue hv = HighValue.valueOf(exp.getHighValue());
					if (hv != null) {
						exp.setHighValueStr(hv.getTypeName());
					} else {
						exp.setHighValueStr(exp.getHighValue());
					}

					if (StringUtils.isNotBlank(exp.getPatentType())) {
						PatentType pt = PatentType.valueOf(exp.getPatentType());
						if (pt != null) {
							exp.setPatentTypeStr(pt.getTypeName2());
						} else {
							exp.setPatentTypeStr(exp.getPatentType());
						}
					}
					if (StringUtils.isNotBlank(exp.getCurrPatentStatus())) {
						if ("10".equals(exp.getCurrPatentStatus())) {
							exp.setCurrPatentStatusStr("有效");
						} else if ("30".equals(exp.getCurrPatentStatus())) {
							exp.setCurrPatentStatusStr("公开");
						} else {
							exp.setCurrPatentStatusStr("无效");
						}
					}

				}
//				ObjectMapper mapper = new ObjectMapper();
//				List<DPatentDataCollationInfoExp> list = mapper.readValue(dPatentDataCollationInfo.getPatentData(),
//						new TypeReference<List<DPatentDataCollationInfoExp>>() {
//						});
				int size = list.size();
				final List<DPatentDataCollationInfoExp> extList = new ArrayList<>();
				extList.addAll(list);
				if (sync) {
					Thread thread = new Thread() {
						public void run() {
							logger.debug("开始异步导出数据,总记录数:" + size);
							doSyncExport(extList, username, dPatentDataCollationInfo.getDataType());
							logger.debug("异步导出数据完成");
						}
					};
					thread.setDaemon(true);
					thread.setName(Thread.currentThread().getName() + "_" + dPatentDataCollationInfo.getDataType());
					thread.start();
					response.setCharacterEncoding("utf-8");
					String msg = new Gson().toJson(AjaxResult.success("系统已接收"));
					response.getWriter().println(msg);
					return;

				} else {
					ExcelUtil<DPatentDataCollationInfoExp> util = new ExcelUtil<>(DPatentDataCollationInfoExp.class, expFieldArr);// 现在多传入一个要导出的字段列表
					util.exportExcel(response, list, "专利数据整理数据");
					return;

				}

			} else {

				if (dPatentDataCollationInfo.getExportNumBegin() == null) {
					dPatentDataCollationInfo.setExportNumBegin(0);
				}
				// TODO 20230423 因为limit的第二个参数是总记录数，这里要转换成总数
				if (dPatentDataCollationInfo.getExportNumEnd() == null) {
					dPatentDataCollationInfo.setExportNumEnd(10);// 默认只导入10条
				} else if (dPatentDataCollationInfo.getExportNumEnd() < dPatentDataCollationInfo.getExportNumBegin()) {
					throw new RuntimeException("结束行不能小于开始行");

				} else {
					// 转换成总记录数
					dPatentDataCollationInfo.setExportNumEnd(dPatentDataCollationInfo.getExportNumEnd() - dPatentDataCollationInfo.getExportNumBegin() + 1);
				}

				// PS:因为limit是从0开始计算的，所以需要将开始条数减1
				dPatentDataCollationInfo.setExportNumBegin(dPatentDataCollationInfo.getExportNumBegin() - 1);

				// 数据类型
//				if (expFields.contains("dataTypeStr")) {
//					expFields = expFields.replace("dataTypeStr", "dataType");
//				}
				// 申请人类型（原始）
				String[] expFieldArr = null;
				if (StringUtils.isNotBlank(expFields)) {
					expFieldArr = expFields.trim().split(",");// 按逗号分隔为数组
				}

				if (sync) {
					Thread thread = new Thread() {
						public void run() {
							long beginTime = System.currentTimeMillis();
							Integer numberEnd = dPatentDataCollationInfo.getExportNumEnd();
							if (numberEnd == null) {
								numberEnd = 0;
							}
							logger.debug("开始异步导出数据，最大记录数:" + numberEnd);

							//
							String dataType = dPatentDataCollationInfo.getDataType();
							String expPath = getExpFilePath();

							String seq = Seq.getId();

//								String expFile = expPath + "/subsidies_" + seq;

							String fileName = dataType + "_" + seq;

							String xlsFileName = fileName + ".xlsx";
							String xlsFile = expPath + "/" + xlsFileName;

							AsynchExpLog asynchExpLog = new AsynchExpLog();

							String dataTypeName = dataType;
							if ("act".equals(dataType)) {
								dataTypeName = "有效";
							} else if ("pub".equals(dataType)) {
								dataTypeName = "公开";
							} else if ("auth".equals(dataType)) {
								dataTypeName = "授权";
							}

							// 异步
							// 入库
							asynchExpLog.setDataType(dataType);
							asynchExpLog.setDataTypeName(dataTypeName + "专利数据");
							asynchExpLog.setFileName(xlsFileName);
							asynchExpLog.setFilePath(xlsFile);
							String fileUrl = xlsFile.replace(RuoYiConfig.getProfile(), ruoYiConfig.getFilePath() + "/profile");
							asynchExpLog.setFileUrl(fileUrl);

							asynchExpLog.setExpStatus("0");// 未导出
							asynchExpLog.setExpDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
							asynchExpLog.setCreateBy(username);
							asynchExpLog.setCreateTime(new Date());
							asynchExpLog.setTotalCnt(Long.parseLong(numberEnd + ""));
							logger.debug("导出记录入库，状态:"+asynchExpLog.getExpStatus());
							asynchExpLogService.insertAsynchExpLog(asynchExpLog);
							ExcelUtil.ExpStatus staus = new ExcelUtil.ExpStatus();
							AsynchExpLogServiceImpl.EXP_STATUS_MAP.put("DPatentDataCollationInfoExp-" + asynchExpLog.getId(), staus);
							//故意把入库时间搞久一点
//							try {
//								Thread.sleep(10000);
//							} catch (InterruptedException e) {
//								// TODO Auto-generated catch block
//								e.printStackTrace();
//							}
							logger.debug("开始预导出...");
							List<DPatentDataCollationInfoExp> expList = preSyncExp(dPatentDataCollationInfo);
//								List<DPatentDataCollationInfoExp> list, String username,String dataType,String xlsFile,String dataTypeName,long beginTime,AsynchExpLog asynchExpLog
							doSyncExport(expList, username, dataType, xlsFile, dataTypeName, beginTime, asynchExpLog);
							logger.debug("异步导出数据完成");
						}
					};
					thread.setDaemon(true);
					thread.setName(Thread.currentThread().getName() + "_" + dPatentDataCollationInfo.getDataType());
					thread.start();
					response.setCharacterEncoding("utf-8");
					String msg = new Gson().toJson(AjaxResult.success("系统已接收"));
					response.getWriter().println(msg);
					return;
				} else {
					List<DPatentDataCollationInfoExp> expList = preSyncExp(dPatentDataCollationInfo);
					ExcelUtil<DPatentDataCollationInfoExp> util = new ExcelUtil<>(DPatentDataCollationInfoExp.class, expFieldArr);// 现在多传入一个要导出的字段列表
					util.exportExcel(response, expList, "专利数据整理数据");
					return;
				}

			}
		} catch (Exception e) {
			logger.error("导出失败，原因：" + e.getMessage(), e, e);
			// PS:如果导出失败报错；请先检查DPatentDataCollationInfoCopy这个类中的属性
			// 是否与DPatentDataCollationInfo这个类中的属性保持一致，不一致的话会导致报错
			throw new RuntimeException("导出失败,请联系管理员！");
		}
//		long endTime = System.currentTimeMillis();
//		long timeElapsed = endTime - startTime;
//		System.out.println("方法执行时间：" + timeElapsed + "毫秒");
	}

	private List<DPatentDataCollationInfoExp> preSyncExp(DPatentDataCollationInfo dPatentDataCollationInfo) {
		List<DPatentDataCollationInfo> list = dPatentDataCollationInfoService.listForAdj(dPatentDataCollationInfo);
		List<DPatentDataCollationInfoExp> expList = new ArrayList<DPatentDataCollationInfoExp>();
		for (DPatentDataCollationInfo pc : list) {
			pc.setInboundDate(pc.getCreateTime());// 入库时间
			DPatentDataCollationInfoExp exp = PojoUtils.copyTo(DPatentDataCollationInfoExp.class, pc);
			if (pc.getStatus() != null) {
				if (pc.getStatus().longValue() == 10L) {
					exp.setStatusStr("有效");
				} else if (pc.getStatus().longValue() == 20L) {
					exp.setStatusStr("无效");
				} else if (pc.getStatus().longValue() == 30L) {
					exp.setStatusStr("公开");
				} else {
					exp.setStatusStr("末知" + pc.getStatus());
				}
			} else {
				exp.setStatusStr("末知");
			}

			if (StringUtils.isNotBlank(pc.getPatentType())) {
				PatentType pt = PatentType.valueOf(pc.getPatentType());
				if (pt != null) {
					exp.setPatentTypeStr(pt.getTypeName2());
				} else {
					exp.setPatentTypeStr(pc.getPatentType());
				}
			}
			if (StringUtils.isNotBlank(pc.getCurrPatentStatus())) {
				if ("10".equals(pc.getCurrPatentStatus())) {
					exp.setCurrPatentStatusStr("有效");
				} else if ("30".equals(pc.getCurrPatentStatus())) {
					exp.setCurrPatentStatusStr("公开");
				} else {
					exp.setCurrPatentStatusStr("无效");
				}
			}
			expList.add(exp);
		}

		for (DPatentDataCollationInfoExp data : expList) {
//			data.setIdStr(data.getDataType() + data.getId());
			if ("act".equals(data.getDataType())) {
				data.setDataTypeStr("有效");
			} else if ("pub".equals(data.getDataType())) {
				data.setDataTypeStr("公开");
			} else if ("auth".equals(data.getDataType())) {
				data.setDataTypeStr("授权");
			}

			data.setHighValueStr(getHightValueStr(data.getHighValue()));

			if (StringUtils.isNotBlank(data.getAppliAddress()) && data.getAppliAddress().trim().startsWith("云南省")
					&& data.getAppliAddress().trim().contains("云南省")) {
				data.setAppliAddress(data.getAppliAddress().trim().substring(data.getAppliAddress().indexOf("云南省")));
			}
			if (StringUtils.isNotBlank(data.getModifyAppliAddress()) && data.getModifyAppliAddress().trim().startsWith("云南省")
					&& data.getModifyAppliAddress().trim().contains("云南省")) {
				data.setAppliAddress(data.getModifyAppliAddress().trim().substring(data.getModifyAppliAddress().indexOf("云南省")));
			}

			ApplicantType appliTypeSrc = ApplicantType.getByCode(data.getAppliTypeSrc());
			if (appliTypeSrc != null) {
				data.setAppliTypeSrcStr(appliTypeSrc.getTypeName());
				data.setAppliTypeSrc(appliTypeSrc.getTypeName());
			} else {
				data.setAppliTypeSrcStr(data.getAppliTypeSrc());
			}

			ApplicantType appliType = ApplicantType.getByCode(data.getAppliType());
			if (appliType != null) {
				data.setAppliTypeStr(appliType.getTypeName());
				data.setAppliType(appliType.getTypeName());
			} else {
				data.setAppliTypeStr(data.getAppliType());
			}

//			<el-table-column label="申请人类型（原始）" align="center" prop="appliTypeSrc" />
//	        <el-table-column label="申请人类型" align="center" prop="appliType" />
		}
		return expList;
	}

	private String getExpFilePath() {
		StringBuffer sb = new StringBuffer();
		sb.append(RuoYiConfig.getDownloadPath());
//		sb.append("/");
		sb.append(DateUtils.datePath());
		String path = sb.toString();
		File pathFile = new File(path);
		if (!pathFile.exists()) {
			pathFile.mkdirs();
		}
		return path;
	}

	private String doSyncExport(List<DPatentDataCollationInfoExp> list, String username, String dataType) {
		long beginTime = System.currentTimeMillis();
		if (list != null && !list.isEmpty()) {
			for (DPatentDataCollationInfoExp m : list) {
//				m.setAreaStr(areaService.getAreaStr(m.getProvinceCode(), m.getCityCode(), m.getAreaCode()));
//				m.setMemberName(desensityName(m.getMemberName()));
//				m.setContactPhone(desensityPhone(m.getContactPhone()));
//				m.setName(desensityName(m.getName()));
			}
		}

		String expPath = getExpFilePath();

		String seq = Seq.getId();

//		String expFile = expPath + "/subsidies_" + seq;

		String fileName = dataType + "_" + seq;

		String xlsFileName = fileName + ".xlsx";
		String xlsFile = expPath + "/" + xlsFileName;

		AsynchExpLog asynchExpLog = new AsynchExpLog();

		String dataTypeName = dataType;
		if ("act".equals(dataType)) {
			dataTypeName = "有效";
		} else if ("pub".equals(dataType)) {
			dataTypeName = "公开";
		} else if ("auth".equals(dataType)) {
			dataTypeName = "授权";
		}

		// 异步
		// 入库
		asynchExpLog.setDataType(dataType);
		asynchExpLog.setDataTypeName(dataTypeName + "专利数据");
		asynchExpLog.setFileName(xlsFileName);
		asynchExpLog.setFilePath(xlsFile);
		String fileUrl = xlsFile.replace(RuoYiConfig.getProfile(), ruoYiConfig.getFilePath() + "/profile");
		asynchExpLog.setFileUrl(fileUrl);
//		http://10.253.228.73:9000/prod-api/profile//download/2023/10/17/act_20231017142655A003.xlsx
		asynchExpLog.setExpStatus("1");// 导出中
		asynchExpLog.setExpDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		asynchExpLog.setCreateBy(username);
		asynchExpLog.setCreateTime(new Date());
		asynchExpLog.setTotalCnt(Long.parseLong(list.size() + ""));

		asynchExpLogService.insertAsynchExpLog(asynchExpLog);
		ExcelUtil.ExpStatus staus = new ExcelUtil.ExpStatus();
		AsynchExpLogServiceImpl.EXP_STATUS_MAP.put("DPatentDataCollationInfoExp-" + asynchExpLog.getId(), staus);
//		List<DPatentDataCollationInfoExp> list, String username,String dataType,String xlsFile,String dataTypeName,long beginTime,AsynchExpLog asynchExpLog

		return doSyncExport(list, username, dataType, xlsFile, dataTypeName, beginTime, asynchExpLog);
	}

	private String doSyncExport(List<DPatentDataCollationInfoExp> list, String username, String dataType, String xlsFile, String dataTypeName, long beginTime,
			AsynchExpLog asynchExpLog) {
		

		FileOutputStream xlsOut = null;

		try {
			logger.debug("开始异步专利整理数据,修改记录为导出中...");
			AsynchExpLog up = new AsynchExpLog();
			up.setId(asynchExpLog.getId());
			up.setExpStatus("1");//导出中
			up.setTotalCnt(Long.parseLong(list.size() + ""));
			asynchExpLogService.updateAsynchExpLog(up);
			
			ExcelUtil.ExpStatus staus = AsynchExpLogServiceImpl.EXP_STATUS_MAP.get("DPatentDataCollationInfoExp-" + asynchExpLog.getId());
			if(staus==null) {
				staus = new ExcelUtil.ExpStatus();
				AsynchExpLogServiceImpl.EXP_STATUS_MAP.put("DPatentDataCollationInfoExp-" + asynchExpLog.getId(), staus);
			}
			xlsOut = new FileOutputStream(new File(xlsFile));
			
			ExcelUtil<DPatentDataCollationInfoExp> util = new ExcelUtil<DPatentDataCollationInfoExp>(DPatentDataCollationInfoExp.class);
			util.exportExcel(xlsOut, list, dataTypeName + "数据整理数据", staus);
			AsynchExpLog u = new AsynchExpLog();
			u.setId(asynchExpLog.getId());
			u.setUpdateBy(username);
			u.setUpdateTime(new Date());
			long endTime = System.currentTimeMillis();
			u.setExpUsedTime((endTime - beginTime) / 1000);
			u.setExpStatus("2");//导出成功
			logger.debug("导出成功了，准备更新到库,id:"+u.getId());
			asynchExpLogService.updateAsynchExpLog(u);

		} catch (Exception e) {

			logger.error("导出失败," + e.getMessage(), e);

			AsynchExpLog u = new AsynchExpLog();
			u.setId(asynchExpLog.getId());
			u.setUpdateBy(username);
			u.setUpdateTime(new Date());
			u.setExpStatus("3");//导出失败
			String reason = e.getMessage();
			if (reason.length() > 3000) {
				reason = reason.substring(0, 3000);
			}
			u.setErrReason(reason);
			asynchExpLogService.updateAsynchExpLog(u);
		} finally {

			if (xlsOut != null) {
				try {
					AsynchExpLogServiceImpl.EXP_STATUS_MAP.remove("DPatentDataCollationInfoExp-" + asynchExpLog.getId());
					xlsOut.close();
				} catch (IOException e) {
				}
			}

		}
		return xlsFile;
	}

	private String getHightValueStr(String hightValue) {
		if (StringUtils.isBlank(hightValue)) {
			return null;
		}
		hightValue = hightValue.trim();
		String[] hightValues = hightValue.split(",");
		StringBuffer sb = new StringBuffer();
		Set<String> hvs = new HashSet<String>();
		for (int i = 0; i < hightValues.length; i++) {
			String hvid = hightValues[i];
			if (hvs.contains(hvid)) {
				continue;
			}
			hvs.add(hvid);
			HighValue hv = HighValue.valueOf(hvid);
			if (hv == null) {
				continue;
			}

			if (i > 0) {
				sb.append(",");
			}
			sb.append(hv.getTypeName().replace("的有效发明专利", ""));
		}

		return sb.toString();
	}

	/**
	 * 获取专利数据整理详细信息
	 *
	 * @param id 主键id
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(dPatentDataCollationInfoService.getById(id));
	}
	
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:query')")
	@GetMapping(value = "/getPubInfo")
	public AjaxResult getPubInfo( String appNumber) {
		DPatentPubInfo pub = dPatentPubInfoService.queryByAppNumber(appNumber, false);
		
		if(pub!=null && StringUtils.isBlank(pub.getModifyCownerAddress())) {
			pub.setModifyCownerAddress(pub.getCownerAddress());
		}
		return AjaxResult.success(pub);
	} 

	/**
	 * 新增专利数据整理信息
	 *
	 * @param dPatentDataCollationInfo 专利数据整理
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:add')")
	// @Log(title = "专利数据整理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody DPatentDataCollationInfo dPatentDataCollationInfo) {
		return toAjax(dPatentDataCollationInfoService.save(dPatentDataCollationInfo));
	}

	/**
	 * 修改专利数据整理信息
	 *
	 * @param dPatentDataCollationInfo 专利数据整理
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:edit')")
	// @Log(title = "专利数据整理", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody DPatentDataCollationInfo dPatentDataCollationInfo) {
		return dPatentDataCollationInfoService.edit(dPatentDataCollationInfo);
	}

	/**
	 * 修改专利数据整理信息
	 *
	 * @param patentDataQO 专利数据整理列表QO
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:edit')")
	// @Log(title = "专利数据整理", businessType = BusinessType.UPDATE)
	@PutMapping("batch/update")
	public AjaxResult batchUpdateList(@RequestBody batchUpdatePatentDataQO patentDataQO) {
		return dPatentDataCollationInfoService.batchUpdateList(patentDataQO);
	}

	/**
	 * 删除专利数据整理信息
	 *
	 * @param ids 主键ids
	 * @return 结果
	 * @date 2023-03-26
	 */
	@PreAuthorize("@ss.hasPermi('adjust:dPatentDataCollationInfo:remove')")
	// @Log(title = "专利数据整理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(dPatentDataCollationInfoService.removeByIds(Arrays.asList(ids)));
	}

}
