package com.yeejoin.equipmanage.quartz;

import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.equipmanage.common.enums.AnalysisReportEnum;
import com.yeejoin.equipmanage.common.utils.DateUtils;
import com.yeejoin.equipmanage.service.IAnalysisReportLogService;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author DELL
 */
@Component
@EnableScheduling
public class AnalysisReportSchedulerJob {

    @Autowired
    private IAnalysisReportLogService iAnalysisReportLogService;
    @Autowired(required = false)
    org.redisson.api.RedissonClient redisson;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${spring.redis.mode}")
    private String cluster;

    /**
     * 每天凌晨0点-日报生成
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void dayReport() throws ParseException {

        if(cluster.equals("cluster")){
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time=format.format(new Date());
            String jobName = "dayReport" + time;

            //为了便于区分key，增加后缀_redisson
            RLock lock = redisson.getLock(jobName);
            try {
                //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
                lock.tryLock(10, 20, TimeUnit.SECONDS);
                //为了防止重复
                if (!redisUtils.hasKey(jobName + "_dayReport_key")) {
                    redisUtils.set(jobName + "_dayReport_key", "1");//增加标识
                    Date beginDate = DateUtils.dateAdd(new Date(), -1, false);
                    Date endDate = DateUtils.dateAdd(new Date(), -1, false);
                    iAnalysisReportLogService.generateReport(AnalysisReportEnum.DAY_REPORT, beginDate, endDate);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw  new RuntimeException();
            } finally {
                lock.unlock(); //释放锁
            }
        }else{
            try {

                Date beginDate = DateUtils.dateAdd(new Date(), -1, false);
                Date endDate = DateUtils.dateAdd(new Date(), -1, false);
                iAnalysisReportLogService.generateReport(AnalysisReportEnum.DAY_REPORT, beginDate, endDate);

            } catch (Exception e) {
                e.printStackTrace();
                throw  new RuntimeException();
            }
        }





    }

    /**
     * 每周1(对应日期的2)凌晨0点-周报生成
     */
    @Scheduled(cron = "0 0 0 ? * 1")
    public void weekReport() throws ParseException {

        if(cluster.equals("cluster")) {


            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = format.format(new Date());
            String jobName = "weekReport" + time;


            //为了便于区分key，增加后缀_redisson
            RLock lock = redisson.getLock(jobName);
            try {
                //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
                lock.tryLock(10, 20, TimeUnit.SECONDS);
                //为了防止重复
                if (!redisUtils.hasKey(jobName + "_weekReport_key")) {
                    redisUtils.set(jobName + "_weekReport_key", "1");//增加标识
                    Date yestDay = DateUtils.dateAdd(new Date(), -1, false);
                    Date beginDate = DateUtils.getFirstDayOfWeek(yestDay);
                    Date endDate = DateUtils.getLastDayOfWeek(yestDay);
                    iAnalysisReportLogService.generateReport(AnalysisReportEnum.WEEK_REPORT, beginDate, endDate);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); //释放锁
            }
        }else{
            Date yestDay = DateUtils.dateAdd(new Date(), -1, false);
            Date beginDate = DateUtils.getFirstDayOfWeek(yestDay);
            Date endDate = DateUtils.getLastDayOfWeek(yestDay);
            iAnalysisReportLogService.generateReport(AnalysisReportEnum.WEEK_REPORT, beginDate, endDate);

        }
    }

    /**
     * 每月第1天凌晨0-月报生成
     */
    @Scheduled(cron="0 0 0 1 * ?")
    public void monthReport() throws ParseException {
        if(cluster.equals("cluster")) {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String time = format.format(new Date());
            String jobName = "monthReport" + time;

            //为了便于区分key，增加后缀_redisson
            RLock lock = redisson.getLock(jobName);
            try {
                //拿锁失败10停止尝试，20秒后直接释放锁 无论是返回 true 还是 false，都会继续执行之后的代码。
                lock.tryLock(10, 20, TimeUnit.SECONDS);
                //为了防止重复
                if (!redisUtils.hasKey(jobName + "_monthReport_key")) {
                    redisUtils.set(jobName + "_monthReport_key", "1");//增加标识
                    Date yestDay = DateUtils.dateAdd(new Date(), -1, false);
                    Date beginDate = DateUtils.getFirstDayOfMonth(yestDay);
                    Date endDate = DateUtils.getLastDayOfMonth(yestDay);
                    iAnalysisReportLogService.generateMonthReport(AnalysisReportEnum.MONTH_REPORT, beginDate, endDate);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); //释放锁
            }
        }else{
            Date yestDay = DateUtils.dateAdd(new Date(), -1, false);
            Date beginDate = DateUtils.getFirstDayOfMonth(yestDay);
            Date endDate = DateUtils.getLastDayOfMonth(yestDay);
            iAnalysisReportLogService.generateMonthReport(AnalysisReportEnum.MONTH_REPORT, beginDate, endDate);

        }
    }
}
