package com.xxfc.platform.activity.biz;

import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.xxfc.platform.activity.entity.ActivityPopup;
import com.xxfc.platform.activity.entity.ActivityPopupUser;
import com.xxfc.platform.activity.mapper.ActivityPopupMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动弹窗biz
 *
 * @author Administrator
 */
@Service
public class ActivityPopupBiz extends BaseBiz<ActivityPopupMapper, ActivityPopup> {
    @Value("${activity.popup.loginTypes}")
    private String loginTypes;

    @Value("${activity.popup.notLoginTypes}")
    private String notLoginTypes;

    @Autowired
    private ActivityPopupUserBiz activityPopupUserBiz;

    @Autowired
    private ActivityPopularizeUserBiz activityPopularizeUserBiz;

    /**
     * 获取活动弹窗,根据是否登录
     *
     * @param userInfo
     * @return
     */
    public List<ActivityPopup> getActivityPopup(AppUserDTO userInfo) {
        if (userInfo != null) {
            List<ActivityPopup> activityPopups = getActivityPopupByTypes(loginTypes);
            if (activityPopups == null || activityPopups.isEmpty()) {
                return activityPopups;
            }
/*            List<Integer> collect = activityPopups.parallelStream().map(ActivityPopup::getId).collect(Collectors.toList());
            Example exaple = Example.builder(ActivityPopupUser.class)
                    .where(WeekendSqls.<ActivityPopupUser>custom()
                            .andEqualTo(ActivityPopupUser::getUserId, userInfo.getUserid())
                            .andIn(ActivityPopupUser::getPopupId, collect)
                    ).build();
            List<ActivityPopupUser> activityPopupUsers = activityPopupUserBiz.selectByExample(exaple);
            if (activityPopupUsers == null || activityPopupUsers.size() == 0) {
                return activityPopups;
            }
            Set<Integer> popupIdSet = activityPopupUsers.parallelStream().map(ActivityPopupUser::getPopupId).collect(Collectors.toSet());*/
            List<ActivityPopup> result = new ArrayList<>();
            List<Integer> activityIds = activityPopups.stream().map(ActivityPopup::getActivityId).collect(Collectors.toList());
            activityIds = CollectionUtils.isEmpty(activityIds)? Collections.EMPTY_LIST:activityIds;
            Map<Integer, Boolean> activityPopularizeUserMap = activityPopularizeUserBiz.getByUserIdAndPopularizeId(userInfo.getUserid(), activityIds);
            for (ActivityPopup activityPopup : activityPopups) {
                /*if (popupIdSet.add(activityPopup.getId())) {*/
                    boolean flag = activityPopularizeUserMap.isEmpty() ||
                            activityPopularizeUserMap.get(activityPopup.getActivityId()) == null ||
                            activityPopularizeUserMap.get(activityPopup.getActivityId()).equals(Boolean.FALSE);
                    if (flag) {
                        result.add(activityPopup);
                    }
//                }
            }

            return result;
        } else {

            return getActivityPopupByTypes(notLoginTypes);

        }

    }

    /**
     * 根据不同的用户,可查询寻的类型.得到对应的弹窗
     *
     * @param popupTypes
     * @return
     */
    private List<ActivityPopup> getActivityPopupByTypes(String popupTypes) {
        long timeMillis = System.currentTimeMillis();
        //获取有期限的弹窗timeType=1
        Example exa = new Example(ActivityPopup.class);
        Example.Criteria criteria = exa.createCriteria();
        exa.orderBy("sort").asc();
        criteria.andEqualTo("timeType",1);
        criteria.andIn("type",Arrays.asList(popupTypes.split(",")));
        criteria.andEqualTo("status",1);
        criteria.andEqualTo("isDel",0);
        criteria.andLessThanOrEqualTo("startTime",BigInteger.valueOf(timeMillis));
        criteria.andGreaterThanOrEqualTo("endTime",BigInteger.valueOf(timeMillis));

        List<ActivityPopup> activityPopups = mapper.selectByExample(exa);

        //获取永久的弹窗timeType=0
        Example permanentExa = Example.builder(ActivityPopup.class)
                .where(
                        WeekendSqls.<ActivityPopup>custom()
                                .andEqualTo(ActivityPopup::getTimeType, 0)
                                .andIn(ActivityPopup::getType, Arrays.asList(popupTypes.split(",")))
                                .andEqualTo(ActivityPopup::getStatus, 1)
                                .andEqualTo(ActivityPopup::getIsDel, 0)
                ).orderByAsc("sort").build();
        List<ActivityPopup> permanentActivityPopups = mapper.selectByExample(permanentExa);
        activityPopups.addAll(permanentActivityPopups);
        return activityPopups;
    }


    /**
     * 判断是否重复弹窗
     *
     * @param userInfo
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void setActivityPopup(AppUserDTO userInfo, Integer id) {
        if (userInfo != null) {
            Example exa = Example.builder(ActivityPopupUser.class).where(
                    WeekendSqls.<ActivityPopupUser>custom()
                            .andEqualTo(ActivityPopupUser::getPopupId, id)
                            .andEqualTo(ActivityPopupUser::getUserId, userInfo.getUserid())
            ).build();
            List<ActivityPopupUser> activityPopupUsers = activityPopupUserBiz.selectByExample(exa);
            if (activityPopupUsers == null || activityPopupUsers.isEmpty()) {
                ActivityPopupUser activityPopupUser = new ActivityPopupUser();
                activityPopupUser.setPopupId(id);
                activityPopupUser.setUserId(userInfo.getUserid());
                activityPopupUser.setCrtTime(BigInteger.valueOf(System.currentTimeMillis()));
                activityPopupUserBiz.insertSelective(activityPopupUser);
            }

        }

    }


    public void deleteOne(Integer id) {
        ActivityPopup activityPopup = selectById(id);
        if (activityPopup.getStatus() == 1) {
            throw new BaseException("Please take it off the shelves first");
        } else {
            activityPopup.setIsDel(1);
        }
    }

    @Override
    public int insertSelectiveRe(ActivityPopup activityPopup) {
        activityPopup.setCrtTime(BigInteger.valueOf(System.currentTimeMillis()));
        if (activityPopup.getSort() == null) {
            activityPopup.setSort(0);
        }
        if (activityPopup.getTimeType() == null) {
            activityPopup.setTimeType(0);
        }
        return mapper.insertSelective(activityPopup);
    }
}
