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 com.xxfc.platform.activity.mapper.ActivityPopupUserMapper;
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 javax.swing.plaf.synth.SynthEditorPaneUI;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
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;

    /**
     * 获取活动弹窗,根据是否登录
     *
     * @param userInfo
     * @return
     */
    public List<ActivityPopup> getActivityPopup(AppUserDTO userInfo) {
        if (userInfo != null) {
            List<ActivityPopup> activityPopups = getActivityPopupByTypes(loginTypes);
            if (activityPopups == null || activityPopups.size() == 0) {
                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<>();
            for (ActivityPopup activityPopup : activityPopups) {
                if (popupIdSet.add(activityPopup.getId())) {
                    result.add(activityPopup);
                }
            }
            return result;
        } else {

            return getActivityPopupByTypes(notLoginTypes);

        }

    }

    /**
     * 根据不同的用户,可查询寻的类型.得到对应的弹窗
     *
     * @param Types
     * @return
     */
    private List<ActivityPopup> getActivityPopupByTypes(String Types) {
        long timeMillis = System.currentTimeMillis();
        //获取有期限的弹窗timeType=1
        Example exa = Example.builder(ActivityPopup.class)
                .where(
                        WeekendSqls.<ActivityPopup>custom()
                                .andEqualTo(ActivityPopup::getTimeType, 1)
                                .andGreaterThanOrEqualTo(ActivityPopup::getEndTime, BigInteger.valueOf(timeMillis))
                                .andLessThanOrEqualTo(ActivityPopup::getStartTime, BigInteger.valueOf(timeMillis))
                                .andIn(ActivityPopup::getType, Arrays.asList(Types.split(",")))
                                .andEqualTo(ActivityPopup::getStatus, 1)
                                .andEqualTo(ActivityPopup::getIsDel, 0)

                ).orderByAsc("sort").build();
        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(Types.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.size() == 0) {
                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);
    }
}
