package com.ruoyi.dimp.controller;

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.adjust.domain.DAdjustSyncLog;
import com.ruoyi.adjust.domain.DPatentDataCollationLog;
import com.ruoyi.adjust.service.IDAdjustSyncLogService;
import com.ruoyi.adjust.service.IDPatentDataCollationInfoService;
import com.ruoyi.adjust.service.IDPatentDataCollationLogService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.PreImpStatus;
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.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.dimp.domain.DPatentAuthInfoExp;
import com.ruoyi.dimp.domain.DPatentAuthInfoPreDetail;
import com.ruoyi.dimp.domain.DPatentAuthInfoPreImp;
import com.ruoyi.dimp.service.IDPatentAuthInfoPreDetailService;
import com.ruoyi.dimp.service.IDPatentAuthInfoPreImpService;

/**
 * 专利授权导入记录Controller
 *
 * @author ruoyi
 * @date 2023-03-19
 */
@RestController
@RequestMapping("/dimp/dPatentAuthInfoPreImp")
public class DPatentAuthInfoPreImpController extends BaseController {
	private final IDPatentAuthInfoPreImpService dPatentAuthInfoPreImpService;
	@Autowired
	private IDPatentAuthInfoPreDetailService dPatentAuthInfoPreDetailService;
	
	 @Autowired
		private RuoYiConfig ruoYiConfig;
	    @Autowired
		private IDPatentDataCollationLogService dPatentDataCollationLogService;
		@Autowired
		private IDAdjustSyncLogService dAdjustSyncLogService;
		@Autowired
		private IDPatentDataCollationInfoService dPatentDataCollationInfoService;

	public DPatentAuthInfoPreImpController(IDPatentAuthInfoPreImpService dPatentAuthInfoPreImpService) {
		this.dPatentAuthInfoPreImpService = dPatentAuthInfoPreImpService;
	}

	@PostMapping("/importTemplate")
	public void importTemplate(HttpServletResponse response) {
		ExcelUtil<DPatentAuthInfoExp> util = new ExcelUtil<DPatentAuthInfoExp>(DPatentAuthInfoExp.class);
		List<DPatentAuthInfoExp> list = new ArrayList<DPatentAuthInfoExp>();
		util.exportExcel(response, list, "专利授权数据");
	}

	@PostMapping("/import")
	@Log(title = "专利授权数据导入", businessType = BusinessType.IMPORT)
	@ResponseBody
	public AjaxResult importData(MultipartFile file,HttpServletRequest req) throws Exception {
		
		String impBatch = req.getParameter("impBatch");
    	if(impBatch!=null) {
    		impBatch=impBatch.replace("-", "").trim();
    	}
    	
    	if(StringUtils.isBlank(impBatch)  || "null".equalsIgnoreCase(impBatch)) {
			throw new RuntimeException("导入批次不能为空");
		}
    	
    	
		DPatentAuthInfoPreImp imp = dPatentAuthInfoPreImpService.importData(file,impBatch);
		// 正在解析
		DPatentAuthInfoPreImp u1 = new DPatentAuthInfoPreImp();
		u1.setId(imp.getId());
		u1.setImpState(PreImpStatus.IMP_ING);
		dPatentAuthInfoPreImpService.updateById(u1);
		Thread pdImpThread = new Thread() {
			public void run() {
				try {
					// 预处理
					List<DPatentAuthInfoPreDetail> list = dPatentAuthInfoPreDetailService.doPreImp(imp);
					if(list==null || list.isEmpty()) {
						DPatentAuthInfoPreImp u1 = new DPatentAuthInfoPreImp();
						u1.setId(imp.getId());
						u1.setImpState(PreImpStatus.PARSE_ERR);
						String errReason = "没有读到数据，可能模板错误或空文件";
						u1.setErrReason(errReason);
						dPatentAuthInfoPreImpService.updateById(u1);
						return;
					}
					// 处理
					dPatentAuthInfoPreDetailService.doImp(list, imp);
					
					
////					重新统计数据	20230710	
//					DPatentDataCollationLog log=new DPatentDataCollationLog();
//					log.setAdjustType("batch");
//					log.setSameFalg("1");
//					log.setSyncStatus("0");
//					log.setRemark("导入auth数据后生成");
//					dPatentDataCollationLogService.save(log);
//					
//					DAdjustSyncLog dAdjustSyncLog = new DAdjustSyncLog();
//					dAdjustSyncLog.setBeginSyncTime(new Date());
//					dAdjustSyncLog.setStatus("1");// 同步中
//					dAdjustSyncLogService.save(dAdjustSyncLog);
//
//					SynThread synThread = new SynThread(dAdjustSyncLog,imp.getImpBatch());
//					synThread.setDaemon(true);// 后台线程
//					synThread.setName("SYNC-AUTH-THREAD");
//					synThread.start();
					
					
				} catch (Exception e) {
					logger.error("导入时发生成异常," + e.getMessage(), e);

					DPatentAuthInfoPreImp u1 = new DPatentAuthInfoPreImp();
					u1.setId(imp.getId());
					u1.setImpState(PreImpStatus.PARSE_ERR);
					String errReason = e.getMessage();
					if (errReason.length() > 3000) {
						errReason = errReason.substring(0, 3000);
					}
					u1.setErrReason(errReason);
					dPatentAuthInfoPreImpService.updateById(u1);

				}
			}
		};
		pdImpThread.setName("pdImpThread");
		pdImpThread.setDaemon(true);
		pdImpThread.start();
		return AjaxResult.success("系统已接收，请稍后留意导入状态");
	}

	
//	private class SynThread extends Thread {
//		private DAdjustSyncLog dAdjustSyncLog;
//		private String impBatch;
//
//		private SynThread(DAdjustSyncLog dAdjustSyncLog,String impBatch) {
//			this.dAdjustSyncLog = dAdjustSyncLog;
//			this.impBatch=impBatch;
//		}
//
//		public void run() {
//			doSync(dAdjustSyncLog,impBatch);
//		}
//
//		private void doSync(DAdjustSyncLog dAdjustSyncLog,String impBatch) {
//			
//			
//			String yearBatch=impBatch.trim().substring(0, 4);
//			String monthBatch=impBatch.trim().substring(4, 6);
//			
//			if(ruoYiConfig.getAutoSync()!=null && ruoYiConfig.getAutoSync().booleanValue()) {
//				dPatentDataCollationInfoService.doSync("auth");
//			}
//			
////			DPatentDataCollationLog dPatentDataCollationLog = new DPatentDataCollationLog();
////			dPatentDataCollationLog.setSyncStatus("0");// 查末同步的
////			List<DPatentDataCollationLog> list = dPatentDataCollationLogService.queryList(dPatentDataCollationLog);
////			if (list == null || list.isEmpty()) {
////				// 没有待同步的调整记录，直接置完成
////				dAdjustSyncLog.setStatus("2");// 同步成功
////				dAdjustSyncLog.setEndSyncTime(new Date());
////				dAdjustSyncLog.setUsedTime(
////						dAdjustSyncLog.getEndSyncTime().getTime() - dAdjustSyncLog.getBeginSyncTime().getTime());
////				dAdjustSyncLogService.updateById(dAdjustSyncLog);
////			} else {
////				try {
////					doSync(dAdjustSyncLog, list);
////					dAdjustSyncLog.setStatus("2");// 同步成功
////					dAdjustSyncLog.setEndSyncTime(new Date());
////					dAdjustSyncLog.setUsedTime(
////							dAdjustSyncLog.getEndSyncTime().getTime() - dAdjustSyncLog.getBeginSyncTime().getTime());
////					dAdjustSyncLogService.updateById(dAdjustSyncLog);
////				} catch (Exception e) {
////					dAdjustSyncLog.setStatus("3");// 同步失败
////					dAdjustSyncLogService.updateById(dAdjustSyncLog);
////					logger.error("同步失败" + e.getMessage(), e);
////				}
////			}
//		}
//
////		private void doSync(DAdjustSyncLog dAdjustSyncLog, List<DPatentDataCollationLog> list) {
////			for (DPatentDataCollationLog log : list) {
////				log.setSyncStatus("1");// 同步处理中
////				dPatentDataCollationLogService.updateById(log);
////			}
////			Set<String> types = new HashSet<String>();
////			for (DPatentDataCollationLog log : list) {
////				if ("1".equals(log.getSameFalg())) {
//////					types.add("pub");
//////					types.add("act");
////					types.add("auth");
////					break;
////				}
////				if (StringUtils.isNotBlank(log.getDataType())) {
////					types.add(log.getDataType());
////				}
////			}
////			
////			if(ruoYiConfig.getAutoSync()!=null && ruoYiConfig.getAutoSync().booleanValue()) {
////				for (String type : types) {
////					dPatentDataCollationInfoService.doSync(type);
////				}
////			}
////			
////
////			for (DPatentDataCollationLog log : list) {
////				log.setSyncStatus("2");// 同步成功
////				dPatentDataCollationLogService.updateById(log);
////			}
////
////		}
//
//		
//		
//
//	}
	
	/**
	 * 查询专利授权导入记录列表
	 *
	 * @param dPatentAuthInfoPreImp 专利授权导入记录
	 * @return 专利授权导入记录集合
	 * @date 2023-03-19
	 */
	@PreAuthorize("@ss.hasPermi('dimp:dPatentAuthInfoPreImp:list')")
	@GetMapping("/list")
	public TableDataInfo list(DPatentAuthInfoPreImp dPatentAuthInfoPreImp) {
		startPage();
		List<DPatentAuthInfoPreImp> list = dPatentAuthInfoPreImpService.queryList(dPatentAuthInfoPreImp);
		return getDataTable(list);
	}

	/**
	 * 导出专利授权导入记录列表
	 *
	 * @param dPatentAuthInfoPreImp 专利授权导入记录
	 * @date 2023-03-19
	 */
	@PreAuthorize("@ss.hasPermi('dimp:dPatentAuthInfoPreImp:export')")
	@Log(title = "专利授权导入记录", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	public void export(HttpServletResponse response, DPatentAuthInfoPreImp dPatentAuthInfoPreImp) {
		List<DPatentAuthInfoPreImp> list = dPatentAuthInfoPreImpService.list(new QueryWrapper<>());
		ExcelUtil<DPatentAuthInfoPreImp> util = new ExcelUtil<>(DPatentAuthInfoPreImp.class);
		util.exportExcel(response, list, "专利授权导入记录数据");
	}

	/**
	 * 获取专利授权导入记录详细信息
	 *
	 * @param id 主键id
	 * @return 结果
	 * @date 2023-03-19
	 */
	@PreAuthorize("@ss.hasPermi('dimp:dPatentAuthInfoPreImp:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		return AjaxResult.success(dPatentAuthInfoPreImpService.getById(id));
	}

	/**
	 * 新增专利授权导入记录信息
	 *
	 * @param dPatentAuthInfoPreImp 专利授权导入记录
	 * @return 结果
	 * @date 2023-03-19
	 */
	@PreAuthorize("@ss.hasPermi('dimp:dPatentAuthInfoPreImp:add')")
	@Log(title = "专利授权导入记录", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody DPatentAuthInfoPreImp dPatentAuthInfoPreImp) {
		return toAjax(dPatentAuthInfoPreImpService.save(dPatentAuthInfoPreImp));
	}

	/**
	 * 修改专利授权导入记录信息
	 *
	 * @param dPatentAuthInfoPreImp 专利授权导入记录
	 * @return 结果
	 * @date 2023-03-19
	 */
	@PreAuthorize("@ss.hasPermi('dimp:dPatentAuthInfoPreImp:edit')")
	@Log(title = "专利授权导入记录", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody DPatentAuthInfoPreImp dPatentAuthInfoPreImp) {
		return toAjax(dPatentAuthInfoPreImpService.updateById(dPatentAuthInfoPreImp));
	}

	/**
	 * 删除专利授权导入记录信息
	 *
	 * @param ids 主键ids
	 * @return 结果
	 * @date 2023-03-19
	 */
	@PreAuthorize("@ss.hasPermi('dimp:dPatentAuthInfoPreImp:remove')")
	@Log(title = "专利授权导入记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(dPatentAuthInfoPreImpService.removeByIds(Arrays.asList(ids)));
	}

}
