package com.ecep.contract.service;

import java.util.List;

import com.ecep.contract.converter.ContractTypeStringConverter;
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.ContractTypeViewModel;
import com.ecep.contract.vo.ContractTypeVo;

import javafx.util.StringConverter;

@Service
@CacheConfig(cacheNames = "contract-type")
public class ContractTypeService extends QueryService<ContractTypeVo, ContractTypeViewModel> {
    private final ContractTypeStringConverter stringConverter = new ContractTypeStringConverter(this);

    @Cacheable(key = "#p0")
    @Override
    public ContractTypeVo findById(Integer id) {
        return super.findById(id);
    }

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

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

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

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

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

    @Override
    public ContractTypeStringConverter getStringConverter() {
        return stringConverter;
    }
}
