package com.sonic.frog.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sonic.common.rpc.Page;
import com.sonic.daosupport.converter.PageConverter;
import com.sonic.frog.dao.GiftDictDao;
import com.sonic.frog.domain.entity.GiftDict;
import com.sonic.frog.domain.entity.HeartbeatLevelDict;
import com.sonic.frog.domain.input.GiftDictListInput;
import com.sonic.frog.domain.output.GiftDictListOutput;
import com.sonic.frog.enums.HeartbeatLevelEnum;
import com.sonic.frog.service.GiftDictService;
import com.sonic.frog.service.HeartbeatLevelDictService;
import com.sonic.frog.utils.BeanConver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 礼物字典业务实现类
 */
@Service
@Slf4j
public class GiftDictServiceImpl extends ServiceImpl<GiftDictDao, GiftDict> implements GiftDictService {

    @Autowired
    private HeartbeatLevelDictService heartbeatLevelDictService;

    @Override
    public Page<GiftDictListOutput> getGiftDictList(GiftDictListInput input) {
        //分页获取
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<GiftDict> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(input.getPage().getPn(), input.getPage().getPs());
        IPage<GiftDict> giftDictPage = page(page, Wrappers.<GiftDict>lambdaQuery()
                .eq(GiftDict::getIsDelete, false)
                .orderByAsc(GiftDict::getPrice,GiftDict::getSort)
        );
        List<GiftDict> records = page.getRecords();
        //心动等级map
        Set<HeartbeatLevelEnum> heartbeatLevelEnumSet = records.stream().filter(e -> e.getHeartbeatLevel() != null).map(GiftDict::getHeartbeatLevel).collect(Collectors.toSet());
        Map<HeartbeatLevelEnum, HeartbeatLevelDict> heartbeatLevelDictMap = heartbeatLevelDictService.mapByLevel(heartbeatLevelEnumSet);
        return PageConverter.convert(giftDictPage, giftDict -> {
            GiftDictListOutput output = BeanConver.copeBean(giftDict, GiftDictListOutput.class);
            //心动等级
            HeartbeatLevelEnum heartbeatLevel = giftDict.getHeartbeatLevel();
            if (heartbeatLevel != null) {
                HeartbeatLevelDict heartbeatLevelDict = heartbeatLevelDictMap.get(heartbeatLevel);
                //心动等级开始值
                output.setStartVal(heartbeatLevelDict != null ? heartbeatLevelDict.getStartVal() : null);
            }
            return output;
        });
    }
}