package com.fs.survey.service.impl;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.fs.common.exception.ServiceException;
import com.fs.common.utils.DateUtils;
import com.fs.survey.domain.SurveyTaskPeriod;
import com.fs.survey.service.ISurveyTaskPeriodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.fs.survey.mapper.SurveyTaskMapper;
import com.fs.survey.domain.SurveyTask;
import com.fs.survey.service.ISurveyTaskService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 问卷任务主Service业务层处理
 * 
 * @author fs
 * @date 2026-02-06
 */
@Service
public class SurveyTaskServiceImpl implements ISurveyTaskService 
{
    @Autowired
    private SurveyTaskMapper surveyTaskMapper;

    @Lazy
    @Autowired
    private ISurveyTaskPeriodService surveyTaskPeriodService;
    /**
     * 查询问卷任务主
     * 
     * @param id 问卷任务主主键
     * @return 问卷任务主
     */
    @Override
    public SurveyTask selectSurveyTaskById(Long id)
    {
        return surveyTaskMapper.selectSurveyTaskById(id);
    }

    /**
     * 查询问卷任务主列表
     * 
     * @param surveyTask 问卷任务主
     * @return 问卷任务主
     */
    @Override
    public List<SurveyTask> selectSurveyTaskList(SurveyTask surveyTask)
    {
        return surveyTaskMapper.selectSurveyTaskList(surveyTask);
    }





    /**
     * 批量删除问卷任务主
     * 
     * @param ids 需要删除的问卷任务主主键
     * @return 结果
     */
    @Override
    public int deleteSurveyTaskByIds(Long[] ids)
    {
        return surveyTaskMapper.deleteSurveyTaskByIds(ids);
    }

    /**
     * 删除问卷任务主信息
     * 
     * @param id 问卷任务主主键
     * @return 结果
     */
    @Override
    public int deleteSurveyTaskById(Long id)
    {
        return surveyTaskMapper.deleteSurveyTaskById(id);
    }

    @Override
    public int updateSurveyTaskBaseInfo(SurveyTask surveyTask) {
        // 1. 检查参数是否为空
        if (surveyTask == null) {
            throw new ServiceException("问卷不能为空");
        }

        Long id = surveyTask.getId();
        if (id == null) {
            throw new ServiceException("任务ID不能为空");
        }

        // 2. 查询原任务信息
        SurveyTask tempTask = surveyTaskMapper.selectSurveyTaskById(id);
        if (tempTask == null) {
            throw new ServiceException("任务不存在或已被删除");
        }
        surveyTask.setYear(tempTask.getYear());

        return surveyTaskMapper.updateSurveyTask(surveyTask);
    }

    /**
     * 新增问卷任务主
     *
     * @param surveyTask 问卷任务主
     * @return 结果
     */
    @Transactional
    @Override
    public int insertSurveyTask(SurveyTask surveyTask) {
        // 1. 设置固定值
        surveyTask.setIntervalDays(90L); // 固定90天间隔

        // 2. 验证必填字段
        if (surveyTask.getYear() == null) {
            throw new ServiceException("所属年份不能为空");
        }

        // 3. 获取开始日期（优先使用createTime，没有则用当前时间）
        Date startDate = surveyTask.getCreateTime();
        if (startDate == null) {
            startDate = new Date();
        }

        // 4. 先计算期数（这样可以看到实际期数）
        List<SurveyTaskPeriod> periods = calculateTaskPeriods(surveyTask, startDate);
        surveyTask.setTotalPeriods((long) periods.size()); // 根据实际计算设置总期数

        // 5. 插入任务主表
        int result = surveyTaskMapper.insertSurveyTask(surveyTask);

        // 6. 如果插入成功，保存期数信息
        if (result > 0 && surveyTask.getId() != null) {
            // 保存期数到数据库

            for (SurveyTaskPeriod period : periods) {
                //都是同一批次
                period.setCreateTime(surveyTask.getUpdateTime());
                period.setTaskId(surveyTask.getId());
                period.setCompanyId(surveyTask.getCompanyId());
                surveyTaskPeriodService.insertSurveyTaskPeriod(period);
            }
        }

        return result;
    }

    /**
     * 修改问卷任务主
     *
     * @param surveyTask 问卷任务主
     * @return 结果
     */
    @Override
    public int updateSurveyTask(SurveyTask surveyTask) {
        // 如果需要重新计算期数（比如开始日期或年份有变化）
        if (surveyTask.getCreateTime() != null || surveyTask.getYear() != null) {
            // 先获取原始任务信息
            SurveyTask originalTask = surveyTaskMapper.selectSurveyTaskById(surveyTask.getId());
            if (originalTask != null) {
                Date startDate = surveyTask.getCreateTime() != null ?
                        surveyTask.getCreateTime() : originalTask.getCreateTime();
                Long year = surveyTask.getYear() != null ?
                        surveyTask.getYear() : originalTask.getYear();

                if (startDate != null && year != null) {
                    // 重新计算期数
                    surveyTask.setYear(year);
                    List<SurveyTaskPeriod> periods = calculateTaskPeriods(surveyTask, startDate);
                    surveyTask.setTotalPeriods((long) periods.size());

                    // 删除旧的期数
                    surveyTaskPeriodService.deleteSurveyTaskPeriodById(surveyTask.getId());

                    // 插入新的期数
                    for (SurveyTaskPeriod period : periods) {
                        period.setTaskId(surveyTask.getId());
                        surveyTaskPeriodService.insertSurveyTaskPeriod(period);
                    }
                }
            }
        }

        return surveyTaskMapper.updateSurveyTask(surveyTask);
    }

    private List<SurveyTaskPeriod> calculateTaskPeriods(SurveyTask surveyTask, Date startDate) {
        // 将Date转换为LocalDate方便计算
        LocalDate currentDate = startDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();

        // 获取年份（优先使用任务中的年份）
        int year = surveyTask.getYear() != null ? surveyTask.getYear().intValue() : currentDate.getYear();
        LocalDate endOfYear = LocalDate.of(year, 12, 31);

        List<SurveyTaskPeriod> periodList = new ArrayList<>();
        long periodCount = 0;
        long intervalDays = surveyTask.getIntervalDays() != null ? surveyTask.getIntervalDays() : 90L;

        // 计算期数，最多3期
        while (periodCount < 3 && !currentDate.isAfter(endOfYear)) {
            periodCount++;

            // 本期结束日期 = 开始日期 + (间隔天数-1)天
            LocalDate periodEndDate = currentDate.plusDays(intervalDays - 1);

            // 如果结束日期超过年底，则调整为年底
            if (periodEndDate.isAfter(endOfYear)) {
                periodEndDate = endOfYear;
            }

            // 创建期数对象
            SurveyTaskPeriod period = new SurveyTaskPeriod();
            period.setPeriodNum(periodCount);
            period.setPeriodStartTime(Date.from(currentDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
            period.setPeriodEndTime(Date.from(periodEndDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));

            periodList.add(period);

            // 下一期开始日期 = 本期结束日期 + 1天
            currentDate = periodEndDate.plusDays(1);

            // 如果下一期开始日期已经是下一年，则停止
            if (currentDate.getYear() != year) {
                break;
            }

            // 如果下一期开始时间距离年底不足intervalDays，但仍然在年内，则继续计算最后一期
            // 这个判断在while循环的条件中已经处理了 (!currentDate.isAfter(endOfYear))
        }

        return periodList;
    }


    /**
     * 获取任务的期数信息
     *
     * @param taskId 任务ID
     * @return 期数列表
     */
    public List<SurveyTaskPeriod> getTaskPeriods(Long taskId) {
        return surveyTaskPeriodService.selectSurveyTaskPeriodListByTaskId(taskId);
    }

    /**
     * 重新计算任务的期数（手动触发）
     *
     * @param taskId 任务ID
     * @param startDate 新的开始日期（可选）
     * @return 是否成功
     */
    public boolean recalculatePeriods(Long taskId, Date startDate) {
        SurveyTask task = surveyTaskMapper.selectSurveyTaskById(taskId);
        if (task == null) {
            return false;
        }

        // 使用新的开始日期或原有的开始日期
        Date calcStartDate = startDate != null ? startDate : task.getCreateTime();
        if (calcStartDate == null) {
            calcStartDate = new Date(); // 默认当前时间
        }

        // 计算期数
        List<SurveyTaskPeriod> periods = calculateTaskPeriods(task, calcStartDate);
        task.setTotalPeriods((long) periods.size());

        // 更新任务
        this.updateSurveyTask(task);

        // 删除旧的期数
        surveyTaskPeriodService.deleteSurveyTaskPeriodByTaskId(taskId);

        // 插入新的期数
        for (SurveyTaskPeriod period : periods) {
            period.setTaskId(taskId);
            surveyTaskPeriodService.insertSurveyTaskPeriod(period);
        }

        return true;
    }



}
