package com.izouma.nineth.service.rewardpoints;

import cn.hutool.core.text.CharSequenceUtil;
import com.izouma.nineth.domain.DrawLotteryHistory;
import com.izouma.nineth.dto.LotteryHistoryDTO;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.enums.rewardpoints.AwardDrawStatus;
import com.izouma.nineth.enums.rewardpoints.PointActivityAwardType;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.repo.rewardpoints.DrawLotteryHistoryRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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 javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户积分抽取记录
 */
@Slf4j
@Service
@AllArgsConstructor
public class DrawLotteryHistoryService {
    private final DrawLotteryHistoryRepo drawLotteryHistoryRepo;

    public void save(DrawLotteryHistory userPointDrawHistory) {
        drawLotteryHistoryRepo.save(userPointDrawHistory);
    }

    /**
     * 活动最近50个抽奖记录
     * @param activityId
     * @return
     */
    public List<DrawLotteryHistory> recent50History(Long activityId) {
        Pageable pageable = PageRequest.of(0, 50);
        List<DrawLotteryHistory> list =drawLotteryHistoryRepo.findByActivityIdLimit50(activityId,pageable);
        int length;
        for (DrawLotteryHistory drawLotteryHistory : list) {
            length = drawLotteryHistory.getUserName().length();
            if (length>6) {
                drawLotteryHistory.setUserName(CharSequenceUtil.hide(drawLotteryHistory.getUserName(), 2, 6));
            } else if (length>=4) {
                drawLotteryHistory.setUserName(CharSequenceUtil.hide(drawLotteryHistory.getUserName(), 1, 3));
            }else if (length>0) {
                drawLotteryHistory.setUserName(CharSequenceUtil.hide(drawLotteryHistory.getUserName(), 1, 2));
            }
        }
        return list;
    }

    /**
     * 历史抽奖记录
     * @param pageQuery
     * @param userId
     * @return
     */
    public Page<DrawLotteryHistory> awards(PageQuery pageQuery , Long userId) {
        if (userId != null) {
            pageQuery.getQuery().put("userId", userId);
        }
        Specification<DrawLotteryHistory> specification = JpaUtils.toSpecification(pageQuery, DrawLotteryHistory.class);
        PageRequest pageRequest = JpaUtils.toPageRequest(pageQuery);
        if (pageRequest.getSort().stream().noneMatch(order -> order.getProperty().equals("createdAt"))) {
            pageRequest = PageRequest.of(pageRequest.getPageNumber(), pageQuery.getSize(),
                    pageRequest.getSort().and(Sort.by("createdAt").descending()));
        }
        specification = specification.and((Specification<DrawLotteryHistory>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> and = new ArrayList<>();
            and.add(criteriaBuilder.notEqual(root.get("awardType"), Enum.valueOf(PointActivityAwardType.class, "EMPTY")));
            return criteriaBuilder.and(and.toArray(new Predicate[0]));
        });
        return drawLotteryHistoryRepo.findAll(specification,pageRequest);
    }

    /**
     * 更新发货状态
     * @param input
     * @return
     */
    @Transactional
    public DrawLotteryHistory updateReceiveAwards(LotteryHistoryDTO input) {
        DrawLotteryHistory history = drawLotteryHistoryRepo.findById(input.getId()).orElseThrow(new BusinessException("更改的发奖记录不存在"));
        history.setTrackingNumber(input.getTrackingNumber());
        history.setStatus(AwardDrawStatus.RECEIVED);
        drawLotteryHistoryRepo.save(history);
        return history;
    }


}
