package com.ygtx.worklog.service.impl;

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

import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.worklog.domain.CollaborateTask;
import com.ygtx.worklog.domain.DailyReport;
import com.ygtx.worklog.domain.WeeklyReport;
import com.ygtx.worklog.mapper.CollaborateTaskMapper;
import com.ygtx.worklog.mapper.DailyReportMapper;
import com.ygtx.worklog.mapper.ReportAttachmentMapper;
import com.ygtx.worklog.service.IDailyReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.worklog.service.IWeeklyReportService;
import com.ygtx.worklog.service.ISystemConfigService;
import com.ygtx.system.service.ISysUserService;

/**
 * 日报Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-21
 */
@Service
public class DailyReportServiceImpl implements IDailyReportService
{
    @Autowired
    private DailyReportMapper dailyReportMapper;

    @Autowired
    private CollaborateTaskMapper collaborateTaskMapper;

    @Autowired
    private ReportAttachmentMapper reportAttachmentMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWeeklyReportService weeklyReportService;

    @Autowired
    private ISystemConfigService systemConfigService;

    /**
     * 查询日报
     *
     * @param id 日报主键
     * @return 日报
     */
    @Override
    public DailyReport selectDailyReportById(Long id)
    {
        DailyReport dailyReport = dailyReportMapper.selectDailyReportById(id);
        if (dailyReport != null) {
            // 加载附件列表
            dailyReport.setAttachmentList(
                reportAttachmentMapper.selectAttachmentsByReport(id, "0")
            );
        }
        return dailyReport;
    }

    /**
     * 查询日报列表
     *
     * @param dailyReport 日报
     * @return 日报
     */
    @Override
    public List<DailyReport> selectDailyReportList(DailyReport dailyReport)
    {
        return dailyReportMapper.selectDailyReportList(dailyReport);
    }

    /**
     * 新增日报
     *
     * @param dailyReport 日报
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDailyReport(DailyReport dailyReport)
    {
        // 自动填充用户信息
        if (dailyReport.getUserId() == null) {
            dailyReport.setUserId(SecurityUtils.getUserId());
        }

        SysUser user = userService.selectUserById(dailyReport.getUserId());
        if (user != null) {
            dailyReport.setUserName(user.getUserName());
            dailyReport.setDeptId(user.getDeptId());
            if (user.getDept() != null) {
                dailyReport.setDeptName(user.getDept().getDeptName());
            }
        }

        // 获取或创建周报（自动关联到本周周报）
        if (dailyReport.getWeeklyReportId() == null) {
            // 计算日报所属的周数
            Calendar cal = Calendar.getInstance();
            cal.setTime(dailyReport.getReportDate());
            int year = cal.get(Calendar.YEAR);
            int weekNum = cal.get(Calendar.WEEK_OF_YEAR);

            // 生成或获取周报
            WeeklyReport weeklyReport = weeklyReportService.generateWeeklyReport(
                dailyReport.getUserId(), year, weekNum
            );
            dailyReport.setWeeklyReportId(weeklyReport.getId());
        }

        // 自动填充今日计划（从昨天的明日计划）
        if (dailyReport.getTodayPlan() == null || dailyReport.getTodayPlan().isEmpty()) {
            DailyReport previousReport = dailyReportMapper.selectPreviousDailyReport(
                dailyReport.getUserId(), dailyReport.getReportDate()
            );
            if (previousReport != null && previousReport.getTomorrowPlan() != null) {
                dailyReport.setTodayPlan(previousReport.getTomorrowPlan());
            }
        }

        // 查询待处理的协作任务，合并到今日计划
        List<CollaborateTask> pendingTasks = collaborateTaskMapper.selectPendingTasksByDate(
            dailyReport.getUserId(), dailyReport.getReportDate()
        );
        if (pendingTasks != null && !pendingTasks.isEmpty()) {
            StringBuilder todayPlan = new StringBuilder(dailyReport.getTodayPlan() != null ? dailyReport.getTodayPlan() : "");
            for (CollaborateTask task : pendingTasks) {
                if (todayPlan.length() > 0) {
                    todayPlan.append("\n");
                }
                todayPlan.append("【协作任务】").append(task.getTaskContent());

                // 更新协作任务状态
                task.setStatus("1"); // 已添加到日报
                task.setProcessTime(new Date());
                collaborateTaskMapper.updateCollaborateTask(task);
            }
            dailyReport.setTodayPlan(todayPlan.toString());
        }

        dailyReport.setCreateTime(DateUtils.getNowDate());
        dailyReport.setCreateBy(SecurityUtils.getUsername());

        int result = dailyReportMapper.insertDailyReport(dailyReport);

        // 处理协作任务列表
        if (dailyReport.getCollaborateTaskList() != null && !dailyReport.getCollaborateTaskList().isEmpty()) {
            for (CollaborateTask task : dailyReport.getCollaborateTaskList()) {
                task.setSourceReportId(dailyReport.getId());
                task.setSourceUserId(dailyReport.getUserId());
                task.setSourceUserName(dailyReport.getUserName());
                task.setStatus("0"); // 待处理

                // 任务日期为明天
                Calendar cal = Calendar.getInstance();
                cal.setTime(dailyReport.getReportDate());
                cal.add(Calendar.DAY_OF_MONTH, 1);
                task.setTaskDate(cal.getTime());
            }
            collaborateTaskMapper.batchInsertCollaborateTask(dailyReport.getCollaborateTaskList());
        }

        return result;
    }

    /**
     * 修改日报
     *
     * @param dailyReport 日报
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDailyReport(DailyReport dailyReport)
    {
        dailyReport.setUpdateTime(DateUtils.getNowDate());
        dailyReport.setUpdateBy(SecurityUtils.getUsername());

        int result = dailyReportMapper.updateDailyReport(dailyReport);

        // 更新协作任务
        if (dailyReport.getCollaborateTaskList() != null && !dailyReport.getCollaborateTaskList().isEmpty()) {
            for (CollaborateTask task : dailyReport.getCollaborateTaskList()) {
                if (task.getId() == null) {
                    task.setSourceReportId(dailyReport.getId());
                    task.setSourceUserId(dailyReport.getUserId());
                    task.setSourceUserName(dailyReport.getUserName());
                    task.setStatus("0");

                    Calendar cal = Calendar.getInstance();
                    cal.setTime(dailyReport.getReportDate());
                    cal.add(Calendar.DAY_OF_MONTH, 1);
                    task.setTaskDate(cal.getTime());

                    collaborateTaskMapper.insertCollaborateTask(task);
                }
            }
        }

        return result;
    }

    /**
     * 批量删除日报
     *
     * @param ids 需要删除的日报主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDailyReportByIds(Long[] ids)
    {
        // 删除关联的附件记录
        for (Long id : ids) {
            reportAttachmentMapper.deleteAttachmentsByReport(id, "0");
        }
        return dailyReportMapper.deleteDailyReportByIds(ids);
    }

    /**
     * 删除日报信息
     *
     * @param id 日报主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDailyReportById(Long id)
    {
        // 删除关联的附件记录
        reportAttachmentMapper.deleteAttachmentsByReport(id, "0");
        return dailyReportMapper.deleteDailyReportById(id);
    }

    /**
     * 发布日报
     *
     * @param id 日报ID
     * @return 结果
     */
    @Override
    public int publishDailyReport(Long id)
    {
        DailyReport dailyReport = new DailyReport();
        dailyReport.setId(id);
        dailyReport.setStatus("1"); // 已发布
        dailyReport.setPublishTime(new Date());
        dailyReport.setUpdateBy(SecurityUtils.getUsername());
        dailyReport.setUpdateTime(DateUtils.getNowDate());

        return dailyReportMapper.updateDailyReport(dailyReport);
    }

    /**
     * 创建新日报（自动填充今日计划）
     *
     * @param userId 用户ID
     * @param reportDate 日期
     * @return 日报
     */
    @Override
    public DailyReport createDailyReport(Long userId, Date reportDate)
    {
        DailyReport dailyReport = new DailyReport();
        dailyReport.setUserId(userId);
        dailyReport.setReportDate(reportDate);
        dailyReport.setStatus("0"); // 草稿

        // 自动填充今日计划
        DailyReport previousReport = dailyReportMapper.selectPreviousDailyReport(userId, reportDate);
        if (previousReport != null && previousReport.getTomorrowPlan() != null) {
            dailyReport.setTodayPlan(previousReport.getTomorrowPlan());
        }

        // 查询协作任务
        List<CollaborateTask> pendingTasks = collaborateTaskMapper.selectPendingTasksByDate(userId, reportDate);
        if (pendingTasks != null && !pendingTasks.isEmpty()) {
            StringBuilder todayPlan = new StringBuilder(dailyReport.getTodayPlan() != null ? dailyReport.getTodayPlan() : "");
            for (CollaborateTask task : pendingTasks) {
                if (todayPlan.length() > 0) {
                    todayPlan.append("\n");
                }
                todayPlan.append("【协作任务】").append(task.getTaskContent());
            }
            dailyReport.setTodayPlan(todayPlan.toString());
        }

        return dailyReport;
    }

    /**
     * 查询授权日报列表
     *
     * @param dailyReport 查询条件
     * @return 日报集合
     */
    @Override
    public List<DailyReport> selectAuthDailyReportList(DailyReport dailyReport)
    {
        Long authUserId = SecurityUtils.getUserId();
        return dailyReportMapper.selectAuthDailyReportList(authUserId, dailyReport);
    }

    /**
     * 补交日报
     *
     * @param dailyReport 日报
     * @return 结果
     */
    @Override
    public int makeupDailyReport(DailyReport dailyReport)
    {
        // 检查是否允许补交
        String enableMakeup = systemConfigService.selectConfigByKey("enable.makeup");
        if (!"1".equals(enableMakeup)) {
            throw new RuntimeException("系统未开启补交功能");
        }

        // 检查补交天数限制
        String makeupDaysLimitStr = systemConfigService.selectConfigByKey("makeup.days.limit");
        int makeupDaysLimit = Integer.parseInt(makeupDaysLimitStr != null ? makeupDaysLimitStr : "7");

        long daysDiff = (new Date().getTime() - dailyReport.getReportDate().getTime()) / (1000 * 60 * 60 * 24);
        if (daysDiff > makeupDaysLimit) {
            throw new RuntimeException("超过补交时限（" + makeupDaysLimit + "天）");
        }

        dailyReport.setStatus("2"); // 补交
        dailyReport.setIsOverdue("1"); // 逾期
        dailyReport.setPublishTime(new Date());

        return insertDailyReport(dailyReport);
    }

    /**
     * 查询未提交日报的用户
     *
     * @param reportDate 日期
     * @return 用户ID列表
     */
    @Override
    public List<Long> getUnsubmittedUsers(Date reportDate)
    {
        return dailyReportMapper.selectUnsubmittedUserIds(reportDate);
    }
}
