package com.corewing.app.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.dto.SubmitActivityRequest;
import com.corewing.app.entity.BizActivity;
import com.corewing.app.entity.BizActivityLottery;
import com.corewing.app.mapper.BizActivityLotteryMapper;
import com.corewing.app.service.BizActivityLotteryService;
import com.corewing.app.service.BizActivityService;
import com.corewing.app.util.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

@Service
public class BizActivityLotteryServiceImpl extends ServiceImpl<BizActivityLotteryMapper, BizActivityLottery> implements BizActivityLotteryService {

    @Resource
    private BizActivityService bizActivityService;

    @Override
    public Boolean submitActivity(SubmitActivityRequest submitActivityRequest) {

        Long userid = StpUtil.getLoginIdAsLong();

        BizActivity activity = bizActivityService.getById(submitActivityRequest.getActivityId());
        if(activity == null) {
            throw new RuntimeException("该活动不存在");
        }

        // 验证活动是否在有效期内
        if(activity.getStartTime() != null && activity.getEndTime() != null) {
            if(!DateUtils.isBefore(activity.getStartTime())) {
                throw new RuntimeException("活动还未开始");
            }

            if(!DateUtils.isAfter(activity.getEndTime())) {
                throw new RuntimeException("活动已过期");
            }
        }



        // 校验是否参与
        LambdaQueryWrapper<BizActivityLottery> checkLotteryWrapper = new LambdaQueryWrapper<>();
        checkLotteryWrapper.eq(BizActivityLottery::getUserId, userid);
        checkLotteryWrapper.eq(BizActivityLottery::getActivityId, submitActivityRequest.getActivityId());
        if(count(checkLotteryWrapper) > 0) {
            throw new RuntimeException("该活动你已经参与");
        }

        BizActivityLottery bizActivityLottery = new BizActivityLottery();
        bizActivityLottery.setActivityId(submitActivityRequest.getActivityId());


        return null;
    }
}
