package com.mcwl.memberCenter.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mcwl.common.constant.HttpStatus;
import com.mcwl.common.core.domain.R;
import com.mcwl.common.core.page.PageDomain;
import com.mcwl.common.core.page.TableDataInfo;
import com.mcwl.common.utils.SecurityUtils;
import com.mcwl.memberCenter.domain.Member;
import com.mcwl.memberCenter.domain.MemberPromotion;
import com.mcwl.memberCenter.domain.Promotion;
import com.mcwl.memberCenter.domain.dto.PromotionDto;
import com.mcwl.memberCenter.domain.vo.PromotionVo;
import com.mcwl.memberCenter.enums.PromotionEnum;
import com.mcwl.memberCenter.mapper.MemberPromotionMapper;
import com.mcwl.memberCenter.mapper.PromotionMapper;
import com.mcwl.memberCenter.service.MemberPromotionService;
import com.mcwl.memberCenter.service.MemberService;
import com.mcwl.memberCenter.service.PromotionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@RequiredArgsConstructor
public class PromotionServiceImpl extends ServiceImpl<PromotionMapper, Promotion> implements PromotionService {

    private final MemberPromotionService memberPromotionService;

    private final MemberService memberService;

    /**
     * 获取促销活动列表
     *
     * @return TableDataInfo
     */
    @Override
    public TableDataInfo getPromotionList(PageDomain pageDomain) {

        // 封装用户参加的促销活动, key为促销活动id, value为用户参加的促销活动
        Map<Long, MemberPromotion> map = new HashMap<>();

        // 获取用户参加的促销活动
        Long userId = SecurityUtils.getUserId();
        List<MemberPromotion> memberPromotionList = memberPromotionService.lambdaQuery()
                .eq(MemberPromotion::getUserId, userId)
                .eq(MemberPromotion::getStatus, PromotionEnum.PARTICIPATE)
                .list();
        for (MemberPromotion memberPromotion : memberPromotionList) {
            map.put(memberPromotion.getPromotionId(), memberPromotion);
        }

        // 查询促销活动列表
        Page<Promotion> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());

        LambdaQueryWrapper<Promotion> lqw = new LambdaQueryWrapper<>();
        lqw.gt(Promotion::getEndTime, new Date());

        baseMapper.selectPage(page, lqw);

        // 封装数据
        List<PromotionVo> promotionVoList = new ArrayList<>();
        page.getRecords().forEach(promotion -> {
            PromotionVo promotionVo = new PromotionVo();
            BeanUtil.copyProperties(promotion, promotionVo);
            if (map.containsKey(promotion.getId())) {
                promotionVo.setIsJoin(1);
            } else {
                promotionVo.setIsJoin(0);
            }
            promotionVoList.add(promotionVo);
        });

        // 封装分页结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(promotionVoList);
        rspData.setTotal(page.getTotal());

        return rspData;
    }

    /**
     * 获取用户参加的促销活动
     *
     * @param pageDomain 分页参数
     * @return TableDataInfo
     */
    @Override
    public TableDataInfo getMyPromotionList(PageDomain pageDomain) {

        // 获取当前用户
        Long userId = SecurityUtils.getUserId();


        List<Long> memberPromotionIds = new ArrayList<>();
        // 默认添加一个不存在的id, 防止List为空时in查询出错
        memberPromotionIds.add(-1L);

        // 查询用户参加的促销活动
        List<MemberPromotion> memberPromotionList = memberPromotionService.lambdaQuery()
                .eq(MemberPromotion::getUserId, userId)
                .eq(MemberPromotion::getStatus, PromotionEnum.PARTICIPATE)
                .list();
        for (MemberPromotion memberPromotion : memberPromotionList) {
            memberPromotionIds.add(memberPromotion.getPromotionId());
        }

        // 查询促销活动列表
        Page<Promotion> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());

        LambdaQueryWrapper<Promotion> lqw = new LambdaQueryWrapper<>();
        lqw.in(Promotion::getId, memberPromotionIds);
        baseMapper.selectPage(page, lqw);

        // 封装数据
        List<PromotionVo> promotionVoList = new ArrayList<>();
        page.getRecords().forEach(promotion -> {
            PromotionVo promotionVo = new PromotionVo();
            BeanUtil.copyProperties(promotion, promotionVo);
            promotionVoList.add(promotionVo);
        });


        // 封装分页结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(promotionVoList);
        rspData.setTotal(page.getTotal());

        return rspData;
    }


    /**
     * 用户参加促销活动
     *
     * @param promotionId 促销活动id
     * @return R
     */
    @Override
    public R<Object> joinPromotion(Long promotionId) {

        // 用户id
        Long userId = SecurityUtils.getUserId();

        // 按活动id查询活动信息
        Promotion promotion = baseMapper.selectById(promotionId);

        if (!Optional.ofNullable(promotion).isPresent()) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"活动不存在");
        }

        if (promotion.getStartTime().after(new Date())) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"活动未开始");
        }

        // 活动是否过期
        if (promotion.getEndTime().before(new Date())) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"活动已过期");
        }

        // 获取当前用户是否参与过该活动
        if (isJoinPromotion(userId, promotionId)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"您已参与过该活动");
        }

        // 是否在活动期间内订阅或续订会员
//        if (!isSubscribe(userId, promotion)) {
//            return AjaxResult.warn("请在活动期间内订阅或续期会员后参加该活动");
//        }

        Member member = memberService.getUseUserMemberByUserId(userId);
        String memberLevelId = Objects.isNull(member) ? "-1" : member.getMemberLevelId().toString();

        String memberLevelIds = promotion.getMemberLevelIds();
        if (!memberLevelIds.contains(memberLevelId)) {
            return R.fail(HttpStatus.SHOW_ERROR_MSG,"会员等级不够，无法参与该活动，请查看活动条件");
        }
        MemberPromotion memberPromotion = getMemberPromotion(userId, promotionId);
        memberPromotionService.save(memberPromotion);

        return R.ok();
    }

    /**
     * 更新促销活动
     */
//    @Override
//    public R<Object> updatePromotion(PromotionDto promotionDto) {
//
//        Date startTime = promotionDto.getStartTime();
//        Date endTime = promotionDto.getEndTime();
//        if (startTime.after(endTime)) {
//            return R.fail(HttpStatus.SHOW_ERROR_MSG,"活动开始时间不能大于结束时间");
//        }
//        Promotion promotion = new Promotion();
//
//        BeanUtil.copyProperties(promotionDto, promotion);
//        baseMapper.updateById(promotion);
//        return R.ok();
//    }

    private boolean isJoinPromotion(Long userId, Long promotionId) {
        MemberPromotion memberPromotion = memberPromotionService.lambdaQuery()
                .eq(MemberPromotion::getUserId, userId)
                .eq(MemberPromotion::getPromotionId, promotionId)
                .one();
        return memberPromotion != null;
    }

    private static MemberPromotion getMemberPromotion(Long userId, Long promotionId) {
        MemberPromotion memberPromotion = new MemberPromotion();
        memberPromotion.setUserId(userId);
        memberPromotion.setPromotionId(promotionId);
        memberPromotion.setStatus(PromotionEnum.PARTICIPATE);
        memberPromotion.setParticipationTime(new Date());
        return memberPromotion;
    }


}
