package com.ruoyi.docking.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.docking.entity.SmartReminders;
import com.ruoyi.docking.entity.request.JAddJobSmart;
import com.ruoyi.docking.entity.request.SREnterRequest;
import com.ruoyi.docking.entity.request.SmartRemindersPageRequest;
import com.ruoyi.docking.mapper.SmartRemindersMapper;
import com.ruoyi.docking.service.SmartRemindersService;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.quartz.SchedulerException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 智能提醒（j_smart_reminders）表业务实现层
 *
 * @author du
 * @since 2024/7/1 13:33
 */
@Service
public class SmartRemindersServiceImpl extends ServiceImpl<SmartRemindersMapper, SmartReminders> implements SmartRemindersService {

    @Resource
    private ISysJobService jobService;

    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 分页查询所有数据
     *
     * @param page           分页对象
     * @param smartReminders 查询实体
     * @return 所有数据
     */
    @Override
    public Page<SmartReminders> page(Page<SmartReminders> page, SmartRemindersPageRequest smartReminders) {
        return baseMapper.page(page, smartReminders);
    }

    /**
     * 生成cron表达式
     *
     * @return cron表达式
     */
    @Override
    public String generateCron(LocalDateTime localDateTime) {
        int second = 0; // 固定为0秒
        int minute = localDateTime.getMinute();
        int hour = localDateTime.getHour();
        int dayOfMonth = localDateTime.getDayOfMonth();
        int month = localDateTime.getMonthValue();
        String dayOfWeek = "?";
        // 构造 Cron 表达式
        return String.format("%d %d %d %d %d %s",
                second, minute, hour, dayOfMonth, month, dayOfWeek);
    }


    /**
     * 新增定期提醒数据（政务端和企业端）
     *
     * @param srEnterRequest 实体对象
     * @return 新增结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long add(SREnterRequest srEnterRequest) throws SchedulerException, TaskException {
        LocalDateTime nt = LocalDateTime.now().plusMinutes(5);
        if (srEnterRequest.getAlertTime().isBefore(nt)) {
            throw new ServiceException("提醒时间必须在当前时间5分钟后!");
        }
        //新增定期提醒到智能提醒
        SmartReminders sr = new SmartReminders();
        BeanUtil.copyProperties(srEnterRequest, sr);
        sr.setAlertManner(1);
        save(sr);
        updateAndAdd(sr,true);
        return sr.getId();
    }

    /**
     * 修改或者新增定时任务
     */
    @Override
    public void updateAndAdd(SmartReminders jSmartReminders, Boolean flag) throws SchedulerException, TaskException {
        SysJob sysJob = new SysJob();
        sysJob.setConcurrent("1");//不允许并发执行
        sysJob.setCronExpression(generateCron(jSmartReminders.getAlertTime()));//生成cron表达式
        if (jSmartReminders.getAlertRecipients() == 1) {
            //如果是企业的定时提醒（调用这个方法）
            sysJob.setInvokeTarget("timingRemind.enterpriseTiming("
                    + "'" + jSmartReminders.getAlertTime() + "'" + ","
                    + jSmartReminders.getId() + "L" + ")");
        } else {
            //如果是政务端的定时提醒
            sysJob.setInvokeTarget("timingRemind.chiefTiming(" + "'"
                    + jSmartReminders.getAlertTime() + "'" + ","
                    + jSmartReminders.getId() + "L," + "'"
                    + jSmartReminders.getProjectId() + "'"+","+ "'"
                    + jSmartReminders.getAlertContent() + "'" + ")");
        }
        sysJob.setJobGroup("DEFAULT");
        sysJob.setJobName(jSmartReminders.getRulesName());
        sysJob.setMisfirePolicy("3");
        sysJob.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        if (flag) {
            //新增定时任务
            jobService.insertJob(sysJob);
            JAddJobSmart ja = new JAddJobSmart();
            ja.setSmartId(jSmartReminders.getId());
            ja.setJobId(sysJob.getJobId());
            //新增定时任务和智能提醒关联数据
            baseMapper.addJobSmart(ja);
        } else {
            //修改
            JAddJobSmart jAddJobSmart = baseMapper.selectJobSmart(jSmartReminders.getId());
            sysJob.setJobId(jAddJobSmart.getJobId());
            jobService.updateJob(sysJob);
        }
    }

    /**
     * 根据智能提醒id查询定时任务
     */
    @Override
    public JAddJobSmart selectJobSmart(Long id) {
        return baseMapper.selectJobSmart(id);
    }

    /**
     * 已读智能提醒
     *
     * @param id 主键
     * @return 单条数据
     */
    @Override
    public Boolean isRead(Serializable id) {
        return baseMapper.isRead(id);
    }
}

