package com.yingpaipay.business.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yingpaipay.business.domain.FolderKeyword;
import com.yingpaipay.business.mapper.FolderKeywordMapper;
import com.yingpaipay.business.service.IFolderKeywordService;
import com.yingpaipay.common.mabatis.utils.WrapperUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class FolderKeywordServiceImpl implements IFolderKeywordService {

    private final FolderKeywordMapper baseMapper;

    @Override
    public boolean insertByFolderIdAndKeyewordIds(Long folderId, List<Long> keywords) {
        return baseMapper.insertBatch(
            keywords.stream().map(id -> {
                FolderKeyword e = new FolderKeyword();
                e.setFolderId(folderId);
                e.setKeywordId(id);
                return e;
            }).toList()
        );
    }

    @Override
    public List<FolderKeyword> getByFolderId(Long folderId) {
        return baseMapper.selectList(
            Wrappers.lambdaQuery(FolderKeyword.class)
                .eq(FolderKeyword::getFolderId, folderId)
        );
    }

    @Override
    public boolean updateByFolderId(List<Long> keywords, Long folderId) {
        boolean deleteFlag = baseMapper.delete(
            Wrappers.lambdaQuery(FolderKeyword.class)
                .eq(FolderKeyword::getFolderId, folderId)
        ) == 0;
        if (deleteFlag) {
            throw new RuntimeException("批量删除旧的失败");
        }
        return baseMapper.insertBatch(
            keywords.stream().map(id -> {
                FolderKeyword e = new FolderKeyword();
                e.setFolderId(folderId);
                e.setKeywordId(id);
                return e;
            }).toList()
        );
    }

    @Override
    public Long getByKeywordAndFolderIds(List<Long> selected, Long keyword) {
        return baseMapper.selectOne(
            Wrappers.lambdaQuery(FolderKeyword.class)
                .in(FolderKeyword::getFolderId, WrapperUtils.convertIds(selected))
                .eq(FolderKeyword::getKeywordId, keyword)
                .last("LIMIT 1")
        ).getFolderId();
    }

    @Override
    public boolean deleteByFolderIds(Collection<Long> folderIds) {
        if (folderIds.isEmpty()) {
            return true;
        }
        return baseMapper.delete(
            Wrappers.lambdaQuery(FolderKeyword.class)
                .in(FolderKeyword::getFolderId, folderIds)
        ) > 0;
    }
}
