package com.ygtx.worklog.task;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.ygtx.common.core.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ygtx.worklog.service.IDailyReportService;
import com.ygtx.worklog.service.ISystemConfigService;
import com.ygtx.system.service.ISysUserService;

/**
 * 日报提醒定时任务
 *
 * @author ruoyi
 */
@Component("dailyReportReminderTask")
public class DailyReportReminderTask
{
    @Autowired
    private IDailyReportService dailyReportService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISystemConfigService systemConfigService;

    /**
     * 检查未提交日报并发送提醒
     * 定时任务配置示例：0 0 18 * * ? （每天18:00执行）
     */
    public void checkUnsubmittedReports()
    {
        try
        {
            // 获取配置
            String reminderMethod = systemConfigService.selectConfigByKey("reminder.method");
            if (reminderMethod == null || reminderMethod.isEmpty()) {
                reminderMethod = "system";
            }

            // 获取当前日期
            Date today = new Date();

            // 查询未提交日报的用户
            List<Long> unsubmittedUserIds = dailyReportService.getUnsubmittedUsers(today);

            if (unsubmittedUserIds != null && !unsubmittedUserIds.isEmpty()) {
                for (Long userId : unsubmittedUserIds) {
                    sendReminder(userId, today, reminderMethod, "1"); // 截止提醒
                }

                // 通知上级
                notifySupervisors(unsubmittedUserIds, today);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 发送提醒
     */
    private void sendReminder(Long userId, Date reportDate, String reminderMethod, String reminderType)
    {
        SysUser user = userService.selectUserById(userId);
        if (user == null) {
            return;
        }

        String content = String.format("提醒：您还未提交 %tF 的工作日报，请及时提交！", reportDate);

        // 根据提醒方式发送
        String[] methods = reminderMethod.split(",");
        for (String method : methods) {
            method = method.trim();
            if ("system".equals(method)) {
                // 发送系统通知（可集成站内消息系统）
                sendSystemNotification(user, content);
            } else if ("email".equals(method)) {
                // 发送邮件（需要配置邮件服务）
                sendEmailNotification(user, content);
            } else if ("sms".equals(method)) {
                // 发送短信（需要配置短信服务）
                sendSmsNotification(user, content);
            }
        }

        // 记录提醒日志
        logReminder(userId, user.getUserName(), reportDate, reminderType, reminderMethod, "0");
    }

    /**
     * 通知上级
     */
    private void notifySupervisors(List<Long> unsubmittedUserIds, Date reportDate)
    {
        // TODO: 查询有权限查看这些用户日报的上级
        // 可以通过授权配置表查询
        // 然后发送汇总通知给上级
    }

    /**
     * 发送系统通知
     */
    private void sendSystemNotification(SysUser user, String content)
    {
        // TODO: 集成系统通知功能
        System.out.println("发送系统通知给 " + user.getUserName() + ": " + content);
    }

    /**
     * 发送邮件通知
     */
    private void sendEmailNotification(SysUser user, String content)
    {
        // TODO: 集成邮件服务
        System.out.println("发送邮件给 " + user.getEmail() + ": " + content);
    }

    /**
     * 发送短信通知
     */
    private void sendSmsNotification(SysUser user, String content)
    {
        // TODO: 集成短信服务
        System.out.println("发送短信给 " + user.getPhonenumber() + ": " + content);
    }

    /**
     * 记录提醒日志
     */
    private void logReminder(Long userId, String userName, Date remindDate,
                            String remindType, String remindMethod, String status)
    {
        // TODO: 保存到提醒日志表
        System.out.println(String.format("提醒日志：用户=%s, 日期=%tF, 类型=%s, 方式=%s",
            userName, remindDate, remindType, remindMethod));
    }

    /**
     * 检查逾期未提交的日报
     * 定时任务配置示例：0 0 9 * * ? （每天09:00执行）
     */
    public void checkOverdueReports()
    {
        try
        {
            // 检查昨天及之前未提交的日报
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_MONTH, -1);
            Date yesterday = cal.getTime();

            List<Long> unsubmittedUserIds = dailyReportService.getUnsubmittedUsers(yesterday);

            if (unsubmittedUserIds != null && !unsubmittedUserIds.isEmpty()) {
                String reminderMethod = systemConfigService.selectConfigByKey("reminder.method");

                for (Long userId : unsubmittedUserIds) {
                    sendReminder(userId, yesterday, reminderMethod, "2"); // 逾期提醒
                }

                // 通知上级
                notifySupervisors(unsubmittedUserIds, yesterday);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
