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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.SpringApp;
import com.ecep.contract.ds.company.service.InvoiceService;
import com.ecep.contract.ds.contract.model.ContractInvoice;
import com.ecep.contract.ds.contract.repository.ContractInvoiceRepository;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.ContractInvoiceVo;
import com.fasterxml.jackson.databind.JsonNode;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@CacheConfig(cacheNames = "contract-invoice")
public class ContractInvoiceService implements IEntityService<ContractInvoice>, QueryService<ContractInvoiceVo>,
        VoableService<ContractInvoice, ContractInvoiceVo> {

    @Autowired
    private ContractInvoiceRepository repository;

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

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

    /**
     * 根据合同ID查找发票列表
     *
     * @param contractId 合同ID
     * @return 发票VO列表
     */
    public List<ContractInvoiceVo> findByContractId(Integer contractId) {
        return repository.findByContractId(contractId)
                .stream()
                .map(ContractInvoice::toVo)
                .toList();
    }

    /**
     * 根据发票ID查找合同发票
     *
     * @param invoiceId 发票ID
     * @return 合同发票VO
     */
    public ContractInvoiceVo findByInvoiceId(Integer invoiceId) {
        return repository.findByInvoiceId(invoiceId)
                .map(ContractInvoice::toVo)
                .orElse(null);
    }

    /**
     * 保存发票
     *
     * @param invoice 发票实体
     * @return 保存后的发票VO
     */
    @Override
    public ContractInvoice save(ContractInvoice invoice) {
        try {
            ContractInvoice saved = repository.save(invoice);
            return saved;
        } catch (Exception e) {
            log.error("保存发票失败", e);
            throw new RuntimeException("保存发票失败", e);
        }
    }

    @Override
    public void updateByVo(ContractInvoice entity, ContractInvoiceVo vo) {
        if (entity == null || vo == null) {
            return;
        }

        entity.setCode(vo.getCode());
        entity.setName(vo.getName());
        entity.setAmount(vo.getAmount());
        entity.setRemark(vo.getRemark());

        // 处理关联实体 - 合同
        if (vo.getContractId() == null) {
            entity.setContract(null);
        } else {
            ContractService contractService = SpringApp.getBean(ContractService.class);
            if (entity.getContract() == null || !entity.getContract().getId().equals(vo.getContractId())) {
                entity.setContract(contractService.getById(vo.getContractId()));
            }
        }

        // 处理关联实体 - 发票
        if (vo.getInvoiceId() == null) {
            entity.setInvoice(null);
        } else {
            InvoiceService invoiceService = SpringApp.getBean(InvoiceService.class);
            if (entity.getInvoice() == null || !entity.getInvoice().getId().equals(vo.getInvoiceId())) {
                entity.setInvoice(invoiceService.getById(vo.getInvoiceId()));
            }
        }

        // 处理关联实体 - 发票
        EmployeeService personService = SpringApp.getBean(EmployeeService.class);
        if (vo.getSetupPersonId() == null) {
            entity.setSetupPerson(null);
        } else {
            if (entity.getSetupPerson() == null || !entity.getSetupPerson().getId().equals(vo.getSetupPersonId())) {
                entity.setSetupPerson(personService.getById(vo.getSetupPersonId()));
            }
        }
        if (vo.getUpdatePersonId() == null) {
            entity.setUpdatePerson(null);
        } else {
            if (entity.getUpdatePerson() == null || !entity.getUpdatePerson().getId().equals(vo.getUpdatePersonId())) {
                entity.setUpdatePerson(personService.getById(vo.getUpdatePersonId()));
            }
        }

    }

    @Override
    public Page<ContractInvoiceVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ContractInvoice> spec = buildParameterSpecification(paramsNode);
        Page<ContractInvoice> page = repository.findAll(spec, pageable);
        return page.map(ContractInvoice::toVo);
    }

    /**
     * 构建参数规范
     *
     * @param paramsNode 参数节点
     * @return 规范对象
     */
    protected Specification<ContractInvoice> buildParameterSpecification(JsonNode paramsNode) {
        Specification<ContractInvoice> spec = null;

        // 处理基本字段参数
        spec = SpecificationUtils.andFieldEqualParam(spec, paramsNode, "name", "code");

        // 处理关联实体参数
        spec = SpecificationUtils.andParam(spec, paramsNode, "contract", "invoice", "setupPerson", "updatePerson");

        // 处理搜索文本
        if (paramsNode.has("searchText")) {
            String searchText = paramsNode.get("searchText").asText();
            if (searchText != null && !searchText.isEmpty()) {
                spec = SpecificationUtils.and(spec, getSpecification(searchText));
            }
        }

        return spec;
    }

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

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

    @Override
    public Specification<ContractInvoice> getSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("name"), "%" + searchText + "%"),
                    builder.like(root.get("code"), "%" + searchText + "%"),
                    builder.like(root.get("remark"), "%" + searchText + "%"));
        };
    }

    @Override
    public void delete(ContractInvoice entity) {
        try {
            repository.delete(entity);
        } catch (Exception e) {
            log.error("删除合同发票失败", e);
            throw new RuntimeException("删除合同发票失败", e);
        }
    }
}