package com.fs.course.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.bean.BeanUtils;
import com.fs.course.domain.FsUserCoursePeriod;
import com.fs.course.domain.FsUserCoursePeriodDays;
import com.fs.course.domain.FsUserCourseTrainingCamp;
import com.fs.course.dto.FsUserCourseTrainingCampDTO;
import com.fs.course.mapper.*;
import com.fs.course.service.IFsUserCoursePeriodDaysService;
import com.fs.course.service.IFsUserCourseTrainingCampService;
import com.fs.course.vo.FsUserCourseTrainingCampVO;
import com.fs.his.vo.OptionsVO;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 会员训练营Service业务层处理
 *
 * @author fs
 * @date 2025-04-15
 */
@Service
@AllArgsConstructor
public class FsUserCourseTrainingCampServiceImpl extends ServiceImpl<FsUserCourseTrainingCampMapper, FsUserCourseTrainingCamp> implements IFsUserCourseTrainingCampService
{

    private final FsUserCoursePeriodMapper fsUserCoursePeriodMapper;
    private final FsUserCourseVideoRedPackageMapper fsUserCourseVideoRedPackageMapper;

    private final FsUserCoursePeriodDaysMapper fsUserCoursePeriodDaysMapper;

    private final IFsUserCoursePeriodDaysService fsUserCoursePeriodDaysService;
    private final FsCourseWatchLogMapper fsCourseWatchLogMapper;

    /**
     * 查询训练营列表
     * @param params    参数
     * @return  list
     */
    @Override
    public List<FsUserCourseTrainingCampVO> selectFsUserCourseTrainingCampVOListByMap(Map<String, Object> params) {
        List<FsUserCourseTrainingCampVO> trainingCampVOS = baseMapper.selectFsUserCourseTrainingCampVOListByMap(params);
        trainingCampVOS.forEach(camp -> camp.setVipCount(fsCourseWatchLogMapper.getUserCountByCampId(camp.getTrainingCampId())));
        return trainingCampVOS;
    }

    /**
     * 新增训练营
     * @param params    参数
     */
    @Override
    public void add(FsUserCourseTrainingCampDTO params,Long userId) {
        FsUserCourseTrainingCamp trainingCamp = new FsUserCourseTrainingCamp();
        trainingCamp.setTrainingCampName(params.getTrainingCampName());
        trainingCamp.setOrderNumber(baseMapper.getOrderNumber());
        trainingCamp.setCreateTime(LocalDateTime.now());
        trainingCamp.setUserId(userId);
        baseMapper.insert(trainingCamp);
    }

    /**
     * 删除训练营
     * @param ids   ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void del(Long[] ids) {
        // 检查是否存在进行中或者已结束的营期
        if (checkPeriodStatus(ids)) {
            throw new ServiceException("存在进行中或已结束的营期，不允许删除");
        }
        batchUpdateDelFlag(Arrays.asList(ids),1);

        // 删除训练营的同时需要删除营期
        List<FsUserCoursePeriod> fsUserCoursePeriods = fsUserCoursePeriodMapper.selectPeriodListByTrainingCampIds(ids);
        List<Long> periodIds = fsUserCoursePeriods.stream().map(FsUserCoursePeriod::getPeriodId).collect(Collectors.toList());
        if(!periodIds.isEmpty()){
            fsUserCoursePeriodMapper.updateBatchDelFlag(periodIds.toArray(new Long[0]),1);
        }
        //删除课程
        Set<Long> set = periodIds.stream().collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(set)){
            return;
        }
        List<FsUserCoursePeriodDays> fsUserCoursePeriodDays = fsUserCoursePeriodDaysMapper.selectCourseVideoList(set);
        List<Long> periodDayIds = fsUserCoursePeriodDays.stream().map(FsUserCoursePeriodDays::getId).collect(Collectors.toList());
        if(!periodDayIds.isEmpty()){
            fsUserCoursePeriodDaysMapper.updateBatchDelFlag(periodDayIds.toArray(new Long[0]),1);
            //删除红包记录（修改状态）
            //fsUserCourseVideoRedPackageMapper.updateBatchDelFlag(videoIds.toArray(new Long[0]),1);
            //直接删除
            fsUserCourseVideoRedPackageMapper.deleteBatchByPeriodIds(set.toArray(new Long[0]));
        }
    }

    /**
     * 批量修改训练列表数据
     * @param ids
     * @param delFlag
     * @return
     */
    public int batchUpdateDelFlag(List<Long> ids, Integer delFlag) {
        LambdaUpdateWrapper<FsUserCourseTrainingCamp> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(FsUserCourseTrainingCamp::getTrainingCampId, ids)
                .set(FsUserCourseTrainingCamp::getDelFlag, delFlag);

        return baseMapper.update(null, updateWrapper);
    }
    /**
     * 检查是否存在进行中的营期
     * @param ids 训练营ID集合
     */
    private boolean checkPeriodStatus(Long[] ids) {
        Map<String, Object> params = new HashMap<>();
        params.put("ids", ids);
        params.put("date", LocalDate.now());
        return fsUserCoursePeriodMapper.countPeriodByCampIds(params) > 0;
    }

    /**
     * 复制训练营
     * @param id    id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copy(Long id) {
        FsUserCourseTrainingCamp fsUserCourseTrainingCamp = baseMapper.selectById(id);
        if (Objects.isNull(fsUserCourseTrainingCamp)) {
            throw new ServiceException("训练营不存在");
        }

        // 复制训练营
        FsUserCourseTrainingCamp trainingCamp = new FsUserCourseTrainingCamp();
        trainingCamp.setTrainingCampName(fsUserCourseTrainingCamp.getTrainingCampName() + " - 副本");
        trainingCamp.setOrderNumber(baseMapper.getOrderNumber());
        trainingCamp.setCreateTime(LocalDateTime.now());
        baseMapper.insert(trainingCamp);

        // 复制营期-课程
        fsUserCoursePeriodMapper.selectFsUserCoursePeriodListByTrainingCampId(id).forEach(p -> {
            // 复制营期
            FsUserCoursePeriod copy = new FsUserCoursePeriod();
            BeanUtils.copyProperties(p, copy, "periodId");
            copy.setTrainingCampId(trainingCamp.getTrainingCampId());
            fsUserCoursePeriodMapper.insertFsUserCoursePeriod(copy);

            // 复制课程
            Wrapper<FsUserCoursePeriodDays> queryWrapper = Wrappers.<FsUserCoursePeriodDays>lambdaQuery().eq(FsUserCoursePeriodDays::getPeriodId, p.getPeriodId());
            List<FsUserCoursePeriodDays> collect = fsUserCoursePeriodDaysService.list(queryWrapper).stream().map(d -> {
                FsUserCoursePeriodDays copyD = new FsUserCoursePeriodDays();
                BeanUtils.copyProperties(d, copyD, "id");
                copyD.setPeriodId(copy.getPeriodId());
                copyD.setCreateTime(new Date());
                return copyD;
            }).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                fsUserCoursePeriodDaysService.saveBatch(collect);
            }
        });
    }

    /**
     * 查询训练营选项列表
     * @param params    参数
     * @return  list
     */
    @Override
    public List<OptionsVO> selectCampListByMap(Map<String, Object> params) {
        return baseMapper.selectCampListByMap(params);
    }

    @Override
    public List<FsUserCourseTrainingCampVO> selectTrainingCampListForApp(Map<String, Object> params) {
        return baseMapper.selectTrainingCampListForApp(params);
    }
}
