package com.ruoyi.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
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.OaProjectSchedule;
import com.ruoyi.oa.domain.bo.BatchBo;
import com.ruoyi.oa.mapper.OaProjectScheduleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.oa.domain.bo.OaProjectScheduleStepBo;
import com.ruoyi.oa.domain.vo.OaProjectScheduleStepVo;
import com.ruoyi.oa.domain.OaProjectScheduleStep;
import com.ruoyi.oa.mapper.OaProjectScheduleStepMapper;
import com.ruoyi.oa.service.IOaProjectScheduleStepService;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 项目进度步骤跟踪Service业务层处理
 *
 * @author hdka
 * @date 2025-05-08
 */
@RequiredArgsConstructor
@Service
public class OaProjectScheduleStepServiceImpl implements IOaProjectScheduleStepService {

    private final OaProjectScheduleStepMapper baseMapper;

    private final OaProjectScheduleMapper scheduleMapper;

    /**
     * 查询项目进度步骤跟踪
     */
    @Override
    public OaProjectScheduleStepVo queryById(Long trackId){
        return baseMapper.selectVoPlusById(trackId, LoginHelper.getUserId());
    }

    /**
     * 查询项目进度步骤跟踪列表
     */
    @Override
    public TableDataInfo<OaProjectScheduleStepVo> queryPageList(OaProjectScheduleStepBo bo, PageQuery pageQuery) {
        QueryWrapper<OaProjectScheduleStep> lqw = buildQueryWrapper(bo);
        Page<OaProjectScheduleStepVo> result = baseMapper.selectVoPagePlus(pageQuery.build(), lqw,LoginHelper.getUserId());
        return TableDataInfo.build(result);
    }

    /**
     * 查询项目进度步骤跟踪列表
     */
    @Override
    public List<OaProjectScheduleStepVo> queryList(OaProjectScheduleStepBo bo) {
        QueryWrapper<OaProjectScheduleStep> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private QueryWrapper<OaProjectScheduleStep> buildQueryWrapper(OaProjectScheduleStepBo bo) {
        Map<String, Object> params = bo.getParams();
        QueryWrapper<OaProjectScheduleStep> lqw = Wrappers.query();
        lqw.eq("opss.use_flag", 1);
        lqw.eq(bo.getScheduleId() != null, "opss.schedule_id", bo.getScheduleId());
        lqw.eq("opss.del_flag", 0);
        lqw.eq(bo.getStepOrder() != null, "opss.step_order", bo.getStepOrder());
        lqw.like(StringUtils.isNotBlank(bo.getStepName()), "opss.step_name", bo.getStepName());
        lqw.eq(bo.getStatus() != null, "opss.status", bo.getStatus());
        return lqw;
    }

    /**
     * 新增项目进度步骤跟踪
     */
    @Override
    public Boolean insertByBo(OaProjectScheduleStepBo bo) {
        OaProjectScheduleStep add = BeanUtil.toBean(bo, OaProjectScheduleStep.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTrackId(add.getTrackId());
        }
        return flag;
    }

    /**
     * 修改项目进度步骤跟踪
     */
    @Override
    public Boolean updateByBo(OaProjectScheduleStepBo bo) {

        // 除了做更新还需要编辑文件权限将涉及到的所有文件 都涉及到userId
        OaProjectScheduleStep update = BeanUtil.toBean(bo, OaProjectScheduleStep.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

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

    @Override
    public OaProjectScheduleStepVo maxStepByScheduleId(Long scheduleId) {
        return baseMapper.maxStepByScheduleId(scheduleId);
    }

    @Override
    public void updateByStepAndScheduleId(Long currentStep, Long scheduleId) {

        baseMapper.updateByStepAndScheduleId(currentStep,scheduleId);
    }

    @Override
    public OaProjectScheduleStepVo selectByCurrentStepAndScheduleId(Long currentStep, Long scheduleId) {
        return baseMapper.selectByCurrentStepAndScheduleId(currentStep,scheduleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeBatch(BatchBo batchBo) {
        List<OaProjectScheduleStepBo> boList = batchBo.getBoList();
        OaProjectScheduleStepBo oaProjectScheduleStepBo = boList.get(0);
        LambdaQueryWrapper<OaProjectScheduleStep> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OaProjectScheduleStep::getScheduleId, oaProjectScheduleStepBo.getScheduleId());
        wrapper.eq(OaProjectScheduleStep::getUseFlag, 1L);
        List<OaProjectScheduleStep> oaProjectScheduleSteps = baseMapper.selectList(wrapper);
        Long batchId = 1L;
        // 首先将上一批次的全部关闭
        for (OaProjectScheduleStep oaProjectScheduleStep : oaProjectScheduleSteps) {
            oaProjectScheduleStep.setUseFlag(0L);
            System.out.println(oaProjectScheduleStep);
            baseMapper.updateById(oaProjectScheduleStep);
            batchId = oaProjectScheduleStep.getBatchId();
        }


        OaProjectSchedule oaProjectSchedule = new OaProjectSchedule();
        oaProjectSchedule.setScheduleId(oaProjectScheduleStepBo.getScheduleId());
        oaProjectSchedule.setCurrentStep(batchBo.getCurrentStep());
        scheduleMapper.updateById(oaProjectSchedule);
        // 新批次进入
        int flag = 0;
        batchId = batchId+1;
        for (OaProjectScheduleStepBo projectScheduleStepBo : boList) {
            projectScheduleStepBo.setTrackId(null);
            projectScheduleStepBo.setUseFlag(1L);
            projectScheduleStepBo.setScheduleId(oaProjectScheduleStepBo.getScheduleId());
            projectScheduleStepBo.setBatchId(batchId);

            // 将新增后的
            if (projectScheduleStepBo.getStepOrder()> batchBo.getCurrentStep()){
                projectScheduleStepBo.setActualStart(null);
                projectScheduleStepBo.setActualEnd(null);
                projectScheduleStepBo.setStatus(0L);
            }

            // 将新增后的
            if (Objects.equals(projectScheduleStepBo.getStepOrder(), batchBo.getCurrentStep())){
                projectScheduleStepBo.setActualStart(new Date());
                projectScheduleStepBo.setActualEnd(null);
                projectScheduleStepBo.setStatus(0L);
            }
            this.insertByBo(projectScheduleStepBo);
            flag =1;
        }

        return flag;
    }
}
