package com.ruoyi.brewery.service.impl;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.domain.WyBeerQrcodeScanLog;
import com.ruoyi.bar.service.IWyBarService;
import com.ruoyi.bar.service.IWyBeerQrcodeScanLogService;
import com.ruoyi.brewery.domain.*;
import com.ruoyi.brewery.service.*;
import com.ruoyi.common.constant.ActivityStageConstants;
import com.ruoyi.common.constant.RewardStatusConstants;
import com.ruoyi.common.utils.CodeGeneratorUtils;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.stereotype.Service;
import com.ruoyi.brewery.mapper.WyActivityMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 营销活动Service业务层处理
 *
 * @author kxl
 * @date 2024-12-21
 */
@Service
public class WyActivityServiceImpl implements IWyActivityService {
    @Resource
    private WyActivityMapper wyActivityMapper;
    @Resource
    private IWyActivityBeerService wyActivityBeerService;
    @Resource
    private IWyBeerService wyBeerService;
    @Resource
    private IWyGoodsService wyGoodsService;
    @Resource
    private IWyActivityRewardService wyActivityRewardService;
    @Resource
    private IWyBeerQrcodeScanLogService beerQrcodeScanLogService;
    @Resource
    private IWyBreweryService wyBreweryService;
    @Resource
    private IWyBarService barService;

    /**
     * 查询营销活动
     *
     * @param id 营销活动主键
     * @return 营销活动
     */
    @Override
    public WyActivity selectWyActivityById(Long id) {
        // 营销活动对象
        final WyActivity activity = wyActivityMapper.selectWyActivityById(id);
        // 奖品信息
        final WyActivityReward wyActivityReward = new WyActivityReward();
        wyActivityReward.setActivityId(id);
        // 奖品列表
        final List<WyActivityReward> wyActivityRewards = wyActivityRewardService.selectWyActivityRewardList(wyActivityReward);
        if (wyActivityRewards == null || wyActivityRewards.isEmpty()) {
            //剩余奖品数量
            activity.setRemainingBeerCount(activity.getActivityRewardCount());
            activity.setClaimCount(0);
        } else {
            // 剩余奖品数量
            activity.setRemainingBeerCount(activity.getActivityRewardCount() - wyActivityRewards.size());
            activity.setClaimCount(wyActivityRewards.size());
        }
        //招募活动
        if (activity.getActivityType() == 1) {
            final WyActivityBar bar = new WyActivityBar();
            bar.setActivityId(id);
            final List<WyActivityBar> wyActivityBars = wyActivityMapper.selectWyActivityBarList(bar);
            activity.setBarIds(wyActivityBars.stream().map(WyActivityBar::getBarId).collect(Collectors.toList()));
        }
        //酒品活动范围-无限制
        if (activity.getBeerScope() == 0) {
            final WyBeer wyBeer = new WyBeer();
            wyBeer.setBreweryId(activity.getBreweryId());
            wyBeer.setOnSale(1);
            HashMap<String, Object> params = new HashMap<>();
            params.put("pageNum", 1);
            params.put("pageSize", 5);
            wyBeer.setParams(params);
            final List<WyBeer> wyBeers = wyBeerService.selectWyBeerList(wyBeer);
            activity.setBeerIds(wyBeers.stream().map(WyBeer::getId).collect(Collectors.toList()));
            activity.setBeers(wyBeers);
        } else { //特定酒品
            final List<WyActivityBeer> wyActivityBeers = wyActivityBeerService.selectWyActivityBeerByActivityId(id);
            List<Long> beerIds = wyActivityBeers.stream().map(WyActivityBeer::getBeerId).collect(Collectors.toList());
            activity.setBeerIds(beerIds);
            if (beerIds.size() == 0) {
                activity.setBeers(null);
            } else {
                final List<WyBeer> wyBeers = wyBeerService.seleteWyBeerByIds(beerIds.toArray(new Long[0]));
                activity.setBeers(wyBeers);
            }
        }
        //奖品信息 1商品 2啤酒币
        if (activity.getActivityRewardType() == 1) {
            activity.setActivityRewardGoods(wyGoodsService.selectWyGoodsById(activity.getActivityRewardGoodsId()));
        }
        final WyBrewery wyBrewery = wyBreweryService.selectWyBreweryById(activity.getBreweryId());
        if (wyBrewery != null) {
            activity.setBreweryName(wyBrewery.getBrandName());
            activity.setBrandLogo(wyBrewery.getBrandLogo());
        }
        //处理活动状态
        if (activity.getStartDate().after(DateUtils.getNowDate())) {
            //活动未开始
            activity.setStage(ActivityStageConstants.STAGE_PREPARATION);
        } else {
            if (activity.getEndDate().before(DateUtils.getNowDate())) {
                //活动已结束
                activity.setStage(ActivityStageConstants.STAGE_COMPLETED);
            } else {
                if (activity.getEndDate().after(DateUtils.addDays(DateUtils.getNowDate(), activity.getDuration()))) {
                    //活动结算中
                    activity.setStage(ActivityStageConstants.STAGE_IN_SETTLEMENT);
                } else {
                    if (activity.getActivityStatus() == 1) {
                        //活动进行中
                        activity.setStage(ActivityStageConstants.STAGE_PROGRESS);
                    } else {
                        //活动暂停
                        activity.setStage(ActivityStageConstants.STAGE_STOPPED);
                    }
                }
            }
        }
        return activity;
    }

    /**
     * 更新活动热度
     *
     * @param activityId 活动ID
     * @return 操作结果
     */
    @Transactional
    @Override
    public int updateActivityPopularity(Long activityId) {
        final WyBeerQrcodeScanLog scanLog = new WyBeerQrcodeScanLog();
        scanLog.setActivityId(activityId);
        scanLog.setScanStatus(1);
        scanLog.setActivitySupplier(1);
        final Integer scanCount = beerQrcodeScanLogService.selectWyBeerQrcodeScanCount(scanLog);
        final WyActivity activity = this.selectWyActivityById(activityId);
        activity.setPopularity(scanCount.longValue());
        return this.updateWyActivity(activity);
    }

    /**
     * 查询营销活动列表
     *
     * @param wyActivity 营销活动
     * @return 营销活动
     */
    @Override
    public List<WyActivity> selectWyActivityList(WyActivity wyActivity) {
        return wyActivityMapper.selectWyActivityList(wyActivity);
    }

    @Override
    public List<WyActivity> selectWyActivityListWithData(WyActivity wyActivity) {
        final List<WyActivity> wyActivities = wyActivityMapper.selectWyActivityList(wyActivity);
        wyActivities.forEach(activity -> {
//            if (activity.getEndDate().before(DateUtils.getNowDate())) {
//                activity.setStage(ActivityStageConstants.STAGE_PROGRESS);
//            }else{
//                if (activity.getEndDate().before(DateUtils.addDays(DateUtils.getNowDate(), activity.getDuration()))) {
//                    activity.setStage(ActivityStageConstants.STAGE_IN_SETTLEMENT);
//                }else{
//                    activity.setStage(ActivityStageConstants.STAGE_COMPLETED);
//                }
//            }
            final WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
            wyBeerQrcodeScanLog.setActivityId(activity.getId());
            wyBeerQrcodeScanLog.setActivitySupplier(1);
            wyBeerQrcodeScanLog.setScanStatus(1);
            final Integer claimCount = beerQrcodeScanLogService.selectWyBeerQrcodeScanCount(wyBeerQrcodeScanLog);
            activity.setClaimCount(claimCount); // 核销总数

            final Integer barCount = beerQrcodeScanLogService.selectWyBeerQrcodeBarCount(wyBeerQrcodeScanLog);
            // 参与活动的酒吧数量
            activity.setJoinBarCount(barCount);

            final WyActivityReward wyActivityReward = new WyActivityReward();
            wyActivityReward.setActivityId(activity.getId());
            wyActivityReward.setRewardStatus(RewardStatusConstants.Waiting);
            final List<WyActivityReward> wyActivityRewards = wyActivityRewardService.selectWyActivityRewardList(wyActivityReward);
            activity.setWaitingClaimCount(wyActivityRewards.size()); // 待领取奖品数量

            wyActivityReward.setRewardStatus(RewardStatusConstants.Redeemed);
            final List<WyActivityReward> finishedRewards = wyActivityRewardService.selectWyActivityRewardList(wyActivityReward);
            activity.setFinishedClaimCount(finishedRewards.size()); // 已领取奖品数量

            final WyActivityBar bar = new WyActivityBar();
            bar.setActivityId(activity.getId());
            final List<WyActivityBar> wyActivityBars = this.selectWyActivityBarList(bar);
            if (wyActivityBars == null || wyActivityBars.size() == 0) {
                activity.setBarIds(null);
            } else {
                activity.setBarIds(wyActivityBars.stream().map(WyActivityBar::getBarId).collect(Collectors.toList()));
                final WyBar wyBar = barService.selectWyBarById(wyActivityBars.get(0).getBarId());
                if (wyBar != null) {
                    activity.setBarNumber(wyBar.getBarNumber());
                }
            }
        });
        return wyActivities;
    }

    /**
     * 品牌活动数据统计
     *
     * @param breweryId 品牌ID
     * @return 品牌活动数据统计
     */
    @Override
    public HashMap<String, Integer> selectActivityDataByBreweryId(Long breweryId) {
        final WyActivity wyActivity = new WyActivity();
        wyActivity.setBreweryId(breweryId);
        final Integer allCount = this.selectActivityCount(wyActivity);

        wyActivity.setActivityType(1);//定向活动
        final Integer qualifiedCount = this.selectActivityCount(wyActivity);

        wyActivity.setActivityType(2);//公开活动
        final Integer publicCount = this.selectActivityCount(wyActivity);

        final WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setBreweryId(breweryId);
        final Integer barCount = beerQrcodeScanLogService.selectWyBeerQrcodeBarCount(wyBeerQrcodeScanLog);

        WyActivityReward wyActivityReward = new WyActivityReward();
        wyActivityReward.setBreweryId(breweryId);
        wyActivityReward.setRewardStatus(RewardStatusConstants.Waiting);
        final List<WyActivityReward> wyActivityRewards = wyActivityRewardService.selectWyActivityRewardList(wyActivityReward);

        wyActivityReward.setRewardStatus(RewardStatusConstants.Redeemed);
        final List<WyActivityReward> redeemedRewards = wyActivityRewardService.selectWyActivityRewardList(wyActivityReward);

        return new HashMap<String, Integer>() {
            {
                put("allCount", allCount);
                put("qualifiedCount", qualifiedCount);
                put("publicCount", publicCount);
                put("barCount", barCount);
                put("waitingClaimCount", wyActivityRewards.size());
                put("redeemedCount", redeemedRewards.size());
            }
        };
    }

    /**
     * 数据统计
     */
    @Override
    public Integer selectActivityCount(WyActivity wyActivity) {
        return wyActivityMapper.selectActivityCount(wyActivity);
    }

    @Override
    public List<WyActivity> selectWyActivityListWithBeer(WyActivity wyActivity) {
        // 创建空活动集合
        List<WyActivity> activities = new ArrayList<>();
        // 获取所有活动
        final List<WyActivity> wyActivities = wyActivityMapper.selectWyActivityList(wyActivity);
        wyActivities.forEach(activity -> {
            //遍历添加其他元素
            activities.add(this.selectWyActivityById(activity.getId()));
        });
        return activities;
    }

    /**
     * 显示公开活动和跟本店有关的定向活动
     */
    @Override
    public List<WyActivity> selectWyActivityListWithBeerAndBar(WyActivity wyActivity, Long barId) {
        final WyBar wyBar = barService.selectWyBarById(barId);
        List<WyActivity> activities = new ArrayList<>();
        final List<WyActivity> wyActivities = wyActivityMapper.selectWyActivityList(wyActivity);
        wyActivities.forEach(activity -> {
            if (activity.getActivityType() == 0) {
                activities.add(this.selectWyActivityById(activity.getId()));
            } else {
                if (activity.getBarIds() == null || activity.getBarIds().isEmpty()) {
                    activities.add(this.selectWyActivityById(activity.getId()));
                } else {
                    if (wyBar != null && activity.getBarIds().contains(wyBar.getId())) {
                        activities.add(this.selectWyActivityById(activity.getId()));
                    }
                }
            }
        });
        return activities;
    }

    @Override
    public List<WyActivity> selectFavoritedWyActivityList(WyActivityFavorite wyActivityFavorite) {
        List<WyActivity> activities = new ArrayList<>();
        final List<WyActivity> wyActivities = wyActivityMapper.selectFavoritedWyActivityList(wyActivityFavorite);
        wyActivities.forEach(activity -> {
            activities.add(this.selectWyActivityById(activity.getId()));
        });
        return activities;
    }

    /**
     * 新增营销活动
     *
     * @param wyActivity 营销活动
     * @return 结果
     */
    @Transactional
    @Override
    public int insertWyActivity(WyActivity wyActivity) {
        final WyBrewery wyBrewery = wyBreweryService.selectWyBreweryById(wyActivity.getBreweryId());
        final WyActivity activityQuery = new WyActivity();
//        wyActivity.setActivityName("ZDA"+DateUtils.dateTimeNow());
        wyActivity.setActivityName(generateSn()); //活动名称为编号
        activityQuery.setBreweryId(wyActivity.getBreweryId());
        activityQuery.setActivityStatus(1);
        final List<WyActivity> wyActivities = this.selectWyActivityList(activityQuery);
        //TODO 读取配置再设置每家酒厂能发布的活动数量
        Integer brandActivityCount = wyBrewery.getActivityNum(); // 每家酒厂能发布的活动数量
        if (brandActivityCount == null || brandActivityCount <= 0) {
            brandActivityCount = 3;
        }
        if (wyActivities.size() >= brandActivityCount) {
            throw new RuntimeException("每家酒吧最多只能同时发布" + brandActivityCount + "个有效的活动");
        }
        if (wyActivity.getActivityType() != 1 && wyActivity.getActivityType() != 2) {
            throw new RuntimeException("活动类型只能为【1定向】或【2招募】");
        }
        if (wyActivity.getActivityType() == 1) {
            wyActivity.setBarIds(null);
//            if (wyActivity.getBarIds() == null || wyActivity.getBarIds().size() == 0) {
////                throw new RuntimeException("定向活动，必须选择一个或多个酒吧");
//                throw new RuntimeException("定向活动，必须选择酒吧");
//            } else {
//                final List<Long> barIds = wyActivity.getBarIds();
//                wyActivity.setBarIds(barIds.stream().distinct().collect(Collectors.toList()));
//            }
            if (wyActivity.getBarNumber() == null || wyActivity.getBarNumber().equals("")) {
                throw new RuntimeException("定向活动，必须选择酒吧");
            } else {
                final WyBar wyBar = barService.selectWyBarByNumber(wyActivity.getBarNumber().trim());
                if (wyBar == null) {
                    throw new RuntimeException("选择的酒吧不存在");
                }
                wyActivity.setBarIds(new ArrayList<Long>() {{
                    add(wyBar.getId());
                }});
            }
        }
        //招募活动
        if (wyActivity.getActivityType() == 2) {
            if (wyActivity.getCity() == null) {
                throw new RuntimeException("招募活动，城市不能为空");
            }
            if (wyActivity.getDuration() == null || wyActivity.getDuration() <= 0) {
                throw new RuntimeException("招募活动，招募时长不能为空");
            }
            if (wyActivity.getDuration() > 31) {
                throw new RuntimeException("招募活动，招募时长不能超过31天");
            }
            activityQuery.setCity(wyActivity.getCity());
            final List<WyActivity> cityActivities = this.selectWyActivityList(activityQuery);
            if (cityActivities.size() != 0) {
                throw new RuntimeException("当前地区已有活动，不能再发布招募活动");
            }
        }
        if (wyActivity.getBeerScope() == 1) {
            if (wyActivity.getBeerIds() == null || wyActivity.getBeerIds().size() == 0) {
                throw new RuntimeException("特定商品活动，商品不能为空");
            }
        }
        if (wyActivity.getActivityRewardType() == 1) {
            if (wyActivity.getActivityRewardGoodsId() == null) {
                throw new RuntimeException("奖品类型为商品时，奖品ID不能为空");
            }
        }
        if (wyActivity.getActivityRewardCount() == null || wyActivity.getActivityRewardCount() <= 0) {
            throw new RuntimeException("奖品数量不能为空");
        }
        if (wyActivity.getBeerScope() == 1 && wyActivity.getBeerIds() == null) {
            throw new RuntimeException("请选择啤酒");
        }
        if (wyActivity.getBeerScope() == 0) {
            wyActivity.setBeerIds(null);
        }
        wyActivity.setCreateTime(DateUtils.getNowDate());
        wyActivityMapper.insertWyActivity(wyActivity);
        if (wyActivity.getActivityType() == 1 && wyActivity.getId() != null) {
            wyActivity.getBarIds().forEach(barId -> {
                final WyBar wyBar = barService.selectWyBarById(barId);
                if (wyBar == null) {
                    throw new RuntimeException("选择的酒吧不存在:" + barId);
                }
                wyActivityMapper.insertWyActivityBar(new WyActivityBar(wyActivity.getId(), barId));
            });
        }
        if (wyActivity.getBeerIds() != null) {
            wyActivity.getBeerIds().forEach(beerId -> {
                WyActivityBeer activityBeer = new WyActivityBeer();
                activityBeer.setActivityId(wyActivity.getId());
                activityBeer.setBeerId(beerId);
                wyActivityBeerService.insertWyActivityBeer(activityBeer);
            });
        }
        return 1;
    }

    /**
     * 修改营销活动
     *
     * @param wyActivity 营销活动
     * @return 结果
     */
    @Transactional
    @Override
    public int updateWyActivity(WyActivity wyActivity) {
        wyActivity.setActivityName(null); //活动名称不允许修改
        WyActivityBeer wyActivityBeer = new WyActivityBeer();
        wyActivityBeer.setActivityId(wyActivity.getId());
        List<WyActivityBeer> wyActivityBeers = wyActivityBeerService.selectWyActivityBeerByActivityId(wyActivity.getId());
        if (wyActivity.getBeerScope() == 1 && wyActivity.getBeerIds() == null && wyActivityBeers == null) {
            throw new RuntimeException("请选择啤酒");
        }
        wyActivity.setUpdateTime(DateUtils.getNowDate());
        wyActivityMapper.updateWyActivity(wyActivity);
        wyActivityBeerService.deleteWyActivityBeerByActivityId(wyActivity.getId());
        if (wyActivity.getBeerIds() != null) {
            wyActivity.getBeerIds().forEach(beerId -> {
                WyActivityBeer activityBeer = new WyActivityBeer();
                activityBeer.setActivityId(wyActivity.getId());
                activityBeer.setBeerId(beerId);
                wyActivityBeerService.insertWyActivityBeer(activityBeer);
            });
        }
        return 1;
    }

    /**
     * 批量删除营销活动
     *
     * @param ids 需要删除的营销活动主键
     * @return 结果
     */
    @Override
    public int deleteWyActivityByIds(Long[] ids) {
        return wyActivityMapper.deleteWyActivityByIds(ids);
    }

    /**
     * 删除营销活动信息
     *
     * @param id 营销活动主键
     * @return 结果
     */
    @Override
    public int deleteWyActivityById(Long id) {
        return wyActivityMapper.deleteWyActivityById(id);
    }

    @Override
    public List<WyActivityBar> selectWyActivityBarList(WyActivityBar bar) {
        return wyActivityMapper.selectWyActivityBarList(bar);
    }

    @Override
    public int insertWyActivityBar(WyActivityBar bar) {
        return wyActivityMapper.insertWyActivityBar(bar);
    }

    @Override
    public WyActivityBar selectWyActivityBar(WyActivityBar bar) {
        return wyActivityMapper.selectWyActivityBar(bar);
    }

    @Transactional
    @Override
    public int deleteWyActivityBarByActivityId(Long activityId) {
        wyActivityBeerService.deleteWyActivityBeerByActivityId(activityId); //删除所有老的关联关系
        return wyActivityMapper.deleteWyActivityBarByActivityId(activityId);
    }

    @Override
    public int deleteWyActivityBarByBarId(Long barId) {
        return wyActivityMapper.deleteWyActivityBarByBarId(barId);
    }

    /**
     * 生成编号
     */
    private String generateSn() {
        final Integer integer = wyActivityMapper.selectActivityCount(new WyActivity());
        String sn = CodeGeneratorUtils.generateActivityCode(integer);
        //生成订单号
        final WyActivity query = new WyActivity();
        query.setActivityName(sn);
        final Integer data = selectActivityCount(query);
        if (data > 0) {
            return generateSn();
        }
        return sn;
    }

//    public static void main(String[] args) throws ParseException {
//        final Date date = DateUtils.parseDate("2025-03-18 00:00:00", "yyyy-MM-dd HH:mm:ss");
//        final Date when = DateUtils.addDays(DateUtils.getNowDate(), 6);
//        System.out.println(when);
//        final boolean before = date.before(when);
//        System.out.println(before);
//    }
}
