/**
 * Copyright
 * All right reserved.
 * 项目名称:
 * 创建日期:2022/5/23
 */
package org.springblade.modules.business.data.manage.deptCache;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.glassfish.jersey.internal.guava.ThreadFactoryBuilder;
import org.springblade.constant.BusinessConstant;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.region.entity.OrgRegionInfoEntity;
import org.springblade.modules.baseinfo.region.entity.RegionTreeNodeEntity;
import org.springblade.modules.baseinfo.region.service.IOrgRegionInfoService;
import org.springblade.modules.baseinfo.region.entity.RegionInfoEntity;
import org.springblade.modules.baseinfo.region.service.IBaseInfoRegionService;
import org.springblade.modules.business.rtu.base.service.IRtuBaseInfoService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;

/***
 * Date:2022/5/22
 * Title: 环境辐射与气象监测系统(KRS) 模块
 * Description：MODBUS TCP 协议传输 ,任务管理
 * @author swp
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
@Component
@EnableScheduling
public class DeptCacheTaskManager {

	/**
	 * 公共线程池
	 **/
	private static ThreadFactory publicThreadFactory = new ThreadFactoryBuilder().setNameFormat("public-thread-pool-%d").build();
	private static ExecutorService publicThreadPool = new ThreadPoolExecutor(1, 1,
		0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), publicThreadFactory, new ThreadPoolExecutor.AbortPolicy());

	@Resource
	private IRtuBaseInfoService iRtuBaseInfoService;

	@Resource
	private RedisTemplate redisTemplate;

	@Resource
	private IDeptService iDeptService;

	@Resource
	private IOrgRegionInfoService iOrgRegionInfoService;

	@Resource
	private IBaseInfoRegionService iBaseInfoRegionService;


	@Scheduled(cron = "0 0 0 * * * ")
	public void deptUpdateTask() {
		try {
			DeptUpdateTask task = new DeptUpdateTask();
			FutureTask<Integer> futureTask = new FutureTask<>(task);
			publicThreadPool.execute(futureTask);
		} catch (Exception e) {
			log.error("{}", e.getMessage());
		}
	}

	private class DeptUpdateTask implements Callable<Integer> {

		@Override
		public Integer call() {
			try {
				log.info("组织机构下的行政区划数据处理");
				ValueOperations<String, String> opsHash = redisTemplate.opsForValue();
				//把机构区划表所有记录更新到删除状态
				LambdaUpdateWrapper<OrgRegionInfoEntity> wrapper = Wrappers.<OrgRegionInfoEntity>update().lambda();
				wrapper.set(OrgRegionInfoEntity::getRegionActive, 0);
				iOrgRegionInfoService.update(wrapper);
				//取所有组织机构信息
				List<Dept> depts = iDeptService.getDeptChild(BusinessConstant.ORG_ADMIN_ID);
				if (null != depts && depts.size() > 0) {
					//取最新的行政区划信息
					List<RegionInfoEntity> regions = iBaseInfoRegionService.list();
					for (Dept dept : depts) {
						for (RegionInfoEntity regionInfoEntity : regions) {
							//计算地区下的测站数量
							Long rtuCount = iRtuBaseInfoService.rtuCount(dept.getId(), regionInfoEntity.getAdcd());
							//更新
							OrgRegionInfoEntity orgRegionInfoEntity = iOrgRegionInfoService.getOrgRegionInfo(dept.getId(), regionInfoEntity.getAdcd());
							if (null == orgRegionInfoEntity) {
								orgRegionInfoEntity = new OrgRegionInfoEntity();
								orgRegionInfoEntity.setDeptId(dept.getId());
								orgRegionInfoEntity.setAdcd(regionInfoEntity.getAdcd());
							}
							orgRegionInfoEntity.setAdnm(regionInfoEntity.getAdnm());
							orgRegionInfoEntity.setAncestors(regionInfoEntity.getAncestors());
							orgRegionInfoEntity.setAddType(regionInfoEntity.getAddType());
							orgRegionInfoEntity.setParentCode(regionInfoEntity.getParentCode());
							orgRegionInfoEntity.setRegionActive(1);
							orgRegionInfoEntity.setRtuCount(rtuCount);
							iOrgRegionInfoService.saveOrUpdate(orgRegionInfoEntity);
						}
						//更新机构行政区划到缓存
						List<RegionTreeNodeEntity> nodeEntities = new LinkedList<>();
						LambdaQueryWrapper<OrgRegionInfoEntity> queryWrapper = Wrappers.<OrgRegionInfoEntity>query().lambda();
						queryWrapper.eq(OrgRegionInfoEntity::getParentCode, "00");
						queryWrapper.eq(OrgRegionInfoEntity::getDeptId, dept.getId());
						queryWrapper.eq(OrgRegionInfoEntity::getRegionActive, 1);
						List<OrgRegionInfoEntity> list = iOrgRegionInfoService.list(queryWrapper);
						for (OrgRegionInfoEntity entity : list) {
							RegionTreeNodeEntity nodeEntity = new RegionTreeNodeEntity();
							nodeEntity.setId(entity.getAdcd());
							nodeEntity.setValue(entity.getAdcd());
							nodeEntity.setTitle(entity.getAdnm());
							nodeEntity.setText(entity.getAdnm());
							nodeEntity.setKey(entity.getAdcd());
							nodeEntity.setParentId(entity.getParentCode());
							getChildren(nodeEntity, entity);
							if (nodeEntity.getChildren() != null && nodeEntity.getChildren().size() > 0) {
								nodeEntity.setHasChildren(true);
							} else {
								nodeEntity.setHasChildren(false);
							}
							nodeEntities.add(nodeEntity);
						}
						String regionString = JSON.toJSONString(nodeEntities);
						opsHash.set("region."+Func.toStr(dept.getId()), regionString);
						log.info("机构 "+dept.getDeptName()+" 行政区划已更新到缓存");
					}
				}
				//更新管理员行政区划到缓存
				List<RegionTreeNodeEntity> adminNodeEntities = new LinkedList<>();
				LambdaQueryWrapper<RegionInfoEntity> queryWrapper = Wrappers.<RegionInfoEntity>query().lambda();
				queryWrapper.eq(RegionInfoEntity::getParentCode, "00");
				List<RegionInfoEntity> list = iBaseInfoRegionService.list(queryWrapper);
				for (RegionInfoEntity entity : list) {
					RegionTreeNodeEntity nodeEntity = new RegionTreeNodeEntity();
					nodeEntity.setId(entity.getAdcd());
					nodeEntity.setValue(entity.getAdcd());
					nodeEntity.setTitle(entity.getAdnm());
					nodeEntity.setText(entity.getAdnm());
					nodeEntity.setKey(entity.getAdcd());
					nodeEntity.setParentId(entity.getParentCode());
					getChildren(nodeEntity, entity);
					if (nodeEntity.getChildren() != null && nodeEntity.getChildren().size() > 0) {
						nodeEntity.setHasChildren(true);
					} else {
						nodeEntity.setHasChildren(false);
					}
					adminNodeEntities.add(nodeEntity);
				}
				String regionString = JSON.toJSONString(adminNodeEntities);
				opsHash.set("region.admin", regionString);
				log.info("管理员行政区划已更新到缓存");
			} catch (Exception e) {
				log.error("数据任务异常 {}", e.getMessage());
			}
			return 0;
		}

		private boolean getChildren(RegionTreeNodeEntity nodeEntity, OrgRegionInfoEntity regionInfoEntity) {
			LambdaQueryWrapper<OrgRegionInfoEntity> queryWrapper = Wrappers.<OrgRegionInfoEntity>query().lambda();
			queryWrapper.eq(OrgRegionInfoEntity::getParentCode, regionInfoEntity.getAdcd());
			queryWrapper.eq(OrgRegionInfoEntity::getDeptId, regionInfoEntity.getDeptId());
			queryWrapper.eq(OrgRegionInfoEntity::getRegionActive, 1);
			List<OrgRegionInfoEntity> list = iOrgRegionInfoService.list(queryWrapper);
			if (null != list && list.size() > 0) {
				List<RegionTreeNodeEntity> nodeEntities = new LinkedList<>();
				for (OrgRegionInfoEntity entity : list) {
					if (entity.getRtuCount() > 0) {
						RegionTreeNodeEntity node = new RegionTreeNodeEntity();
						node.setId(entity.getAdcd());
						node.setValue(entity.getAdcd());
						node.setTitle(entity.getAdnm());
						node.setText(entity.getAdnm());
						node.setKey(entity.getAdcd());
						node.setParentId(entity.getParentCode());
						getChildren(node, entity);
						if (node.getChildren() != null && node.getChildren().size() > 0) {
							node.setHasChildren(true);
						} else {
							node.setHasChildren(false);
						}
						nodeEntities.add(node);
					}
				}
				nodeEntity.setChildren(nodeEntities);
			}
			return true;
		}

		private boolean getChildren(RegionTreeNodeEntity nodeEntity, RegionInfoEntity regionInfoEntity) {
			LambdaQueryWrapper<RegionInfoEntity> queryWrapper = Wrappers.<RegionInfoEntity>query().lambda();
			queryWrapper.eq(RegionInfoEntity::getParentCode, regionInfoEntity.getAdcd());
			List<RegionInfoEntity> list = iBaseInfoRegionService.list(queryWrapper);
			if (null != list && list.size() > 0) {
				List<RegionTreeNodeEntity> nodeEntities = new LinkedList<>();
				for (RegionInfoEntity entity : list) {
					RegionTreeNodeEntity node = new RegionTreeNodeEntity();
					node.setId(entity.getAdcd());
					node.setValue(entity.getAdcd());
					node.setTitle(entity.getAdnm());
					node.setText(entity.getAdnm());
					node.setKey(entity.getAdcd());
					node.setParentId(entity.getParentCode());
					getChildren(node, entity);
					if (node.getChildren() != null && node.getChildren().size() > 0) {
						node.setHasChildren(true);
					} else {
						node.setHasChildren(false);
					}
					nodeEntities.add(node);
				}
				nodeEntity.setChildren(nodeEntities);
			}
			return true;
		}
	}
}
