package org.jeecg.modules.demo.linkouterchaindetection.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.externalinternalsite.entity.ExternalInternalSite;
import org.jeecg.modules.demo.externalinternalsite.service.IExternalInternalSiteService;
import org.jeecg.modules.demo.linkouterchaindetection.entity.LinkOuterChainDetection;
import org.jeecg.modules.demo.linkouterchaindetection.service.ILinkOuterChainDetectionService;
import org.jeecg.modules.demo.linkouterchainlog.entity.LinkOuterChainLog;
import org.jeecg.modules.demo.linkouterchainlog.service.ILinkOuterChainLogService;
import org.jeecg.modules.demo.linkouterouterstatistics.entity.LinkOuterouterStatistics;
import org.jeecg.modules.demo.linkouterouterstatistics.service.ILinkOuterouterStatisticsService;
import org.jeecg.modules.demo.mainsite.entity.MainSite;
import org.jeecg.modules.demo.mainsite.service.IMainSiteService;
import org.jeecg.modules.system.service.ISysUserService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.*;

/**
 * 示例带参定时任务
 * 
 * @Author Scott
 */
@Slf4j
@Component
public class LinkOuterChainDetectionCheckParamJob implements Job {

	/**
	 * 若参数变量名修改 QuartzJobController中也需对应修改
	 */
	private String parameter;

	@Autowired
	private ILinkOuterChainDetectionService linkOuterChainDetectionService;
	@Autowired
	private IMainSiteService iMainSiteService;

	@Autowired
	private IExternalInternalSiteService externalInternalSiteService;

	@Autowired
	private ILinkOuterChainLogService linkOuterChainLogService;

	@Autowired
	private ILinkOuterouterStatisticsService iLinkOuterouterStatisticsService;

	@Autowired
	private ISysUserService userService;

	private Integer ThreadpageNum = 0;

	public void setParameter(String parameter) {
		this.parameter = parameter;
	}

	@Override
	public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		try {
			String TenantId = this.parameter.split("&&&")[1];
			this.parameter =  this.parameter.split("&&&")[0];
			log.info(" Job Execution key："+jobExecutionContext.getJobDetail().getKey());
			log.info( String.format("welcome %s! Jeecg-Boot 带参数定时任务 SampleParamJob !   时间:" + DateUtils.now(), this.parameter));
			QueryWrapper<MainSite> mainSiteQueryWrapper = new QueryWrapper<MainSite>();
			Page<MainSite> page = new Page<MainSite>(1, 1);
			System.out.println(this.parameter);
			System.out.println(iMainSiteService.list());
			mainSiteQueryWrapper.eq("main_site_url",this.parameter);
			TenantContext.setTenant(TenantId);
			Page<MainSite> page1 = iMainSiteService.page(page, mainSiteQueryWrapper);
			log.info(page1.getRecords()+"");
			MainSite mainSite = null;
			if(page1.getRecords().size() >= 1){
				mainSite = page1.getRecords().get(0);
			}
			log.info(mainSite+"");
			Map<String,ExternalInternalSite> stringExternalInternalSiteMap = new HashMap<String,ExternalInternalSite>();
			if(!ObjectUtils.isEmpty(mainSite)){
				Integer threadNumber = mainSite.getThreadNumber();
				//将对应的扫描列表的起始页分为上述的
				if(threadNumber > 1){
					multithreading(threadNumber,mainSite,TenantId);
				}
				if(threadNumber == 1 || threadNumber == 0){
					onethreading(mainSite,TenantId);
				}
			}
			try {
				TenantContext.setTenant(TenantId);
				LinkOuterouterStatistics linkOuterouterStatistics = iLinkOuterouterStatisticsService.listCountByMainUrl(this.parameter);
				if(!org.springframework.util.ObjectUtils.isEmpty(linkOuterouterStatistics)){
					linkOuterouterStatistics.setId(IdWorker.getIdStr());
					linkOuterouterStatistics.setScanTime(linkOuterouterStatistics.getUpdateTime());
					linkOuterouterStatistics.setTestType("2");
					TenantContext.setTenant(TenantId);
					linkOuterouterStatistics.setTenantId(Integer.parseInt(TenantId));
					iLinkOuterouterStatisticsService.save(linkOuterouterStatistics);
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	public void onethreading(MainSite mainSiteMM,String TenantId ){
		String mainUrl = mainSiteMM.getMainSiteUrl();
		if(org.springframework.util.ObjectUtils.isEmpty(mainUrl) || mainUrl == "" || mainUrl == null){
			mainUrl = "http://www.hetaodaxue.com/hyywxx/";
		}
		TenantContext.setTenant(TenantId);
		Integer count =  externalInternalSiteService.countSourceLinkOuter(mainUrl);
		Integer pageSize = 100;
		Integer pageNum = (int)Math.ceil((double)count/pageSize);
		for(int i = 1; i <= pageNum;i+=1){
			Page<ExternalInternalSite> page = new Page<ExternalInternalSite>(i, pageSize);
			TenantContext.setTenant(TenantId);
			IPage<ExternalInternalSite> pageList = externalInternalSiteService.pageSourceMainUrlLinkOuter(page,mainUrl);
			for (ExternalInternalSite externalInternalSite : pageList.getRecords()){
				LinkOuterChainDetection outerChainDetection = new LinkOuterChainDetection();
				outerChainDetection.setId(DigestUtils.md5DigestAsHex((externalInternalSite.getUrl()).getBytes()));
				outerChainDetection.setCreateBy(externalInternalSite.getMainUrl());
				outerChainDetection.setCreateTime(new Date());
				outerChainDetection.setUpdateBy(externalInternalSite.getMainUrl());
				outerChainDetection.setUpdateTime(new Date());
				QueryWrapper<MainSite> mainSiteQueryWrapper = new QueryWrapper<MainSite>();
				String mainUrl1 = externalInternalSite.getMainUrl();
				mainSiteQueryWrapper.eq("main_site_url",mainUrl1);
				TenantContext.setTenant(TenantId);
				List<MainSite> mainSiteList = iMainSiteService.list(mainSiteQueryWrapper);
				if(mainSiteList.size() >= 1){
					MainSite mainSite = mainSiteList.get(0);
					outerChainDetection.setMainSiteId(mainSite.getId());
					outerChainDetection.setMainSiteName(mainSite.getMainSiteName());
					outerChainDetection.setMainSiteUrl(mainSite.getMainSiteUrl());
				}
				outerChainDetection.setOuterUrl(externalInternalSite.getUrl());
				outerChainDetection.setOuterUrlType(externalInternalSite.getTypeUrl());
				outerChainDetection.setOuterUrlState(externalInternalSite.getStateUrl());
				//设置引用页数
				QueryWrapper<ExternalInternalSite> siteQueryWrapper = new QueryWrapper<ExternalInternalSite>();
				siteQueryWrapper.eq("url",externalInternalSite.getUrl());
				TenantContext.setTenant(TenantId);
				long countSiteQuery = externalInternalSiteService.count(siteQueryWrapper);
				outerChainDetection.setCheckNumberApplicationPagesv(Integer.parseInt(String.valueOf(countSiteQuery)));
				QueryWrapper<LinkOuterChainDetection> linkOuterChainDetectionQueryWrapper = new QueryWrapper<LinkOuterChainDetection>();
				linkOuterChainDetectionQueryWrapper.eq("id",externalInternalSite.getId());
				Page<LinkOuterChainDetection> pageListS = new Page<LinkOuterChainDetection>(1, 1);
				TenantContext.setTenant(TenantId);
				Page<LinkOuterChainDetection> page1 = linkOuterChainDetectionService.page(pageListS,linkOuterChainDetectionQueryWrapper);
				List<LinkOuterChainDetection> outerChainDetectionList = page1.getRecords();
				LinkOuterChainDetection chainDetection = null;
				if(outerChainDetectionList.size() >=1){
					chainDetection = outerChainDetectionList.get(0);
				}
				if(!org.springframework.util.ObjectUtils.isEmpty(chainDetection)){
					outerChainDetection.setUpdateTime(chainDetection.getUpdateTime());
					Integer numberScans = chainDetection.getNumberScans();
					numberScans = numberScans + 1;
					outerChainDetection.setNumberScans(numberScans);
					outerChainDetection.setNumberApplicationPages(chainDetection.getNumberApplicationPages());
					outerChainDetection.setIsRevise(chainDetection.getIsRevise());
					outerChainDetection.setIsIgnore(chainDetection.getIsIgnore());
				}else{
					outerChainDetection.setNumberApplicationPages(Integer.parseInt(String.valueOf(countSiteQuery)));
					outerChainDetection.setNumberScans(1);
				}
				outerChainDetection.setCheckState("1");
				outerChainDetection.setCheckTime(new Date());
				outerChainDetection.setTenantId(externalInternalSite.getTenantId());
				TenantContext.setTenant(TenantId);
				linkOuterChainDetectionService.saveOrUpdate(outerChainDetection);
				//记录日志信息
				LinkOuterChainLog linkOuterChainLog = new LinkOuterChainLog();
				linkOuterChainLog.setId(IdWorker.getIdStr());
				linkOuterChainLog.setOuterChainDetectionId(outerChainDetection.getId());
				linkOuterChainLog.setCreateBy(outerChainDetection.getCreateBy());
				linkOuterChainLog.setCreateTime(outerChainDetection.getCreateTime());
				linkOuterChainLog.setUpdateBy(outerChainDetection.getUpdateBy());
				linkOuterChainLog.setUpdateTime(outerChainDetection.getUpdateTime());
				linkOuterChainLog.setMainSiteId(outerChainDetection.getMainSiteId());
				linkOuterChainLog.setMainSiteName(outerChainDetection.getMainSiteName());
				linkOuterChainLog.setMainSiteUrl(outerChainDetection.getMainSiteUrl());
				linkOuterChainLog.setOuterUrl(outerChainDetection.getOuterUrl());
				linkOuterChainLog.setOuterUrlType(outerChainDetection.getOuterUrlType());
				linkOuterChainLog.setOuterUrlState(outerChainDetection.getOuterUrlState());
				linkOuterChainLog.setNumberApplicationPages(outerChainDetection.getNumberApplicationPages());
				linkOuterChainLog.setNumberScans(outerChainDetection.getNumberScans());
				linkOuterChainLog.setIsRevise(outerChainDetection.getIsRevise());
				linkOuterChainLog.setIsIgnore(outerChainDetection.getIsIgnore());
				linkOuterChainLog.setCheckTime(outerChainDetection.getCheckTime());
				linkOuterChainLog.setCheckState(outerChainDetection.getCheckState());
				linkOuterChainLog.setCheckNumberApplicationPagesv(outerChainDetection.getCheckNumberApplicationPagesv());
				linkOuterChainLog.setCheckMessage(outerChainDetection.getCheckMessage());
				linkOuterChainLog.setTenantId(externalInternalSite.getTenantId());
				TenantContext.setTenant(TenantId);
				linkOuterChainLogService.save(linkOuterChainLog);

			}
		}
	}
	public void multithreading(Integer threadNumber,MainSite mainSite,String TenantId){
		TenantContext.setTenant(TenantId);
		long countExternalInternalSite = externalInternalSiteService.countSourceLinkOuter(mainSite.getMainSiteUrl());
		this.ThreadpageNum = (int)Math.ceil((double)countExternalInternalSite/threadNumber);
		log.info(countExternalInternalSite+"");
		log.info("ThreadpageNum========"+ThreadpageNum+"");
		List<Map<Integer,Integer>> integerList = new ArrayList<Map<Integer,Integer>>();
		for (Integer i = 0; i < threadNumber; i++) {
			Map<Integer,Integer> hashMap = new HashMap<Integer,Integer>();
			Integer index =  ThreadpageNum * i;
			if(index == 0){
				index = 1;
			}
			hashMap.put(index,ThreadpageNum * (i+1));
			integerList.add(hashMap);
		}
		for (Map<Integer, Integer> integerIntegerMap : integerList) {
			Iterator<Map.Entry<Integer, Integer>> iterator = integerIntegerMap.entrySet().iterator();
			Integer threadIndex = 1;
			while(iterator.hasNext()){
				Map.Entry<Integer,Integer> entry = iterator.next();
				Integer keyStart = entry.getKey();
				Integer valueEnd = entry.getValue();
				Integer finalThreadIndex = threadIndex;
				new Thread(){
					@Override
					public void run() {
						Integer count =  valueEnd - keyStart;
						Integer pageSize = 100;
						Integer pageNum = (int)Math.ceil((double)count/pageSize);
						for (Integer i = keyStart; i <= valueEnd; i+=pageSize) {
							System.out.println("========================");
							System.out.println(keyStart);
							System.out.println(valueEnd);
							System.out.println("========================");
							TenantContext.setTenant(TenantId);
							List<ExternalInternalSite> externalInternalSiteList =  externalInternalSiteService.listPageLinkOuter(i,pageSize);
							for (ExternalInternalSite externalInternalSite : externalInternalSiteList) {
								System.out.println(externalInternalSite);
								LinkOuterChainDetection outerChainDetection = new LinkOuterChainDetection();
								outerChainDetection.setId(DigestUtils.md5DigestAsHex((externalInternalSite.getUrl()).getBytes()));
								outerChainDetection.setCreateBy(externalInternalSite.getMainUrl());
								outerChainDetection.setCreateTime(new Date());
								outerChainDetection.setUpdateBy(externalInternalSite.getMainUrl());
								outerChainDetection.setUpdateTime(new Date());
								QueryWrapper<MainSite> mainSiteQueryWrapper = new QueryWrapper<MainSite>();
								String mainUrl1 = externalInternalSite.getMainUrl();
								mainSiteQueryWrapper.eq("main_site_url",mainUrl1);
								TenantContext.setTenant(TenantId);
								List<MainSite> mainSiteList = iMainSiteService.list(mainSiteQueryWrapper);
								if(mainSiteList.size() >= 1){
									MainSite mainSite = mainSiteList.get(0);
									outerChainDetection.setMainSiteId(mainSite.getId());
									outerChainDetection.setMainSiteName(mainSite.getMainSiteName());
									outerChainDetection.setMainSiteUrl(mainSite.getMainSiteUrl());
								}
								outerChainDetection.setOuterUrl(externalInternalSite.getUrl());
								outerChainDetection.setOuterUrlType(externalInternalSite.getTypeUrl());
								outerChainDetection.setOuterUrlState(externalInternalSite.getStateUrl());
								//设置引用页数
								QueryWrapper<ExternalInternalSite> siteQueryWrapper = new QueryWrapper<ExternalInternalSite>();
								siteQueryWrapper.eq("url",externalInternalSite.getUrl());
								TenantContext.setTenant(TenantId);
								long countSiteQuery = externalInternalSiteService.count(siteQueryWrapper);
								outerChainDetection.setCheckNumberApplicationPagesv(Integer.parseInt(String.valueOf(countSiteQuery)));
								QueryWrapper<LinkOuterChainDetection> linkOuterChainDetectionQueryWrapper = new QueryWrapper<LinkOuterChainDetection>();
								linkOuterChainDetectionQueryWrapper.eq("id",externalInternalSite.getId());
								Page<LinkOuterChainDetection> pageListS = new Page<LinkOuterChainDetection>(1, 1);
								TenantContext.setTenant(TenantId);
								Page<LinkOuterChainDetection> page1 = linkOuterChainDetectionService.page(pageListS,linkOuterChainDetectionQueryWrapper);
								List<LinkOuterChainDetection> outerChainDetectionList = page1.getRecords();
								LinkOuterChainDetection chainDetection = null;
								if(outerChainDetectionList.size() >=1){
									chainDetection = outerChainDetectionList.get(0);
								}
								if(!org.springframework.util.ObjectUtils.isEmpty(chainDetection)){
									outerChainDetection.setUpdateTime(chainDetection.getUpdateTime());
									Integer numberScans = chainDetection.getNumberScans();
									numberScans = numberScans + 1;
									outerChainDetection.setNumberScans(numberScans);
									outerChainDetection.setNumberApplicationPages(chainDetection.getNumberApplicationPages());
									outerChainDetection.setIsRevise("2");
									outerChainDetection.setIsIgnore(chainDetection.getIsIgnore());
								}else{
									outerChainDetection.setNumberApplicationPages(Integer.parseInt(String.valueOf(countSiteQuery)));
									outerChainDetection.setNumberScans(1);
									outerChainDetection.setIsRevise("1");
								}
								outerChainDetection.setCheckState("1");
								outerChainDetection.setCheckTime(new Date());
								outerChainDetection.setTenantId(externalInternalSite.getTenantId());
								TenantContext.setTenant(TenantId);
								linkOuterChainDetectionService.saveOrUpdate(outerChainDetection);
								//记录日志信息
								LinkOuterChainLog linkOuterChainLog = new LinkOuterChainLog();
								linkOuterChainLog.setId(IdWorker.getIdStr());
								linkOuterChainLog.setOuterChainDetectionId(outerChainDetection.getId());
								linkOuterChainLog.setCreateBy(outerChainDetection.getCreateBy());
								linkOuterChainLog.setCreateTime(outerChainDetection.getCreateTime());
								linkOuterChainLog.setUpdateBy(outerChainDetection.getUpdateBy());
								linkOuterChainLog.setUpdateTime(outerChainDetection.getUpdateTime());
								linkOuterChainLog.setMainSiteId(outerChainDetection.getMainSiteId());
								linkOuterChainLog.setMainSiteName(outerChainDetection.getMainSiteName());
								linkOuterChainLog.setMainSiteUrl(outerChainDetection.getMainSiteUrl());
								linkOuterChainLog.setOuterUrl(outerChainDetection.getOuterUrl());
								linkOuterChainLog.setOuterUrlType(outerChainDetection.getOuterUrlType());
								linkOuterChainLog.setOuterUrlState(outerChainDetection.getOuterUrlState());
								linkOuterChainLog.setNumberApplicationPages(outerChainDetection.getNumberApplicationPages());
								linkOuterChainLog.setNumberScans(outerChainDetection.getNumberScans());
								linkOuterChainLog.setIsRevise(outerChainDetection.getIsRevise());
								linkOuterChainLog.setIsIgnore(outerChainDetection.getIsIgnore());
								linkOuterChainLog.setCheckTime(outerChainDetection.getCheckTime());
								linkOuterChainLog.setCheckState(outerChainDetection.getCheckState());
								linkOuterChainLog.setCheckNumberApplicationPagesv(outerChainDetection.getCheckNumberApplicationPagesv());
								linkOuterChainLog.setCheckMessage(outerChainDetection.getCheckMessage());
								linkOuterChainLog.setTenantId(externalInternalSite.getTenantId());
								TenantContext.setTenant(TenantId);
								linkOuterChainLogService.save(linkOuterChainLog);
							}
						}
					}
				}.start();
				threadIndex++;
			}
		}
	}
}
