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

import java.util.List;

import com.ecep.contract.ds.vendor.model.PurchaseBillVoucherItem;
import com.ecep.contract.ds.vendor.model.PurchaseOrderItem;
import jakarta.persistence.criteria.Root;
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.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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.company.service.InvoiceService;
import com.ecep.contract.ds.contract.repository.PurchaseBillVoucherRepository;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.vendor.model.PurchaseBillVoucher;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.PurchaseBillVoucherVo;
import com.fasterxml.jackson.databind.JsonNode;

/**
 * 采购账单凭证服务
 */
@Lazy
@Service
@CacheConfig(cacheNames = "purchase-bill-voucher")
public class PurchaseBillVoucherService
        implements IEntityService<PurchaseBillVoucher>, QueryService<PurchaseBillVoucherVo>,
        VoableService<PurchaseBillVoucher, PurchaseBillVoucherVo> {
    private static final Logger logger = LoggerFactory.getLogger(PurchaseBillVoucherService.class);

    @Lazy
    @Autowired
    private PurchaseBillVoucherRepository repository;

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

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

    @Override
    public Specification<PurchaseBillVoucher> getSpecification(String searchText) {
        // if null
        if (!StringUtils.hasText(searchText)) {
            return null;
        }

        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("code"), "%" + searchText + "%"),
                    builder.like(root.get("description"), "%" + searchText + "%"));
        };
    }

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

    @Cacheable(key = "'refId-'+#p0")
    public PurchaseBillVoucherVo findByRefId(Integer refId) {
        return repository.findByRefId(refId).map(PurchaseBillVoucher::toVo).orElse(null);
    }

    public PurchaseBillVoucher getByRefId(Integer refId) {
        return repository.findByRefId(refId).orElse(null);
    }

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

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

    public long count() {
        return repository.count();
    }

    public long count(Specification<PurchaseBillVoucher> spec) {
        return repository.count(spec);
    }

    @Override
    public Page<PurchaseBillVoucher> findAll(Specification<PurchaseBillVoucher> spec, Pageable pageable) {
        return repository.findAll(spec, pageable);
    }

    @Override
    public Page<PurchaseBillVoucherVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<PurchaseBillVoucher> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "company", "inventory");
        if (paramsNode.has("purchaseOrder")) {
            spec = SpecificationUtils.and(spec, (root, query, cb) -> {
                Root<PurchaseBillVoucherItem> voucherItemRoot = query.from(PurchaseBillVoucherItem.class);
                Root<PurchaseOrderItem> orderItemRoot = query.from(PurchaseOrderItem.class);
                return cb.and(
                        cb.equal(voucherItemRoot.get("orderItem"), orderItemRoot),
                        cb.equal(orderItemRoot.get("order").get("id"), paramsNode.get("purchaseOrder").asInt()),
                        cb.equal(root, voucherItemRoot.get("voucher"))
                );
            });
        }
        return findAll(spec, pageable).map(PurchaseBillVoucher::toVo);
    }

    public List<PurchaseBillVoucher> findAll(Specification<PurchaseBillVoucher> spec, Sort sort) {
        return repository.findAll(spec, sort);
    }

    public List<PurchaseBillVoucher> search(String searchText) {
        return repository.findAll(getSpecification(searchText), Pageable.ofSize(10)).getContent();
    }

    @Override
    public void updateByVo(PurchaseBillVoucher model, PurchaseBillVoucherVo vo) {
        if (model == null || vo == null) {
            return;
        }

        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.getInvoiceId() == null) {
            model.setInvoice(null);
        } else {
            model.setInvoice(SpringApp.getBean(InvoiceService.class).getById(vo.getInvoiceId()));
        }

        if (vo.getCompanyId() == null) {
            model.setCompany(null);
        } else {
            model.setCompany(SpringApp.getBean(CompanyService.class).getById(vo.getCompanyId()));
        }

        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()));
        }
    }
}
