package com.xindazhou.business.service.community.activity;

import com.xindazhou.business.controller.admin.community.activity.vo.ActivityPageReqVO;
import com.xindazhou.business.controller.admin.community.activity.vo.ActivityRespVO;
import com.xindazhou.business.controller.admin.community.activity.vo.ActivitySaveReqVO;
import com.xindazhou.business.convert.community.activity.ActivityConvert;
import com.xindazhou.business.dal.community.dataobject.activity.ActivityDO;
import com.xindazhou.business.dal.community.mysql.activity.ActivityMapper;
import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.framework.mybatis.core.query.LambdaQueryWrapperX;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;

import static com.xindazhou.framework.common.exception.enums.GlobalErrorCodeConstants.NOT_FOUND;

/**
 * 活动 Service 实现类
 *
 * @author xindazhou
 */
@Service("communityActivityServiceImpl")
@Validated
@Slf4j
public class ActivityServiceImpl implements ActivityService {

    @Resource
    private ActivityMapper activityMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createActivity(ActivitySaveReqVO createReqVO) {
        // 生成活动编号
        String activityId = "ACT" + System.currentTimeMillis();
        
        // 插入活动
        ActivityDO activity = ActivityConvert.INSTANCE.convert(createReqVO);
        activity.setActivityId(activityId);
        activity.setStatus(0); // 0-未开始
        activity.setRegisterCount(0);
        activity.setVirtualRegisterCount(0);
        
        // 根据时间计算状态
        updateActivityStatus(activity);
        
        activityMapper.insert(activity);
        return activity.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateActivity(ActivitySaveReqVO updateReqVO) {
        // 校验存在
        validateActivityExists(updateReqVO.getId());
        
        // 更新
        ActivityDO updateObj = ActivityConvert.INSTANCE.convert(updateReqVO);
        updateObj.setId(updateReqVO.getId());
        
        // 根据时间计算状态
        updateActivityStatus(updateObj);
        
        activityMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteActivity(Long id) {
        // 校验存在
        validateActivityExists(id);
        // 删除
        activityMapper.deleteById(id);
    }

    @Override
    public ActivityRespVO getActivity(Long id) {
        ActivityDO activity = validateActivityExists(id);
        return ActivityConvert.INSTANCE.convert(activity);
    }

    @Override
    public ActivityRespVO getActivityByActivityId(String activityId) {
        ActivityDO activity = activityMapper.selectOne(new LambdaQueryWrapperX<ActivityDO>()
                .eq(ActivityDO::getActivityId, activityId));
        if (activity == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "活动不存在");
        }
        return ActivityConvert.INSTANCE.convert(activity);
    }

    @Override
    public PageResult<ActivityRespVO> getActivityPage(ActivityPageReqVO pageReqVO) {
        LambdaQueryWrapperX<ActivityDO> queryWrapper = new LambdaQueryWrapperX<ActivityDO>()
                .likeIfPresent(ActivityDO::getName, pageReqVO.getKeyword())
                .eqIfPresent(ActivityDO::getStatus, pageReqVO.getStatus())
                .eqIfPresent(ActivityDO::getType, pageReqVO.getType())
                .betweenIfPresent(ActivityDO::getStartTime, pageReqVO.getStartTime())
                .betweenIfPresent(ActivityDO::getEndTime, pageReqVO.getEndTime())
                .orderByDesc(ActivityDO::getCreateTime);
        PageResult<ActivityDO> pageResult = activityMapper.selectPage(pageReqVO, queryWrapper);
        return ActivityConvert.INSTANCE.convertPage(pageResult);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setVirtualUsers(String activityId, Integer virtualCount) {
        ActivityDO activity = activityMapper.selectOne(new LambdaQueryWrapperX<ActivityDO>()
                .eq(ActivityDO::getActivityId, activityId));
        if (activity == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "活动不存在");
        }
        
        ActivityDO updateObj = new ActivityDO();
        updateObj.setId(activity.getId());
        updateObj.setVirtualRegisterCount(virtualCount);
        activityMapper.updateById(updateObj);
    }

    private ActivityDO validateActivityExists(Long id) {
        ActivityDO activity = activityMapper.selectById(id);
        if (activity == null) {
            throw ServiceExceptionUtil.exception(NOT_FOUND, "活动不存在");
        }
        return activity;
    }

    /**
     * 根据时间计算活动状态
     */
    private void updateActivityStatus(ActivityDO activity) {
        LocalDateTime now = LocalDateTime.now();
        if (activity.getStartTime() != null && activity.getEndTime() != null) {
            if (now.isBefore(activity.getStartTime())) {
                activity.setStatus(0); // 未开始
            } else if (now.isAfter(activity.getEndTime())) {
                activity.setStatus(2); // 已结束
            } else {
                activity.setStatus(1); // 进行中
            }
        }
    }

}

