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.DailyReport;
import com.ygtx.worklog.domain.WeeklyReport;
import com.ygtx.worklog.mapper.WeeklyReportMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.worklog.service.IWeeklyReportService;
import com.ygtx.system.service.ISysUserService;

/**
 * 周报Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-21
 */
@Service
public class WeeklyReportServiceImpl implements IWeeklyReportService
{
    @Autowired
    private WeeklyReportMapper weeklyReportMapper;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询周报
     *
     * @param id 周报主键
     * @return 周报
     */
    @Override
    public WeeklyReport selectWeeklyReportById(Long id)
    {
        return weeklyReportMapper.selectWeeklyReportById(id);
    }

    /**
     * 查询周报列表
     *
     * @param weeklyReport 周报
     * @return 周报
     */
    @Override
    public List<WeeklyReport> selectWeeklyReportList(WeeklyReport weeklyReport)
    {
        return weeklyReportMapper.selectWeeklyReportList(weeklyReport);
    }

    /**
     * 新增周报（不再直接使用，仅供内部调用）
     *
     * @param weeklyReport 周报
     * @return 结果
     */
    @Override
    public int insertWeeklyReport(WeeklyReport weeklyReport)
    {
        // 自动填充用户信息
        if (weeklyReport.getUserId() == null) {
            weeklyReport.setUserId(SecurityUtils.getUserId());
        }

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

        // 自动计算周数和日期
        if (weeklyReport.getStartDate() == null) {
            Date now = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(now);

            // 设置为本周一
            cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            weeklyReport.setStartDate(cal.getTime());

            // 设置为本周日
            cal.add(Calendar.DAY_OF_WEEK, 6);
            weeklyReport.setEndDate(cal.getTime());

            // 计算周数
            cal.setTime(now);
            weeklyReport.setYear(cal.get(Calendar.YEAR));
            weeklyReport.setWeekNum(cal.get(Calendar.WEEK_OF_YEAR));
        }

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

        return weeklyReportMapper.insertWeeklyReport(weeklyReport);
    }

    /**
     * 修改周报
     *
     * @param weeklyReport 周报
     * @return 结果
     */
    @Override
    public int updateWeeklyReport(WeeklyReport weeklyReport)
    {
        weeklyReport.setUpdateTime(DateUtils.getNowDate());
        weeklyReport.setUpdateBy(SecurityUtils.getUsername());
        return weeklyReportMapper.updateWeeklyReport(weeklyReport);
    }

    /**
     * 批量删除周报
     *
     * @param ids 需要删除的周报主键
     * @return 结果
     */
    @Override
    public int deleteWeeklyReportByIds(Long[] ids)
    {
        return weeklyReportMapper.deleteWeeklyReportByIds(ids);
    }

    /**
     * 删除周报信息
     *
     * @param id 周报主键
     * @return 结果
     */
    @Override
    public int deleteWeeklyReportById(Long id)
    {
        return weeklyReportMapper.deleteWeeklyReportById(id);
    }

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

        return weeklyReportMapper.updateWeeklyReport(weeklyReport);
    }

    /**
     * 自动生成周报（基于本周日报）
     *
     * @param userId 用户ID
     * @param year 年份
     * @param weekNum 周数
     * @return 周报
     */
    @Override
    public WeeklyReport generateWeeklyReport(Long userId, Integer year, Integer weekNum)
    {
        // 检查是否已存在周报
        WeeklyReport existingReport = weeklyReportMapper.selectWeeklyReportByUserAndWeek(userId, year, weekNum);
        if (existingReport != null) {
            return existingReport;
        }

        // 获取本周的所有日报
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, weekNum);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        Date startDate = cal.getTime();

        cal.add(Calendar.DAY_OF_WEEK, 6);
        Date endDate = cal.getTime();

        // 查询本周的所有已发布日报
        DailyReport queryParam = new DailyReport();
        queryParam.setUserId(userId);
        // 这里需要添加日期范围查询，简化处理

        // 创建周报
        WeeklyReport weeklyReport = new WeeklyReport();
        weeklyReport.setUserId(userId);
        weeklyReport.setYear(year);
        weeklyReport.setWeekNum(weekNum);
        weeklyReport.setStartDate(startDate);
        weeklyReport.setEndDate(endDate);

        // 填充用户信息
        SysUser user = userService.selectUserById(userId);
        if (user != null) {
            weeklyReport.setUserName(user.getUserName());
            weeklyReport.setDeptId(user.getDeptId());
            if (user.getDept() != null) {
                weeklyReport.setDeptName(user.getDept().getDeptName());
            }
        }

        // TODO: 这里可以集成 AI 总结功能，根据日报内容生成周总结
        // 目前先留空，由用户手动编辑
        weeklyReport.setWeekPlan("本周工作计划将基于日报自动生成...");
        weeklyReport.setCompletionStatus("本周完成情况将基于日报自动汇总...");
        weeklyReport.setIssuesSuggestions("本周问题及建议将基于日报自动汇总...");
        weeklyReport.setIsAutoGenerated("1"); // 自动生成
        weeklyReport.setStatus("0"); // 草稿

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

        weeklyReportMapper.insertWeeklyReport(weeklyReport);

        return weeklyReport;
    }

    /**
     * 手动编辑周报
     *
     * @param weeklyReport 周报
     * @return 结果
     */
    @Override
    public int editWeeklyReport(WeeklyReport weeklyReport)
    {
        weeklyReport.setIsAutoGenerated("0"); // 标记为手动编辑
        weeklyReport.setUpdateTime(DateUtils.getNowDate());
        weeklyReport.setUpdateBy(SecurityUtils.getUsername());
        return weeklyReportMapper.updateWeeklyReport(weeklyReport);
    }

    /**
     * 查询授权周报列表
     *
     * @param weeklyReport 查询条件
     * @return 周报集合
     */
    @Override
    public List<WeeklyReport> selectAuthWeeklyReportList(WeeklyReport weeklyReport)
    {
        Long authUserId = SecurityUtils.getUserId();
        return weeklyReportMapper.selectAuthWeeklyReportList(authUserId, weeklyReport);
    }
}
