package com.liquidnet.client.admin.zhengzai.sweet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.zhengzai.sweet.service.ISweetIntegralActivityService;
import com.liquidnet.client.admin.zhengzai.sweet.utils.SweetObjectAdminUtil;
import com.liquidnet.client.admin.zhengzai.sweet.utils.SweetRedisAdminUtils;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.sweet.dto.SweetIntegralActivityDto;
import com.liquidnet.service.sweet.dto.param.admin.SweetIntegralActivityFromParam;
import com.liquidnet.service.sweet.dto.param.admin.SweetIntegralActivityListSearchParam;
import com.liquidnet.service.sweet.dto.param.admin.SweetIntegralActivityPrizeFormParam;
import com.liquidnet.service.sweet.dto.vo.IntegralActivityVo;
import com.liquidnet.service.sweet.dto.vo.admin.SweetIntegralActivityPrizeVo;
import com.liquidnet.service.sweet.dto.vo.admin.SweetIntegralActivityVo;
import com.liquidnet.service.sweet.entity.SweetIntegralActivity;
import com.liquidnet.service.sweet.entity.SweetIntegralActivityDraw;
import com.liquidnet.service.sweet.entity.SweetIntegralActivityPrize;
import com.liquidnet.service.sweet.mapper.SweetIntegralActivityDrawMapper;
import com.liquidnet.service.sweet.mapper.SweetIntegralActivityMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.service.sweet.mapper.SweetIntegralActivityPrizeMapper;
import com.liquidnet.service.sweet.utils.SweetNewObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 积分活动表 服务实现类
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-10-20
 */
@Service
public class SweetIntegralActivityServiceImpl extends ServiceImpl<SweetIntegralActivityMapper, SweetIntegralActivity> implements ISweetIntegralActivityService {

    @Autowired
    SweetIntegralActivityMapper sweetIntegralActivityMapper;
    @Autowired
    SweetIntegralActivityPrizeMapper sweetIntegralActivityPrizeMapper;
    @Autowired
    SweetIntegralActivityDrawMapper sweetIntegralActivityDrawMapper;

    @Autowired
    private SweetRedisAdminUtils sweetRedisAdminUtils;

    @Override
    public Integer createForm(SweetIntegralActivityFromParam param) {
        try {
            SweetIntegralActivity sweetIntegralActivity = SweetIntegralActivityFromParam.getNew().copy(param);
            String integralActivityId = IDGenerator.nextSnowId();
            sweetIntegralActivity.setIntegralActivityId(integralActivityId);
            int insert = sweetIntegralActivityMapper.insert(sweetIntegralActivity);
            List<SweetIntegralActivityPrizeFormParam> prizeList = param.getPrizeList();
            if (!CollectionUtils.isEmpty(prizeList)) {
                for (SweetIntegralActivityPrizeFormParam prize : prizeList) {
                    if (prize.getPrizeType() == 2) {
                        prize.setPrizeTypeNum(10);
                    } else {
                        prize.setPrizeTypeNum(1);
                    }
                    SweetIntegralActivityPrize sweetIntegralActivityPrize = SweetIntegralActivityPrizeFormParam.getNew().copy(prize);
                    sweetIntegralActivityPrize.setPrizeId(IDGenerator.nextSnowId());
                    sweetIntegralActivityPrize.setIntegralActivityId(integralActivityId);
                    sweetIntegralActivityPrizeMapper.insert(sweetIntegralActivityPrize);
                    // 奖品库存和中奖人数redis
                    sweetRedisAdminUtils.incrIntegralActivityPrizeNum(integralActivityId, sweetIntegralActivityPrize.getPrizeId(), sweetIntegralActivityPrize.getPrizeNum());
                    sweetRedisAdminUtils.incrIntegralActivityPrizeWinnersNum(integralActivityId, sweetIntegralActivityPrize.getPrizeId(), sweetIntegralActivityPrize.getWinnersNum());
                }
            }
            // 活动redis处理
            this.integralActivityList(integralActivityId);
            return insert;
        } catch (Exception e) {
            log.error("创建活动失败 [e:{}]", e);
            return 0;
        }
    }

    @Override
    public Integer updateForm(SweetIntegralActivityFromParam param) {
        try {
            SweetIntegralActivity sweetIntegralActivity = SweetIntegralActivityFromParam.getNew().copy(param);
            sweetIntegralActivity.setUpdatedAt(LocalDateTime.now());
            String integralActivityId = param.getIntegralActivityId();
            int update = sweetIntegralActivityMapper.update(
                    sweetIntegralActivity,
                    Wrappers.lambdaUpdate(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIntegralActivityId, integralActivityId)
            );
            List<SweetIntegralActivityPrizeFormParam> prizeList = param.getPrizeList();
            if (!CollectionUtils.isEmpty(prizeList)) {
                for (SweetIntegralActivityPrizeFormParam prize : prizeList) {
                    SweetIntegralActivityPrize sweetIntegralActivityPrize = SweetIntegralActivityPrizeFormParam.getNew().copy(prize);
                    sweetIntegralActivityPrize.setUpdatedAt(LocalDateTime.now());
                    sweetIntegralActivityPrize.setIntegralActivityId(integralActivityId);
                    String prizeId = prize.getPrizeId();
                    if (prize.getPrizeType() == 2) {
                        sweetIntegralActivityPrize.setPrizeTypeNum(10);
                    } else {
                        sweetIntegralActivityPrize.setPrizeTypeNum(1);
                    }
                    // 处理奖品库存
                    SweetIntegralActivityPrize sweetIntegralActivityPrizeOld = sweetIntegralActivityPrizeMapper.selectOne(
                            Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getPrizeId, prizeId)
                    );
                    sweetIntegralActivityPrizeMapper.update(
                            sweetIntegralActivityPrize,
                            Wrappers.lambdaUpdate(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getPrizeId, prizeId)
                    );
                    Integer prizeNum = sweetIntegralActivityPrizeOld.getPrizeNum();
                    Integer winnersNum = sweetIntegralActivityPrizeOld.getWinnersNum();
                    Integer prizeNumNew = sweetIntegralActivityPrize.getPrizeNum();
                    Integer winnersNumNew = sweetIntegralActivityPrize.getWinnersNum();
                    int prizeNumDiff = prizeNumNew - prizeNum;
                    int winnersNumDiff = winnersNumNew - winnersNum;
                    if (prizeNumDiff > 0) {//增加库存
                        sweetRedisAdminUtils.incrIntegralActivityPrizeNum(integralActivityId, prizeId, prizeNumDiff);
                    } else if(prizeNumDiff < 0) {// 减少库存
                        sweetRedisAdminUtils.decrIntegralActivityPrizeNum(integralActivityId, prizeId, Math.abs(prizeNumDiff));
                    }
                    if (winnersNumDiff > 0) {//增加中奖人数
                        sweetRedisAdminUtils.incrIntegralActivityPrizeWinnersNum(integralActivityId, prizeId, winnersNumDiff);
                    } else if(winnersNumDiff < 0) {// 减少中奖人数
                        sweetRedisAdminUtils.decrIntegralActivityPrizeWinnersNum(integralActivityId, prizeId, Math.abs(winnersNumDiff));
                    }
                }
            }
            // 活动redis处理
            this.integralActivityList(integralActivityId);
            return update;
        } catch (Exception e) {
            log.error("编辑活动失败 [e:{}]", e);
            return 0;
        }
    }

    @Override
    public Integer isOnline(String integralActivityId, Integer isOnline) {
        SweetIntegralActivity sweetIntegralActivity = SweetIntegralActivity.getNew();
        sweetIntegralActivity.setIsOnline(isOnline);
        sweetIntegralActivity.setUpdatedAt(LocalDateTime.now());
        int update = sweetIntegralActivityMapper.update(
                sweetIntegralActivity,
                Wrappers.lambdaUpdate(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIntegralActivityId, integralActivityId)
        );
        // 活动redis处理
        this.integralActivityList(integralActivityId);
        return update;
    }

    @Override
    public SweetIntegralActivityVo detail(String integralActivityId) {
        SweetIntegralActivity sweetIntegralActivity = sweetIntegralActivityMapper.selectOne(
                Wrappers.lambdaQuery(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIntegralActivityId, integralActivityId)
        );
        SweetIntegralActivityVo integralActivityVo = SweetIntegralActivityVo.getNew().copy(sweetIntegralActivity);
        List<SweetIntegralActivityPrize> sweetIntegralActivityPrizes = sweetIntegralActivityPrizeMapper.selectList(
                Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getIntegralActivityId, integralActivityId)
        );
        if (!CollectionUtils.isEmpty(sweetIntegralActivityPrizes)) {
            List<SweetIntegralActivityPrizeVo> prizeVoList = SweetNewObjectUtil.getSweetIntegralActivityPrizeVoArrayList();
            for (SweetIntegralActivityPrize prize : sweetIntegralActivityPrizes) {
                SweetIntegralActivityPrizeVo sweetIntegralActivityPrizeVo = SweetIntegralActivityPrizeVo.getNew().copy(prize);
                // 已发出
                Integer winPrizeNum = sweetIntegralActivityDrawMapper.selectCount(
                        Wrappers.lambdaQuery(SweetIntegralActivityDraw.class).eq(SweetIntegralActivityDraw::getPrizeId, prize.getPrizeId())
                );
                sweetIntegralActivityPrizeVo.setWinPrizeNum(winPrizeNum);
                prizeVoList.add(sweetIntegralActivityPrizeVo);
            }
            integralActivityVo.setPrizeList(prizeVoList);
        }
        return integralActivityVo;
    }

    @Override
    public PageInfo<SweetIntegralActivityDto> list(SweetIntegralActivityListSearchParam listParam) {
        PageHelper.startPage(listParam.getPageNum(), listParam.getPageSize());
        List<SweetIntegralActivityDto> voList = sweetIntegralActivityMapper.searchActivityList(listParam.getActivityTitle());
        return new PageInfo(voList);
    }

    private void integralActivityList(String integralActivityId) {
        // 活动列表
        LambdaQueryWrapper<SweetIntegralActivity> queryWrapper = Wrappers.lambdaQuery(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIsOnline, 2);
        LocalDateTime now = LocalDateTime.now();
        queryWrapper.eq(SweetIntegralActivity::getTimeType, 1).or().eq(SweetIntegralActivity::getIsOnline, 2).eq(SweetIntegralActivity::getTimeType, 2).gt(SweetIntegralActivity::getEndTime, now).lt(SweetIntegralActivity::getStartTime, now);
        List<SweetIntegralActivity> sweetIntegralActivities = sweetIntegralActivityMapper.selectList(queryWrapper);
        List<IntegralActivityVo> voList = SweetObjectAdminUtil.getSweetIntegralActivityVoList();
        sweetIntegralActivities.forEach(r -> {
            IntegralActivityVo copy = IntegralActivityVo.getNew().copy(r);
            voList.add(copy);
        });
        sweetRedisAdminUtils.setIntegralActivityList(voList);
        // 活动详情
        SweetIntegralActivity sweetIntegralActivity = sweetIntegralActivityMapper.selectOne(
                Wrappers.lambdaQuery(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIntegralActivityId, integralActivityId)
        );
        IntegralActivityVo integralActivityVo = IntegralActivityVo.getNew().copy(sweetIntegralActivity);
        List<SweetIntegralActivityPrize> sweetIntegralActivityPrizes = sweetIntegralActivityPrizeMapper.selectList(
                Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getIntegralActivityId, integralActivityId)
        );
        integralActivityVo.setPrizeList(sweetIntegralActivityPrizes);
        sweetRedisAdminUtils.setIntegralActivityInfo(integralActivityVo);
    }

}
