package shop.alien.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import shop.alien.entity.store.ActivityPeriod;
import shop.alien.entity.store.ActivitySignInConfig;
import shop.alien.entity.store.ActivitySignInReward;
import shop.alien.entity.store.vo.ActivityConfigVo;
import shop.alien.entity.store.vo.ActivityPeriodVo;
import shop.alien.mapper.ActivityPeriodMapper;
import shop.alien.mapper.ActivitySignRewardMapper;
import shop.alien.store.service.ActivityConfigService;
import shop.alien.mapper.ActivitySignInConfigMapper;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 *
 * 签到类型活动服务
 * @author zhangchen
 * @since 2025-9-8
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ActivityConfigServiceImpl extends ServiceImpl<ActivitySignInConfigMapper, ActivitySignInConfig> implements ActivityConfigService {

    private final ActivitySignInConfigMapper activitySignInConfigMapper;
    private final ActivitySignRewardMapper activitySignRewardMapper;
    private final ActivityPeriodMapper activityPeriodMapper;

    @Override
    public ActivityConfigVo createOrUpdateActivity(ActivityConfigVo configVO) {
        log.info("创建活动开始执行，请求参数: {}", configVO);
        if(configVO == null) {
            log.error("创建活动configVO为空。");
            configVO = new ActivityConfigVo();
            configVO.setErrorMessage("参数为空");
            return configVO;
        }
        List<ActivitySignInReward> activitySignInRewardList = configVO.getRewards();

        // 校验是否存在重复时间段的方案
        List<ActivityPeriod> activityPeriodList = configVO.getActivityPeriodList();
        if(!CollectionUtils.isEmpty(activityPeriodList)){
            boolean checkPeriodResult= checkPeriodTime(activityPeriodList);
            if(!checkPeriodResult){
                configVO.setErrorMessage("方案时间重叠");
                return configVO;
            }
        }

        ActivitySignInConfig activitySignInConfig = new ActivitySignInConfig();

        if(configVO.getId() == null) {
            if(configVO.getPlanConfigType()!=null && configVO.getPlanConfigType() == 1){
                // 创建默认活动，先check是否已经存在默认数据
                LambdaQueryWrapper<ActivitySignInConfig> activitySignInConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
                activitySignInConfigLambdaQueryWrapper.eq(ActivitySignInConfig::getDeleteFlag, 0);
                activitySignInConfigLambdaQueryWrapper.eq(ActivitySignInConfig::getPlanConfigType, 1);
                int count = activitySignInConfigMapper.selectCount(activitySignInConfigLambdaQueryWrapper);
                if(count > 0){
                    log.error("已经存在默认方案，请不要重复创建。");
                    configVO.setErrorMessage("已经存在默认方案，请不要重复创建。");
                    return configVO;
                }
            }

            //创建活动操作
            BeanUtils.copyProperties(configVO, activitySignInConfig);
            if( activitySignInConfig.getPlanConfigType()!=null&&activitySignInConfig.getPlanConfigType() == 1){
                activitySignInConfig.setStatus(1);
            }
            int configInsertResult = activitySignInConfigMapper.insert(activitySignInConfig);
            if(configInsertResult == 0){
                //插入活动配置数据失败，返回
                log.error("插入活动配置数据失败, {}", configVO);
                configVO.setErrorMessage("插入活动配置数据失败");
                return configVO;
            }

            // 创建时间段数据
            if(!CollectionUtils.isEmpty(activityPeriodList)) {
                activityPeriodList.forEach(item -> {
                    item.setActivityId(activitySignInConfig.getId());
                    activityPeriodMapper.insert(item);
                });
            }

            // 创建活动奖励记录
            if(!CollectionUtils.isEmpty(activitySignInRewardList)){
                activitySignInRewardList.forEach(item -> {
                    item.setActivityId(activitySignInConfig.getId());
                    activitySignRewardMapper.insert(item);
                });
            }
        } else {
            //更新操作
            BeanUtils.copyProperties(configVO, activitySignInConfig);
            int configUpdateResult =  activitySignInConfigMapper.updateById(activitySignInConfig);
            if(configUpdateResult == 0){
                //更新活动配置数据失败，返回
                log.error("更新活动配置数据失败, {}", configVO);
                configVO.setErrorMessage("更新活动配置数据失败");
                return configVO;
            }
            int activityId = configVO.getId();

            //更新时间段信息
            LambdaQueryWrapper<ActivityPeriod> deletePeriodWrapper = new LambdaQueryWrapper<>();
            deletePeriodWrapper.eq(ActivityPeriod::getActivityId, configVO.getId());
            activityPeriodMapper.delete(deletePeriodWrapper);
            if(!CollectionUtils.isEmpty(activityPeriodList)){
                activityPeriodList.forEach(item -> {
                    item.setActivityId(activityId);
                    activityPeriodMapper.insert(item);
                });
            }

            //更新活动奖励
            LambdaQueryWrapper<ActivitySignInReward> deleteRewardWrapper = new LambdaQueryWrapper<>();
            deleteRewardWrapper.eq(ActivitySignInReward::getActivityId, configVO.getId());
            activitySignRewardMapper.delete(deleteRewardWrapper);
            if(!CollectionUtils.isEmpty(activitySignInRewardList)){
                activitySignInRewardList.forEach(item -> {
                item.setActivityId(activityId);
                activitySignRewardMapper.insert(item);
            });

            }
        }
        return configVO;
    }

    private boolean  checkPeriodTime(List<ActivityPeriod> activityPeriodList){
        if (activityPeriodList == null || activityPeriodList.size() <= 1) {
            return true;
        }

        // 按开始时间排序
        List<ActivityPeriod> sorted = new ArrayList<>(activityPeriodList);
        sorted.sort(Comparator.comparing(ActivityPeriod::getStartTime));
        for (int i = 0; i < sorted.size() - 1; i++) {
            ActivityPeriod current = sorted.get(i);
            ActivityPeriod next = sorted.get(i + 1);

            // 检查重叠条件：当前结束时间 > 下一个开始时间
            if (current.getEndTime().compareTo(next.getStartTime()) > 0) {
                return false; // 存在重叠
            }
        }
        return true;
    }

    @Override
    public ActivitySignInConfig updateActivity(Long id, ActivityConfigVo configVO) {
        return null;
    }

    @Override
    public ActivityConfigVo getActivitySignInConfigById(Long id) {
        ActivityConfigVo activityConfigVO = new ActivityConfigVo();
        if(id == null || id == 0){
            //id为空
            return activityConfigVO;
        }

        // 查询签到活动配置信息
        ActivitySignInConfig activitySignInConfig = activitySignInConfigMapper.selectById(id);
        if(activitySignInConfig == null){
            return activityConfigVO;
        }
        BeanUtils.copyProperties(activitySignInConfig, activityConfigVO);

        // 查询活动奖励列表
        LambdaQueryWrapper<ActivitySignInReward> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivitySignInReward::getActivityId, id);
        wrapper.eq(ActivitySignInReward::getDeleteFlag,0);
        List <ActivitySignInReward> activitySignInRewardList = activitySignRewardMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(activitySignInRewardList)){
            activityConfigVO.setRewards(activitySignInRewardList);
        }
        // 查询活动时间段列表
        LambdaQueryWrapper<ActivityPeriod> activityPeriodWrapper = new LambdaQueryWrapper<>();
        activityPeriodWrapper.eq(ActivityPeriod::getActivityId, id);
        activityPeriodWrapper.eq(ActivityPeriod::getDeleteFlag,0);
        List <ActivityPeriod> activityPeriodList = activityPeriodMapper.selectList(activityPeriodWrapper);
        if(!CollectionUtils.isEmpty(activityPeriodList)){
            activityConfigVO.setActivityPeriodList(activityPeriodList);
        }

        return activityConfigVO;
    }

    @Override
    public ActivityConfigVo getDefaultActivitySignInConfigById() {
        ActivityConfigVo activityConfigVO = new ActivityConfigVo();

        // 查询签到活动配置信息
        LambdaQueryWrapper<ActivitySignInConfig> activitySignInConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        activitySignInConfigLambdaQueryWrapper.eq(ActivitySignInConfig::getDeleteFlag, 0);
        activitySignInConfigLambdaQueryWrapper.eq(ActivitySignInConfig::getPlanConfigType,1);
        ActivitySignInConfig activitySignInConfig = activitySignInConfigMapper.selectOne(activitySignInConfigLambdaQueryWrapper);
        if(activitySignInConfig == null){
            return activityConfigVO;
        }
        BeanUtils.copyProperties(activitySignInConfig, activityConfigVO);

        // 查询活动奖励列表
        LambdaQueryWrapper<ActivitySignInReward> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivitySignInReward::getActivityId, activitySignInConfig.getId());
        wrapper.eq(ActivitySignInReward::getDeleteFlag,0);
        List <ActivitySignInReward> activitySignInRewardList = activitySignRewardMapper.selectList(wrapper);
        if(!CollectionUtils.isEmpty(activitySignInRewardList)){
            activityConfigVO.setRewards(activitySignInRewardList);
        }
        // 查询活动时间段列表
        LambdaQueryWrapper<ActivityPeriod> activityPeriodWrapper = new LambdaQueryWrapper<>();
        activityPeriodWrapper.eq(ActivityPeriod::getActivityId, activitySignInConfig.getId());
        activityPeriodWrapper.eq(ActivityPeriod::getDeleteFlag,0);
        List <ActivityPeriod> activityPeriodList = activityPeriodMapper.selectList(activityPeriodWrapper);
        if(!CollectionUtils.isEmpty(activityPeriodList)){
            activityConfigVO.setActivityPeriodList(activityPeriodList);
        }

        return activityConfigVO;
    }

    @Override
    public List<ActivityPeriodVo> checkOverlapTime(String startTime, String endTime) {
        List<ActivityPeriodVo> activityPeriodVoList = new ArrayList<>();
        if(startTime != null && endTime != null){

            activityPeriodVoList =  activityPeriodMapper.getActivityPeriodList(startTime, endTime);
        }
        return activityPeriodVoList;
    }

    @Override
    public IPage<ActivitySignInConfig> getActivityList(int pageNum, int pageSize, String activityName, Integer status) {
        IPage<ActivitySignInConfig> iPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<ActivitySignInConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(activityName)){
            lambdaQueryWrapper.like(ActivitySignInConfig::getActivityName, activityName);
        }
        if(status != null){
            lambdaQueryWrapper.eq(ActivitySignInConfig::getStatus, status);
        }
        lambdaQueryWrapper.eq(ActivitySignInConfig::getDeleteFlag, 0);
        lambdaQueryWrapper.eq(ActivitySignInConfig::getPlanConfigType, 2);
        return activitySignInConfigMapper.selectPage(iPage, lambdaQueryWrapper);
    }

    @Override
    public boolean updateActivityStatus(Integer id, Integer status) {
        if(id == null || status == null){
            return false;
        }
        ActivitySignInConfig activitySignInConfig = new ActivitySignInConfig();
        activitySignInConfig.setId(id);
        activitySignInConfig.setStatus(status);
        int result = activitySignInConfigMapper.updateById(activitySignInConfig);
        return result > 0;
    }

    @Override
    public void saveActivityRewards(Long activityId, List<ActivitySignInReward> rewards) {

    }

    @Override
    public boolean deleteActivity(Integer id) {
        if(id != null){
            // 删除活动信息
            int configResult = activitySignInConfigMapper.deleteById(id);
            if(configResult == 0){
                return false;
            }

            // 删除活动奖励信息
            LambdaQueryWrapper<ActivitySignInReward> activitySignInRewardWrapper = new LambdaQueryWrapper<>();
            activitySignInRewardWrapper.eq(ActivitySignInReward::getActivityId, id);
            activitySignRewardMapper.delete(activitySignInRewardWrapper);

            // 删除活动时间信息
            LambdaQueryWrapper<ActivityPeriod> activityPeriodLambdaQueryWrapper = new LambdaQueryWrapper<>();
            activityPeriodLambdaQueryWrapper.eq(ActivityPeriod::getActivityId, id);
            activityPeriodMapper.delete(activityPeriodLambdaQueryWrapper);
        }
        return true;
    }
}
