package com.jsc.oscm.service;

import com.jsc.oscm.dao.TargetApiRepository;
import com.jsc.oscm.entity.TargetApi;
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 TargetApiService {
    @Resource
    TargetApiRepository targetApiRepository;

    public ReturnT<List<TargetApi>> getTargetApiList(TargetApi targetApi, Integer index, Integer size) {
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        Example<TargetApi> targetApiExample = Example.of(targetApi, matcher);
        Pageable pageable = PageRequest.of(index, size);
        Page<TargetApi> targetApiPage = targetApiRepository.findAll(targetApiExample, pageable);
        return new ReturnT<>(200, String.valueOf(targetApiPage.getTotalElements()), targetApiPage.getContent());
    }

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

    public ReturnT<String> save(TargetApi targetApi) {
        TargetApi saveRes = targetApiRepository.save(targetApi);
        if (ObjectUtils.isEmpty(saveRes) || StringUtils.isBlank(saveRes.getTargetName())) {
            return new ReturnT<>(200, "failed", "");
        }
        return new ReturnT<>(200, "success", "");
    }

    public ReturnT<List<TargetApi>> getAllTargetApi() {
        return new ReturnT<>(200, "success", targetApiRepository.findAll());
    }

    public ReturnT<String> delete(TargetApi targetApi) {
        targetApiRepository.delete(targetApi);
        return new ReturnT<>(200, "success", "");
    }
}
