package com.ecep.contract.ds.contract.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.context.annotation.Lazy;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ecep.contract.EntityService;
import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.contract.repository.SalesOrderRepository;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.contract.model.Contract;
import com.ecep.contract.ds.customer.model.SalesOrder;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.SalesOrderVo;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 合同服务
 */
@Lazy
@Service
@CacheConfig(cacheNames = "contract-sale-order")
public class SaleOrdersService extends EntityService<SalesOrder, SalesOrderVo, Integer>
        implements IEntityService<SalesOrder>, QueryService<SalesOrderVo>, VoableService<SalesOrder, SalesOrderVo> {
    private static final Logger logger = LoggerFactory.getLogger(SaleOrdersService.class);

    @Lazy
    @Autowired
    private SalesOrderRepository repository;

    @Override
    protected SalesOrderRepository getRepository() {
        return repository;
    }

    @Override
    public SalesOrder createNewEntity() {
        return new SalesOrder();
    }

    @Override
    public SalesOrder getById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Cacheable(key = "#p0")
    public SalesOrderVo findById(Integer id) {
        return repository.findById(id).map(SalesOrder::toVo).orElse(null);
    }

    @Override
    protected Specification<SalesOrder> buildParameterSpecification(JsonNode paramsNode) {
        Specification<SalesOrder> spec = null;
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "code");
        spec = SpecificationUtils.andParam(spec, paramsNode, "contract", "employee", "maker", "verifier");
        return spec;
    }

    @Override
    protected Specification<SalesOrder> buildSearchSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("name"), "%" + searchText + "%"),
                    builder.like(root.get("code"), "%" + searchText + "%"));
        };
    }

    @Cacheable(key = "'code-'+#p0")
    public SalesOrderVo findByCode(String code) {
        return repository.findByCode(code).map(SalesOrder::toVo).orElse(null);
    }

    /**
     * 保存实体对象，异步方法
     *
     * @param order 要保存的实体对象
     * @return 返回异步调用
     */
    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.code")
    })
    public SalesOrder save(SalesOrder order) {
        return repository.save(order);
    }

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

    @Override
    public void updateByVo(SalesOrder model, SalesOrderVo vo) {
        // 更新基本属性
        model.setCode(vo.getCode());
        model.setMakerDate(vo.getMakerDate());
        model.setVerifierDate(vo.getVerifierDate());
        model.setDescription(vo.getDescription());

        // 处理关联对象
        if (vo.getContractId() == null) {
            model.setContract(null);
        } else {
            model.setContract(SpringApp.getBean(ContractService.class).getById(vo.getContractId()));
        }

        if (vo.getEmployeeId() == null) {
            model.setEmployee(null);
        } else {
            model.setEmployee(SpringApp.getBean(EmployeeService.class).getById(vo.getEmployeeId()));
        }

        if (vo.getMakerId() == null) {
            model.setMaker(null);
        } else {
            model.setMaker(SpringApp.getBean(EmployeeService.class).getById(vo.getMakerId()));
        }

        if (vo.getVerifierId() == null) {
            model.setVerifier(null);
        } else {
            model.setVerifier(SpringApp.getBean(EmployeeService.class).getById(vo.getVerifierId()));
        }

        // active字段在SalesOrder实体类中不存在，不需要设置
    }

    public List<SalesOrder> findAllByContract(Contract contract) {
        return repository.findAllByContract(contract);
    }
}
