package com.cyksj.service.sys.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.mapper.manage.home.HomeManagementConfigMapper;
import com.cyksj.mapper.sys.SysFuncTimingShelfMapper;
import com.cyksj.model.entity.SysFuncTimingShelf;
import com.cyksj.redis.RedisService;
import com.cyksj.service.sys.SysFuncTimingShelfService;
import com.cyksj.task.JobManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 项目名: yhlxj2
 * 文件名: SysFuncTimingShelfServiceImpl
 * 创建者: JavaZou
 * 创建时间:2023/12/28 11:03
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class SysFuncTimingShelfServiceImpl extends ServiceImpl<SysFuncTimingShelfMapper, SysFuncTimingShelf> implements SysFuncTimingShelfService {
	private final JobManager jobManager;

	private final HomeManagementConfigMapper homeManagementConfigMapper;

	private final RedisService redisService;


	@PostConstruct
	public void initShelfTimingJob() {
		List<SysFuncTimingShelf> list = this.list(Wrappers.lambdaQuery(SysFuncTimingShelf.class).eq(SysFuncTimingShelf::getDeleted, 1));

		long nowMills = System.currentTimeMillis();
		log.info("初始化添加定时上下架任务数量:{}", list.size());
		list.forEach(sysFuncTimingShelf -> {
			addTimingJob(sysFuncTimingShelf.getType(), sysFuncTimingShelf.getFuncId(), sysFuncTimingShelf.getPreStatus(), sysFuncTimingShelf.getTime(), nowMills);
		});
	}

	@Override
	public void addTimingJob(String type, Long funcId, Boolean preStatus, Long time, Long nowMills) {
		Runnable task = null;
		if (SysFuncTimingShelf.Type.valueOf(type) == SysFuncTimingShelf.Type.hc) {
			log.info("添加首页配置id：{},time{},状态为:{}定时任务-------------->", funcId, DateTime.of(time), preStatus);
			task = () -> addHomeConfigTimingJob(funcId);
		}
		if (task != null) {
			Long startTime = time - nowMills;
			if (startTime < 0) {
				//随机一个2s
				startTime = RandomUtil.randomLong(2000);
			}
			jobManager.addJob(startTime, task);
		}
	}


	@Transactional(rollbackFor = Throwable.class)
	public void addHomeConfigTimingJob(Long funcId) {
		Optional.ofNullable(this.getOne(Wrappers.lambdaQuery(SysFuncTimingShelf.class)
				.eq(SysFuncTimingShelf::getType, SysFuncTimingShelf.Type.hc)
				.eq(SysFuncTimingShelf::getFuncId, funcId)
				.le(SysFuncTimingShelf::getTime, System.currentTimeMillis())
				.eq(SysFuncTimingShelf::getDeleted, 1)
				.last("limit 1"))).ifPresent(timingShelf -> {
			timingShelf.setDeleted(false);
			this.updateById(timingShelf);
			Optional.ofNullable(homeManagementConfigMapper.selectById(funcId)).ifPresent(homeManagementConfig -> {
				if (!timingShelf.getPreStatus()) {
					homeManagementConfig.setTime(null);
					homeManagementConfig.setEndTime(null);
				}
				homeManagementConfig.setPreStatus(null);
				homeManagementConfig.setStatus(timingShelf.getPreStatus());
				homeManagementConfigMapper.updateById(homeManagementConfig);
				log.info("将首页配置:{}的状态置为:{}状态", funcId, timingShelf.getPreStatus());

				Set<String> keys = redisService.keys(RedisService.key.YH_HOME_PAGHE_CACHE.getName() + "*");
				redisService.del(keys.toArray(String[]::new));
			});
		});
	}
}
