package com.ecep.contract.service;

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.ContractInvoiceViewModel;
import com.ecep.contract.vo.ContractInvoiceVo;

@Service
@CacheConfig(cacheNames = "contract-invoice")
public class ContractInvoiceService extends QueryService<ContractInvoiceVo, ContractInvoiceViewModel> {

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.code")
    })
    public ContractInvoiceVo save(ContractInvoiceVo invoice) {
        return super.save(invoice);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.code")
    })
    public void delete(ContractInvoiceVo invoice) {
        super.delete(invoice);
    }

    @Cacheable(key = "'code-'+#p0")
    public ContractInvoiceVo findByCode(String code) {
        try {
            return async("findByCode", code, String.class).handle((response, ex) -> {
                if (ex != null) {
                    throw new RuntimeException("远程方法+findByCode+调用失败", ex);
                }
                if (response != null) {
                    return updateValue(createNewEntity(), response);
                }
                return null;
            }).get();
        } catch (Exception e) {
            throw new RuntimeException("查找合同发票 " + code + " 时发生错误", e);
        }
    }

    public ContractInvoiceVo findByContractId(Integer contractId) {
        try {
            return async("findByContractId", contractId, Integer.class).handle((response, ex) -> {
                if (response != null) {
                    return updateValue(createNewEntity(), response);
                }
                return null;
            }).get();
        } catch (Exception e) {
            throw new RuntimeException("查找合同ID为 " + contractId + " 的发票时发生错误", e);
        }
    }
}