package com.webchat.service.lottery;

import com.webchat.common.bean.APIPageResponseBean;
import com.webchat.common.constants.LotteryConstants;
import com.webchat.domain.vo.request.lottery.LotteryItemSaveVO;
import com.webchat.domain.vo.response.lottery.LotteryItemVO;
import com.webchat.repository.dao.lottery.ILotteryItemDAO;
import com.webchat.repository.entity.lottery.LotteryItemEntity;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 程序员七七
 * @webSite https://www.coderutil.com
 * @Date 2022/11/16 23:40
 * @description
 */
@Service
public class LotteryItemService {

    @Autowired
    private ILotteryItemDAO lotteryItemDAO;

    /**
     * 保存更新抽奖奖品
     *
     * @param lotteryItemSaveVO
     * @param userId
     * @return
     */
    public Long save(LotteryItemSaveVO lotteryItemSaveVO, String userId) {
        LotteryItemEntity lotteryItemEntity = this.convert(lotteryItemSaveVO, userId);
        long count = lotteryItemDAO.countByActivityIdAndSlot(lotteryItemSaveVO.getActivityId(), lotteryItemEntity.getSlot());
        Assert.isTrue(count == 0, "槽位已经设置了奖品！");
        return lotteryItemDAO.save(lotteryItemEntity).getId();
    }

    /**
     * 分页
     * @param activityId
     * @param name
     * @param slot
     * @param pageNo
     * @param pageSize
     * @return
     */
    public APIPageResponseBean<List<LotteryItemVO>> pageList(String activityId, String name, Integer slot, int pageNo, int pageSize) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Order.desc("id")));
        Specification<LotteryItemEntity> specification = ((root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(activityId)) {
                predicates.add(criteriaBuilder.equal(root.get("activityId").as(String.class), activityId));
            }
            if (StringUtils.isNotBlank(name)) {
                predicates.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + name + "%"));
            }
            if (slot != null) {
                predicates.add(criteriaBuilder.equal(root.get("slot").as(Integer.class), slot));
            }
            Predicate[] pre = new Predicate[predicates.size()];
            criteriaQuery.where(predicates.toArray(pre));
            return criteriaQuery.getRestriction();
        });
        Page<LotteryItemEntity> lotteryItemEntities = lotteryItemDAO.findAll(specification, pageable);
        if (CollectionUtils.isEmpty(lotteryItemEntities.getContent())) {
            return APIPageResponseBean.success(pageNo, pageSize, lotteryItemEntities.getTotalPages(), Collections.emptyList());
        }
        List<LotteryItemVO> lotteryItemVOList = lotteryItemEntities.getContent().stream().map(la -> {
            LotteryItemVO lotteryItemVO = new LotteryItemVO();
            lotteryItemVO.setId(la.getId());
            lotteryItemVO.setActivityId(la.getActivityId());
            lotteryItemVO.setCover(la.getCover());
            lotteryItemVO.setName(la.getName());
            lotteryItemVO.setType(la.getType());
            lotteryItemVO.setIcon(la.getIcon());
            lotteryItemVO.setCover(la.getCover());
            lotteryItemVO.setSlot(la.getSlot());
            lotteryItemVO.setStock(la.getStock());
            lotteryItemVO.setCreateTime(la.getCreateDate().getTime());
            return lotteryItemVO;
        }).collect(Collectors.toList());
        return APIPageResponseBean.success(pageNo, pageSize, lotteryItemEntities.getTotalElements(), lotteryItemVOList);
    }

    /**
     * 校验抽奖活动的奖品数量
     *
     * @param lotteryActivityId
     */
    public void validateLotteryItemCount(String lotteryActivityId) {
        Long count = countLotteryItem(lotteryActivityId);
        Assert.isTrue(LotteryConstants.LOTTERY_ITEM_COUNT == count, "活动奖品数量配置有误");
    }

    /**
     * 获取活动奖品数量
     *
     * @param lotteryActivityId
     * @return
     */
    public Long countLotteryItem(String lotteryActivityId) {
        Long count = lotteryItemDAO.countByActivityId(lotteryActivityId);
        return count == null ? 0L : count;
    }

    private LotteryItemEntity convert(LotteryItemSaveVO lotteryItemSaveVO, String userId) {
        Long id = lotteryItemSaveVO.getId();
        LotteryItemEntity entity;
        Date now = new Date();
        if (id != null) {
            entity = lotteryItemDAO.findById(id).orElse(null);
            Assert.isTrue(entity != null, "奖品信息更新失败:奖品不存在!");
        } else {
            entity = new LotteryItemEntity();
            entity.setActivityId(lotteryItemSaveVO.getActivityId());
            entity.setCreateBy(userId);
            entity.setCreateDate(now);
        }
        entity.setType(lotteryItemSaveVO.getType());
        entity.setName(lotteryItemSaveVO.getName());
        entity.setIcon(lotteryItemSaveVO.getIcon());
        entity.setCover(lotteryItemSaveVO.getCover());
        entity.setSlot(lotteryItemSaveVO.getSlot());
        entity.setStock(lotteryItemSaveVO.getStock());
        entity.setUpdateBy(userId);
        entity.setUpdateDate(now);
        return entity;
    }

}
