package com.ecep.contract.service;

import java.util.List;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.ecep.contract.vm.ContractKindViewModel;
import com.ecep.contract.vo.ContractKindVo;

import javafx.util.StringConverter;

@Service
@CacheConfig(cacheNames = "contract-kind")
public class ContractKindService extends QueryService<ContractKindVo, ContractKindViewModel> {
    @Cacheable(key = "#p0")
    @Override
    public ContractKindVo findById(Integer id) {
        return super.findById(id);
    }

    public ContractKindVo findByName(String name) {
        try {
            return async("findByName", name, String.class).handle((response, ex) -> {
                ContractKindVo newEntity = createNewEntity();
                return updateValue(newEntity, response);
            }).get();
        } catch (Exception e) {
            throw new RuntimeException("查询实体失败" + name, e);
        }

    }

    public ContractKindVo findByCode(String code) {
        try {
            return async("findByCode", code, String.class).handle((response, ex) -> {
                if (ex != null) {
                    throw new RuntimeException("远程方法+findByCode+调用失败", ex);
                }
                ContractKindVo newEntity = createNewEntity();
                return updateValue(newEntity, response);
            }).get();
        } catch (Exception e) {
            throw new RuntimeException("查询实体失败" + code, e);
        }
    }

    @Cacheable(key = "'kinds'")
    @Override
    public List<ContractKindVo> findAll() {
        return super.findAll();
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"), @CacheEvict(key = "'kinds'"),
    })
    @Override
    public ContractKindVo save(ContractKindVo entity) {
        return super.save(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"), @CacheEvict(key = "'kinds'"),
    })
    @Override
    public void delete(ContractKindVo entity) {
        super.delete(entity);
    }

    @Override
    public StringConverter<ContractKindVo> getStringConverter() {
        return new StringConverter<ContractKindVo>() {
            @Override
            public String toString(ContractKindVo object) {
                return object.getCode() + " " + object.getName() + " " + object.getTitle();
            }

            @Override
            public ContractKindVo fromString(String string) {
                return findByCode(string);
            }
        };
    }

}