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.IntegralActivityPrizeRelationVo;
import com.liquidnet.service.sweet.dto.vo.IntegralActivityPrizeVo;
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.entity.SweetIntegralActivityPrizeRelation;
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.mapper.SweetIntegralActivityPrizeRelationMapper;
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.ArrayList;
import java.util.Arrays;
import java.util.List;

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

    @Autowired
    private SweetIntegralActivityMapper sweetIntegralActivityMapper;
    @Autowired
    private SweetIntegralActivityPrizeMapper sweetIntegralActivityPrizeMapper;
    @Autowired
    private SweetIntegralActivityDrawMapper sweetIntegralActivityDrawMapper;
    @Autowired
    private SweetIntegralActivityPrizeRelationMapper relationMapper;

    @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) {
                    SweetIntegralActivityPrize sweetIntegralActivityPrize = SweetIntegralActivityPrizeFormParam.getNew().copy(prize);
                    String prizeId = IDGenerator.nextSnowId();
                    sweetIntegralActivityPrize.setPrizeId(prizeId);
                    sweetIntegralActivityPrize.setIntegralActivityId(integralActivityId);
                    if (prize.getIsInfinite() == 2) {
                        sweetIntegralActivityPrize.setPrizeNum(0);
                    }
                    sweetIntegralActivityPrizeMapper.insert(sweetIntegralActivityPrize);
                    // 奖品库存
                    sweetRedisAdminUtils.incrIntegralActivityPrizeNum(integralActivityId, sweetIntegralActivityPrize.getPrizeId(), sweetIntegralActivityPrize.getPrizeNum());
                    // 预估人数
                    sweetRedisAdminUtils.incrIntegralActivityEstimatedNum(integralActivityId, sweetIntegralActivity.getEstimatedNum());
                }
            }
            // 活动redis处理
            this.integralActivityList(integralActivityId);
            return insert;
        } catch (Exception e) {
            log.error("创建活动失败 [e:{}]", e);
            return 0;
        }
    }

    @Override
    public Integer updateForm(SweetIntegralActivityFromParam param) {
        try {
            LocalDateTime nowTime = LocalDateTime.now();
            SweetIntegralActivity sweetIntegralActivity = SweetIntegralActivityFromParam.getNew().copy(param);
            sweetIntegralActivity.setUpdatedAt(nowTime);
            String integralActivityId = param.getIntegralActivityId();
            SweetIntegralActivity sweetIntegralActivityOld = sweetIntegralActivityMapper.selectOne(
                    Wrappers.lambdaQuery(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIntegralActivityId, integralActivityId)
            );
            int update = sweetIntegralActivityMapper.update(
                    sweetIntegralActivity,
                    Wrappers.lambdaUpdate(SweetIntegralActivity.class).eq(SweetIntegralActivity::getIntegralActivityId, integralActivityId)
            );

            Integer estimatedNum = sweetIntegralActivityOld.getEstimatedNum();
            Integer estimatedNumNew = sweetIntegralActivity.getEstimatedNum();
            int estimatedNumDiff = estimatedNumNew - estimatedNum;
            if (estimatedNumDiff > 0) {//增加
                sweetRedisAdminUtils.incrIntegralActivityEstimatedNum(integralActivityId, estimatedNumDiff);
            } else if(estimatedNumDiff < 0) {// 减少
                sweetRedisAdminUtils.decrIntegralActivityEstimatedNum(integralActivityId, Math.abs(estimatedNumDiff));
            }

            List<SweetIntegralActivityPrizeFormParam> prizeList = param.getPrizeList();
            if (!CollectionUtils.isEmpty(prizeList)) {
                for (SweetIntegralActivityPrizeFormParam prize : prizeList) {
                    SweetIntegralActivityPrize sweetIntegralActivityPrize = SweetIntegralActivityPrizeFormParam.getNew().copy(prize);
                    sweetIntegralActivityPrize.setUpdatedAt(nowTime);
                    String prizeId = prize.getPrizeId();
                    if (prize.getIsInfinite() == 2) {
                        sweetIntegralActivityPrize.setPrizeNum(0);
                        sweetRedisAdminUtils.delIntegralActivityPrizeNum(integralActivityId, prizeId);
                    } else {
                        // 处理奖品库存
                        SweetIntegralActivityPrize sweetIntegralActivityPrizeOld = sweetIntegralActivityPrizeMapper.selectOne(
                                Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getPrizeId, prizeId)
                        );
                        Integer prizeNum = sweetIntegralActivityPrizeOld.getPrizeNum();
                        Integer prizeNumNew = sweetIntegralActivityPrize.getPrizeNum();
                        int prizeNumDiff = prizeNumNew - prizeNum;
                        if (prizeNumDiff > 0) {//增加库存
                            sweetRedisAdminUtils.incrIntegralActivityPrizeNum(integralActivityId, prizeId, prizeNumDiff);
                        } else if(prizeNumDiff < 0) {// 减少库存
                            sweetRedisAdminUtils.decrIntegralActivityPrizeNum(integralActivityId, prizeId, Math.abs(prizeNumDiff));
                        }
                    }
                    sweetIntegralActivityPrizeMapper.update(
                            sweetIntegralActivityPrize,
                            Wrappers.lambdaUpdate(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getPrizeId, prizeId)
                    );
                }
            }
            // 活动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> activityPrizes = sweetIntegralActivityPrizeMapper.selectList(
                Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getIntegralActivityId, integralActivityId)
        );
        List<IntegralActivityPrizeVo> prizeList = SweetObjectAdminUtil.getSweetIntegralActivityPrizeVoList();
        activityPrizes.forEach(r -> {
            IntegralActivityPrizeVo copy = IntegralActivityPrizeVo.getNew().copy(r);
            // 奖品券列表
            List<SweetIntegralActivityPrizeRelation> prizeRelations = relationMapper.selectList(
                    Wrappers.lambdaQuery(SweetIntegralActivityPrizeRelation.class).eq(SweetIntegralActivityPrizeRelation::getPrizeId, copy.getPrizeId())
            );
            ArrayList<IntegralActivityPrizeRelationVo> prizeRelationVoList = SweetObjectAdminUtil.getSweetIntegralActivityPrizeRelationVoList();
            if (!CollectionUtils.isEmpty(prizeRelations)) {
                prizeRelations.forEach(rr -> {
                    IntegralActivityPrizeRelationVo copyR = IntegralActivityPrizeRelationVo.getNew().copy(rr);
                    prizeRelationVoList.add(copyR);
                });
            }
            copy.setPrizeRelationList(prizeRelationVoList);

            prizeList.add(copy);
        });
        integralActivityVo.setPrizeList(prizeList);
        // 详情奖品 积分和券
        List<SweetIntegralActivityPrize> activityPrizes1 = sweetIntegralActivityPrizeMapper.selectList(
                Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getIntegralActivityId, integralActivityId)
                        .in(SweetIntegralActivityPrize::getPrizeType, Arrays.asList(1,2))
        );
        List<IntegralActivityPrizeVo> prizeList1 = SweetObjectAdminUtil.getSweetIntegralActivityPrizeVoList();
        activityPrizes1.forEach(r -> {
            IntegralActivityPrizeVo copy = IntegralActivityPrizeVo.getNew().copy(r);
            // 奖品券列表
            List<SweetIntegralActivityPrizeRelation> prizeRelations = relationMapper.selectList(
                    Wrappers.lambdaQuery(SweetIntegralActivityPrizeRelation.class).eq(SweetIntegralActivityPrizeRelation::getPrizeId, copy.getPrizeId())
            );
            ArrayList<IntegralActivityPrizeRelationVo> prizeRelationVoList = SweetObjectAdminUtil.getSweetIntegralActivityPrizeRelationVoList();
            if (!CollectionUtils.isEmpty(prizeRelations)) {
                prizeRelations.forEach(rr -> {
                    IntegralActivityPrizeRelationVo copyR = IntegralActivityPrizeRelationVo.getNew().copy(rr);
                    prizeRelationVoList.add(copyR);
                });
            }
            copy.setPrizeRelationList(prizeRelationVoList);

            prizeList1.add(copy);
        });
        integralActivityVo.setPrizeList1(prizeList1);
        // 详情奖品 实物等
        List<SweetIntegralActivityPrize> activityPrizes2 = sweetIntegralActivityPrizeMapper.selectList(
                Wrappers.lambdaQuery(SweetIntegralActivityPrize.class).eq(SweetIntegralActivityPrize::getIntegralActivityId, integralActivityId)
                        .in(SweetIntegralActivityPrize::getPrizeType, Arrays.asList(3,4))
        );
        List<IntegralActivityPrizeVo> prizeList2 = SweetObjectAdminUtil.getSweetIntegralActivityPrizeVoList();
        int totalPrizeNum = 0;
        for (SweetIntegralActivityPrize prize : activityPrizes2) {
            IntegralActivityPrizeVo copy = IntegralActivityPrizeVo.getNew().copy(prize);
            prizeList2.add(copy);
            int prizeNum = sweetRedisAdminUtils.getIntegralActivityPrizeNum(integralActivityId, prize.getPrizeId());
            totalPrizeNum += prizeNum;
        }
        sweetRedisAdminUtils.setIntegralActivityTotalPrizeNum(integralActivityId, totalPrizeNum);

        integralActivityVo.setPrizeList2(prizeList2);

        sweetRedisAdminUtils.setIntegralActivityInfo(integralActivityVo);
    }

}
