package com.ruoyi.adjust.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

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.adjust.domain.DAdjustSyncLog;
import com.ruoyi.adjust.domain.DPatentDataCollationLog;
import com.ruoyi.adjust.mapper.DAdjustSyncLogMapper;
import com.ruoyi.adjust.service.IDAdjustSyncLogService;
import com.ruoyi.adjust.service.IDPatentDataCollationInfoService;
import com.ruoyi.adjust.service.IDPatentDataCollationLogService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;

/**
 * 数据调整同步记录Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-19
 */
@Service
public class DAdjustSyncLogServiceImpl extends ServiceImpl<DAdjustSyncLogMapper, DAdjustSyncLog> implements IDAdjustSyncLogService {

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

	@Autowired
	private IDPatentDataCollationLogService dPatentDataCollationLogService;
	@Autowired
	private RuoYiConfig ruoYiConfig;
	@Autowired
	private IDAdjustSyncLogService dAdjustSyncLogService;
	@Autowired
	private IDPatentDataCollationInfoService dPatentDataCollationInfoService;

	public void syncAdjuestAfterRestart() {
		logger.debug("同步到应用系统-系统处理完成以后，开始同步专利调整数据");
		DAdjustSyncLog qo = new DAdjustSyncLog();
		qo.setStatus("1");// 同步中
		List<DAdjustSyncLog> list = queryList(qo);
		if (list != null && list.size() > 0) {
			SynThread thread = newSynThread(list);
			thread.start();
		}
	}

	public SynThread newSynThread(List<DAdjustSyncLog> dAdjustSyncLogs) {
		SynThread synThread = new SynThread(dAdjustSyncLogs);
		synThread.setDaemon(true);// 后台线程
		synThread.setName("SYNC-THREAD");
		return synThread;
	}
	public SynThread newSynThread(DAdjustSyncLog dAdjustSyncLog) {
		List<DAdjustSyncLog> dAdjustSyncLogs = new ArrayList<DAdjustSyncLog>();
		dAdjustSyncLogs.add(dAdjustSyncLog);
		SynThread synThread = new SynThread(dAdjustSyncLogs);
		synThread.setDaemon(true);// 后台线程
		synThread.setName("SYNC-THREAD");
		return synThread;
	}

	public class SynThread extends Thread {
		List<DAdjustSyncLog> dAdjustSyncLogs;

		public SynThread(List<DAdjustSyncLog> dAdjustSyncLogs) {
			this.dAdjustSyncLogs = dAdjustSyncLogs;
		}

		public void run() {
			doSync(dAdjustSyncLogs);
		}

		private void doSync(List<DAdjustSyncLog> dAdjustSyncLogs) {
			if (dAdjustSyncLogs != null && !dAdjustSyncLogs.isEmpty()) {
				for (DAdjustSyncLog dAdjustSyncLog : dAdjustSyncLogs) {
					doSync(dAdjustSyncLog);
				}
			}
		}

		private void doSync(DAdjustSyncLog dAdjustSyncLog) {
			logger.debug("同步到应用系统-后台同步线程启动:" + new Gson().toJson(dAdjustSyncLog));
			DPatentDataCollationLog dPatentDataCollationLog = new DPatentDataCollationLog();
			dPatentDataCollationLog.setSyncStatus("0");// 查末同步的
			List<DPatentDataCollationLog> list = dPatentDataCollationLogService.queryList(dPatentDataCollationLog);

			if (list == null || list.isEmpty()) {
				logger.debug("同步到应用系统-没有待同步的调整记录，直接置完成");
				// 没有待同步的调整记录，直接置完成
				dAdjustSyncLog.setStatus("2");// 同步成功
				dAdjustSyncLog.setEndSyncTime(new Date());
				dAdjustSyncLog.setUsedTime(dAdjustSyncLog.getEndSyncTime().getTime() - dAdjustSyncLog.getBeginSyncTime().getTime());
				dAdjustSyncLogService.updateById(dAdjustSyncLog);
			} else {
				logger.debug("同步到应用系统-查询到待同步的数据:" + new Gson().toJson(list));
				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) {

			logger.debug("同步到应用系统-开始同步，更新为同步处理中," + new Gson().toJson(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());
				}
			}
			logger.debug("同步到应用系统-统计出待同步数据类型:" + new Gson().toJson(types));
			if (ruoYiConfig.getAutoSync() != null && ruoYiConfig.getAutoSync().booleanValue()) {
				for (String type : types) {
					logger.debug("同步到应用系统-开始同步类型:" + type + "类型数据");
					dPatentDataCollationInfoService.doSync(type);
				}
			} else {
				logger.warn("同步到应用系统-末开启自动同步。。。");
			}

			logger.debug("同步到应用系统-同步完成，更新状态为同步成功," + new Gson().toJson(list));
			for (DPatentDataCollationLog log : list) {
				log.setSyncStatus("2");// 同步成功
				dPatentDataCollationLogService.updateById(log);
			}

		}
	}

	/**
	 * 查询数据调整同步记录列表
	 *
	 * @param dAdjustSyncLog 数据调整同步记录
	 * @return 数据调整同步记录集合
	 * @date 2023-04-19
	 */
	@Override
	public List<DAdjustSyncLog> queryList(DAdjustSyncLog dAdjustSyncLog) {
		QueryWrapper<DAdjustSyncLog> queryWrapper = Wrappers.query();
		if (StringUtils.isNotNull(dAdjustSyncLog.getBeginSyncTime())) {
			queryWrapper.eq("begin_sync_time", dAdjustSyncLog.getBeginSyncTime());
		}
		if (StringUtils.isNotNull(dAdjustSyncLog.getEndSyncTime())) {
			queryWrapper.eq("end_sync_time", dAdjustSyncLog.getEndSyncTime());
		}
		if (StringUtils.isNotNull(dAdjustSyncLog.getUsedTime())) {
			queryWrapper.eq("used_time", dAdjustSyncLog.getUsedTime());
		}
		if (StringUtils.isNotNull(dAdjustSyncLog.getStatus())) {
			queryWrapper.eq("status", dAdjustSyncLog.getStatus());
		}
		queryWrapper.orderByDesc("id");
		return this.list(queryWrapper);
	}

}
