package com.jsc.oscm.service;

import com.jsc.oscm.dao.RulesApiParserRepository;
import com.jsc.oscm.entity.RulesApiParser;
import com.jsc.oscm.model.ReturnT;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

@Service
public class RulesApiParserService {
    @Resource
    RulesApiParserRepository rulesApiParserRepository;

    public ReturnT<List<RulesApiParser>> getRulesApiParserList(RulesApiParser rulesApiParser, Integer index, Integer size) {
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        Example<RulesApiParser> rulesApiParserExample = Example.of(rulesApiParser, matcher);
        Pageable pageable = PageRequest.of(index, size);
        Page<RulesApiParser> rulesApiParserPage = rulesApiParserRepository.findAll(rulesApiParserExample, pageable);
        return new ReturnT<>(200, String.valueOf(rulesApiParserPage.getTotalElements()), rulesApiParserPage.getContent());
    }

    public ReturnT<RulesApiParser> getRulesApiParserById(Integer id) {
        Optional<RulesApiParser> rulesApiParserOptional = rulesApiParserRepository.findById(id);
        return rulesApiParserOptional.map(targetApi -> new ReturnT<>(200, "", targetApi)).orElseGet(() -> new ReturnT<>(500, "获取API信息失败", null));
    }

    public ReturnT<String> save(RulesApiParser rulesApiParser) {
        RulesApiParser saveRes = rulesApiParserRepository.save(rulesApiParser);
        if (ObjectUtils.isEmpty(saveRes) || StringUtils.isBlank(saveRes.getParserName())) {
            return new ReturnT<>(200, "failed", "");
        }
        return new ReturnT<>(200, "success", "");
    }

    public ReturnT<List<RulesApiParser>> getAllRulesApiParser() {
        return new ReturnT<>(200, "success", rulesApiParserRepository.findAll());
    }

    public ReturnT<String> delete(RulesApiParser rulesApiParser) {
        rulesApiParserRepository.delete(rulesApiParser);
        return new ReturnT<>(200, "success", "");
    }
}
