package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.oa.domain.*;
import com.ruoyi.oa.domain.bo.SysOaTaskItemBo;
import com.ruoyi.oa.mapper.SysOaTaskItemMapper;
import com.ruoyi.oa.service.ISysOaTaskItemService;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.SysOaTaskBo;
import com.ruoyi.oa.domain.vo.SysOaTaskVo;
import com.ruoyi.oa.mapper.SysOaTaskMapper;
import com.ruoyi.oa.service.ISysOaTaskService;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务管理Service业务层处理
 *
 * @author huangxing
 * @date 2024-01-11
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SysOaTaskServiceImpl implements ISysOaTaskService {

    private final SysOaTaskMapper baseMapper;

    private final ISysOaTaskItemService taskItemService;

    private final SysOaTaskItemMapper taskItemMapper;

    private final ISysOssService ossService;

    /**
     * 查询任务管理
     */
    @Override
    public SysOaTaskVo queryById(Long taskId){
        return baseMapper.selectDetailVoById(taskId);
    }

    /**
     * 查询任务管理列表
     */
    @Override
    public TableDataInfo<SysOaTaskVo> queryPageList(SysOaTaskBo bo, PageQuery pageQuery) {
        QueryWrapper<SysOaTask> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc("sot.task_rank");
        lqw.orderByDesc("sot.create_time");
        Page<SysOaTaskVo> result = baseMapper.selectListVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<SysOaTaskVo> queryPageListOwn(SysOaTaskBo bo, PageQuery pageQuery) {
        QueryWrapper<SysOaTask> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc("sot.own_rank");
        lqw.orderByDesc("sot.create_time");
        Page<SysOaTaskVo> result = baseMapper.selectListVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public void addPostpones(Long taskId) {

    }

    @Override
    public TableDataInfo<UserMonthlyData> getMonthlyData(String month) {
        List<UserMonthlyData> result = baseMapper.getMonthlyData(month);
        return TableDataInfo.build(result);
    }

    @Override
    public TableDataInfo<SysOaTaskVo> queryPageListDocument(SysOaTaskBo bo, PageQuery pageQuery) {
        QueryWrapper<SysOaTask> lqw = new QueryWrapper<>();
        lqw.eq("sotu.user_id", LoginHelper.getUserId());
        lqw.eq("sot.del_flag", 0);
//        lqw.eq("sot.create_user_id", LoginHelper.getUserId())
//                .or()
//                .eq("sot.worker_id", LoginHelper.getUserId());
        lqw.isNotNull("sot.accessory")
                 .or()
            .isNotNull("soti.files");
        lqw.orderByDesc("sot.create_time");
        Page<SysOaTaskVo> result = baseMapper.queryPageListDocument(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询任务管理列表
     */
    @Override
    public List<SysOaTaskVo> queryList(SysOaTaskBo bo) {
        QueryWrapper<SysOaTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询任务管理列表
     */
    @Override
    public List<SysOaTaskVo> queryListByRemain(SysOaTaskBo bo, PageQuery pageQuery) {
        QueryWrapper<SysOaTask> lqw = buildQueryWrapper(bo);
        return baseMapper.selectListVoPage(pageQuery.build(),lqw).getRecords();
    }

    @Override
    public List<SysOaTaskVo> listDocumentProject(Long projectId) {

        return baseMapper.listDocumentProject(projectId);
    }

    private QueryWrapper<SysOaTask> buildQueryWrapper(SysOaTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<SysOaTask> lqw = Wrappers.query();
        lqw.eq("sot.del_flag", 0);
        lqw.eq(bo.getProjectId()!=null, "sot.project_id", bo.getProjectId());
        lqw.eq(bo.getCreateUserId()!=null, "sot.create_user_id", bo.getCreateUserId());
        lqw.eq(bo.getWorkerId()!=null, "sot.worker_id", bo.getWorkerId());
        lqw.eq(bo.getProjectId()!=null, "sot.project_id", bo.getProjectId());
        lqw.eq(bo.getProjectNum()!=null, "sop.project_num", bo.getProjectNum());
        lqw.eq(bo.getState()!=null, "sot.state", bo.getState());
        lqw.eq(bo.getItemStatus()!=null, "soti.status", bo.getItemStatus());
        lqw.like(bo.getTaskTitle()!=null, "sot.task_title", bo.getTaskTitle());
        lqw.isNotNull("sot.task_title");
        lqw.like(bo.getTaskTitle()!=null, "sot.task_title", bo.getTaskTitle());
        lqw.like(bo.getCreateUserNickName()!=null, "su1.nick_name", bo.getCreateUserNickName());
        lqw.like(bo.getWorkerNickName()!=null, "su2.nick_name", bo.getWorkerNickName());
        return lqw;
    }

    /**
     * 新增任务管理
     */
    @Override
    public Boolean insertByBo(SysOaTaskBo bo) {
        List<Long> workerIdList = new ArrayList<>();
        // 拿到所有的执行人id列表进行遍历添加
        if (bo.getWorkerIds()!=null) {
            System.out.println(bo.getWorkerIds());
            workerIdList = Arrays.stream(bo.getWorkerIds().split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
            System.out.println(workerIdList);
        }else{
            // 适配文件上传
            bo.setBeginTime(new Date());
            bo.setCompletedTime(new Date());
            bo.setFinishTime(new Date());
            workerIdList.add(LoginHelper.getUserId());
        }

        boolean flag = false;
        for (Long workerId : workerIdList) {
            SysOaTask add = BeanUtil.toBean(bo, SysOaTask.class);
            add.setCreateUserId(LoginHelper.getUserId());
            add.setOriginFinishTime(add.getFinishTime());
            add.setWorkerId(workerId);
            flag = baseMapper.insert(add) > 0;
            // 判断是否为报工模式
            if (bo.getStatus()==1L){
                // 这里新增item数据，为单个条目
                SysOaTaskItemBo sysOaTaskItemBo = new SysOaTaskItemBo();
                sysOaTaskItemBo.setTaskId(add.getTaskId());
                sysOaTaskItemBo.setBeginTime(add.getBeginTime());
                Date firstFinishTime = addDays(add.getBeginTime(),add.getTimeGap());
                sysOaTaskItemBo.setOriginEndTime(firstFinishTime);
                sysOaTaskItemBo.setEndTime(firstFinishTime);
                taskItemService.insertByBo(sysOaTaskItemBo);
            }
        }

        return flag;
    }

    /**
     * 修改任务管理
     */
    @Override
    public Boolean updateByBo(SysOaTaskBo bo) {
        // 先删除所有的bo然后再次进行新增操作
        SysOaTask update = BeanUtil.toBean(bo, SysOaTask.class);
        // 再进行重新新增
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysOaTask entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除任务管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 推迟任务state=15代表申请延期
     * @param bo
     * @return
     */
    @Override
    public Boolean postponeTask(SysOaTaskBo bo) {
        // 防止截止日期被写入 新增对象
        SysOaTaskBo sysOaTaskBo = new SysOaTaskBo();
        sysOaTaskBo.setTaskId(bo.getTaskId());
        sysOaTaskBo.setState(15L);
        sysOaTaskBo.setTempTime(bo.getTempTime());
        if (bo.getStatus()==1L && bo.getItemId()!=null ){
            SysOaTaskItemBo sysOaTaskItemBo = new SysOaTaskItemBo();
            sysOaTaskItemBo.setItemId(bo.getItemId());
            sysOaTaskItemBo.setTempTime(bo.getTempTime());
            taskItemService.updateByBo(sysOaTaskItemBo);
        }
        return updateByBo(sysOaTaskBo);
    }

    /**
     * 20为同
     * @param bo
     * @return
     */
    @Override
    public Boolean postponeSuccess(SysOaTaskBo bo) {
        SysOaTask sysOaTask = baseMapper.selectById(bo.getTaskId());
        sysOaTask.setState(0L);
        sysOaTask.setPostponements(sysOaTask.getPostponements() + 1);
        if (sysOaTask.getStatus()!=1L){
            sysOaTask.setFinishTime(sysOaTask.getTempTime());
        }else{
            SysOaTaskItem sysOaTaskItem = taskItemMapper.selectById(bo.getItemId());
            sysOaTaskItem.setEndTime(sysOaTaskItem.getTempTime());
            taskItemMapper.updateById(sysOaTaskItem);
        }
        return baseMapper.updateById(sysOaTask) > 0;
    }




    /**
     * 使用 Java 8 的 LocalDateTime 在 beginTime 上加上 timeGap 天并返回新的 Date。
     *
     * @param beginTime 开始时间（Date类型）
     * @param timeGap   需要增加的天数（Long类型）
     * @return 加上 timeGap 天后的日期（Date类型）
     */
    public static Date addDays(Date beginTime, Long timeGap) {
        if (beginTime == null || timeGap == null) {
            return null; // 或根据业务需求进行异常处理
        }

        // 将 Date 转为 LocalDateTime
        LocalDateTime localDateTime = beginTime.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime();

        // 加上 timeGap 天
        localDateTime = localDateTime.plusDays(timeGap);

        // 再转换回 Date
        return Date.from(localDateTime
                .atZone(ZoneId.systemDefault())
                .toInstant());
    }
}
