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

import com.ecep.contract.ds.customer.model.SalesOrder;
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.company.service.CompanyService;
import com.ecep.contract.ds.contract.repository.SalesBillVoucherRepository;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.customer.model.SalesBillVoucher;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.SalesBillVoucherVo;
import com.fasterxml.jackson.databind.JsonNode;

import java.util.List;

/**
 * 采购账单凭证服务
 */
@Lazy
@Service
@CacheConfig(cacheNames = "sales-bill-voucher")
public class SalesBillVoucherService extends EntityService<SalesBillVoucher, SalesBillVoucherVo, Integer>
        implements IEntityService<SalesBillVoucher>, QueryService<SalesBillVoucherVo>,
        VoableService<SalesBillVoucher, SalesBillVoucherVo> {
    private static final Logger logger = LoggerFactory.getLogger(SalesBillVoucherService.class);

    @Lazy
    @Autowired
    private SalesBillVoucherRepository salesBillVoucherRepository;

    @Override
    protected SalesBillVoucherRepository getRepository() {
        return salesBillVoucherRepository;
    }

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

    @Cacheable(key = "#p0")
    @Override
    public SalesBillVoucherVo findById(Integer id) {
        return salesBillVoucherRepository.findById(id).map(SalesBillVoucher::toVo).orElse(null);
    }

    @Override
    protected Specification<SalesBillVoucher> 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 SalesBillVoucherVo findByCode(String code) {
        return salesBillVoucherRepository.findByCode(code).map(SalesBillVoucher::toVo).orElse(null);
    }

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

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

    @Override
    protected Specification<SalesBillVoucher> buildParameterSpecification(JsonNode paramsNode) {
        Specification<SalesBillVoucher> spec = null;
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "refId");
        spec = SpecificationUtils.andParam(spec, paramsNode, "company", "order", "employee", "maker", "verifier");
        return spec;
    }

    @Override
    public void updateByVo(SalesBillVoucher model, SalesBillVoucherVo vo) {
        // 更新基本属性
        model.setRefId(vo.getRefId());
        model.setCode(vo.getCode());
        model.setMakerDate(vo.getMakerDate());
        model.setModifyDate(vo.getModifyDate());
        model.setVerifierDate(vo.getVerifierDate());
        model.setDescription(vo.getDescription());

        // 处理关联对象
        if (vo.getCompanyId() == null) {
            model.setCompany(null);
        } else {
            model.setCompany(SpringApp.getBean(CompanyService.class).getById(vo.getCompanyId()));
        }

        if (vo.getOrderId() == null) {
            model.setOrder(null);
        } else {
            model.setOrder(SpringApp.getBean(SaleOrdersService.class).getById(vo.getOrderId()));
        }

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

        if (vo.getMakerId() == null) {
            model.setMaker(null);
        } else {
            model.setMaker(employeeService.getById(vo.getMakerId()));
        }

        if (vo.getVerifierId() == null) {
            model.setVerifier(null);
        } else {
            model.setVerifier(employeeService.getById(vo.getVerifierId()));
        }
    }

    public List<SalesBillVoucher> findAllByOrder(SalesOrder order) {
        return salesBillVoucherRepository.findAllByOrder(order);
    }
}
