package com.ycwl.basic.repository;

import com.ycwl.basic.mapper.SourceMapper;
import com.ycwl.basic.model.pc.source.entity.MemberSourceEntity;
import com.ycwl.basic.model.pc.source.entity.SourceEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Component
public class SourceRepository {
    @Autowired
    private SourceMapper sourceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void addSource(SourceEntity source) {
        sourceMapper.add(source);
    }

    public void setUserIsBuyItem(Long memberId, int type, Long faceId, Long orderId) {
        MemberSourceEntity memberSource = new MemberSourceEntity();
        memberSource.setMemberId(memberId);
        memberSource.setFaceId(faceId);
        memberSource.setType(type);
        memberSource.setOrderId(orderId);
        memberSource.setIsBuy(1);
        sourceMapper.updateRelation(memberSource);
    }

    public void setUserNotBuyItem(Long memberId, int type, Long faceId) {
        MemberSourceEntity memberSource = new MemberSourceEntity();
        memberSource.setMemberId(memberId);
        memberSource.setFaceId(faceId);
        memberSource.setType(type);
        memberSource.setOrderId(null);
        memberSource.setIsBuy(0);
        sourceMapper.updateRelation(memberSource);
    }

    public boolean getUserIsBuy(Long userId, int type, Long faceId) {
        switch (type) {
            case 1:
                List<SourceEntity> videoSourceList = sourceMapper.listVideoByFaceRelation(userId, faceId);
                if (videoSourceList == null || videoSourceList.isEmpty()) {
                    return false;
                }
                return videoSourceList.stream().filter(Objects::nonNull).anyMatch(item -> Integer.valueOf(1).equals(item.getIsBuy()));
            case 2:
                List<SourceEntity> imageSourceList = sourceMapper.listImageByFaceRelation(userId, faceId);
                if (imageSourceList == null || imageSourceList.isEmpty()) {
                    return false;
                }
                return imageSourceList.stream().filter(Objects::nonNull).anyMatch(item -> Integer.valueOf(1).equals(item.getIsBuy()));
            default:
                return false;
        }
    }

    public SourceEntity getSource(Long id) {
        return sourceMapper.getEntity(id);
    }
}
