package org.springblade.modules.timer;


import lombok.AllArgsConstructor;
import org.springblade.bank.checklist.service.IChecklistService;
import org.springblade.bank.checklist.vo.ChecklistVO;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.modules.desk.service.INoticeService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
@RestController
@AllArgsConstructor
public class TimeTask extends BladeController {

	private final IDeptService deptService;
	private final IChecklistService checklistService;
	private final INoticeService noticeService;

	//3.添加定时任务
	@Scheduled(cron = "0 0 22 * * ?")
//	@Scheduled(cron = "0/10 * * * * ?")
	//或直接指定时间间隔，例如：5秒
	//@Scheduled(fixedRate=5000)
	private void configureTasks() {
		System.err.println("执行静态定时任务时间: " + DateUtil.format(DateUtil.now(), "yyyy-MM-dd HH:mm:ss"));

		//1、每天
		dayTask();

		//2、每周
		if (CommonUtil.isWeekLastDay(DateUtil.format(DateUtil.now(), CommonUtil.pattern))){
			weekTask();
		}
		//3、每月
		if (CommonUtil.isMonthLastDay(DateUtil.format(DateUtil.now(), CommonUtil.pattern))){
			monthTask();
		}

	}

	private void checklistTask(String cycle){
		Dept yybDept = deptService.getByOrgNo("51007");
		//1、每天
		List<Long> deptChildIds = deptService.getDeptChildIds(yybDept.getId());
		deptChildIds.forEach(deptId -> {
			Dept dept = deptService.getById(deptId);
			ChecklistVO checklist = new ChecklistVO();
			checklist.setCycle(cycle);
			checklist.setOrgNo(dept.getOrgNo());
			List<Map> dayReport = checklistService.getReport(checklist);
			boolean flag = false;
			for (int i = 0; i < dayReport.size(); i++) {
				Map map = dayReport.get(i);
				int nocheck = Integer.parseInt(map.get("nocheck").toString());
				flag = flag || nocheck >= 1;
			}
			if (flag){
				//給支行管理層發送行信通知
				noticeService.sendChecklistNotice(checklist.getCycle(), dept);
			}
		});

	}

	private void dayTask(){
		checklistTask("day");
	}

	private void weekTask(){
		checklistTask("week");
	}

	private void monthTask(){
		checklistTask("month");
	}
}
