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

import java.util.List;

import com.ecep.contract.ds.contract.service.ContractService;
import com.ecep.contract.ds.other.service.EmployeeService;
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.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.constant.ServiceConstant;
import com.ecep.contract.ds.project.repository.ProjectCostRepository;
import com.ecep.contract.ds.project.model.Project;
import com.ecep.contract.ds.project.model.ProjectCost;
import com.ecep.contract.ds.project.model.ProjectCostItem;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.ProjectCostVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "project-cost")
public class ProjectCostService implements IEntityService<ProjectCost>, QueryService<ProjectCostVo>,
        VoableService<ProjectCost, ProjectCostVo> {
    @Lazy
    @Autowired
    private ProjectCostRepository repository;

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

    @Cacheable(key = "#p0")
    @Override
    public ProjectCostVo findById(Integer id) {
        ProjectCost cost = getById(id);
        if (cost != null) {
            return cost.toVo();
        }
        return null;
    }

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

    @Override
    public Page<ProjectCostVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ProjectCost> spec = null;
        if (paramsNode.has(ServiceConstant.KEY_SEARCH_TEXT)) {
            spec = getSpecification(paramsNode.get(ServiceConstant.KEY_SEARCH_TEXT).asText());
        }

        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "project");

        if (paramsNode.has("project.customer")) {
            Integer customerId = paramsNode.get("project.customer").asInt();
            spec = SpecificationUtils.and(spec, (root, query, builder) -> {
                return builder.equal(root.get("project").get("customer").get("id"), customerId);
            });
        }
        Page<ProjectCost> page = findAll(spec, pageable);
        return page.map(ProjectCost::toVo);
    }

    @Override
    public Specification<ProjectCost> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("code"), "%" + searchText + "%"),
                    builder.like(root.get("name"), "%" + searchText + "%"));
        };
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
    })
    public ProjectCost save(ProjectCost cost) {
        return repository.save(cost);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
    })
    public void delete(ProjectCost cost) {
        repository.delete(cost);
    }

    public List<ProjectCost> findByProject(Project project) {
        return repository.findAllByProject(project);
    }

    public void calculateTotalAmount(ProjectCost cost) {
        List<ProjectCostItem> items = SpringApp.getBean(ProjectCostItemService.class).findByCostId(cost.getId());
        double totalOutAmount = 0;
        double totalInAmount = 0;
        for (ProjectCostItem item : items) {
            totalInAmount += item.getInExclusiveTaxPrice() != 0 ? item.getInQuantity() : 0;
            totalOutAmount += item.getOutExclusiveTaxPrice() != 0 ? item.getOutQuantity() : 0;
        }
        // ProjectCost类中没有totalAmount属性，使用现有属性存储计算结果
        cost.setOutExclusiveTaxAmount(totalOutAmount);
        cost.setInExclusiveTaxAmount(totalInAmount);
        save(cost);
    }

    @Override
    public void updateByVo(ProjectCost model, ProjectCostVo vo) {
        // 根据ProjectCostVo的实际属性更新ProjectCost
        model.setVersion(vo.getVersion());
        model.setStandardPayWay(vo.isStandardPayWay());
        model.setNoStandardPayWayText(vo.getNoStandardPayWayText());
        model.setStandardContractText(vo.isStandardContractText());
        model.setNoStandardContractText(vo.getNoStandardContractText());
        model.setStampTax(vo.getStampTax());
        model.setStampTaxFee(vo.getStampTaxFee());
        model.setOnSiteServiceFee(vo.getOnSiteServiceFee());
        model.setAssemblyServiceFee(vo.getAssemblyServiceFee());
        model.setTechnicalServiceFee(vo.getTechnicalServiceFee());
        model.setBidServiceFee(vo.getBidServiceFee());
        model.setFreightCost(vo.getFreightCost());
        model.setGuaranteeLetterFee(vo.getGuaranteeLetterFee());
        model.setTaxAndSurcharges(vo.getTaxAndSurcharges());
        model.setTaxAndSurchargesFee(vo.getTaxAndSurchargesFee());
        model.setDescription(vo.getDescription());
        model.setImportLock(vo.isImportLock());

        if (vo.getProject() == null) {
            model.setProject(null);
        } else {
            Project project = SpringApp.getBean(ProjectService.class).getById(vo.getProject());
            model.setProject(project);
        }

        if (vo.getContractId() == null) {
            model.setContract(null);
        } else {
            model.setContract(SpringApp.getBean(ContractService.class).getById(vo.getContractId()));
        }

        if (vo.getApplicantId() == null) {
            model.setAuthorizer(null);
        } else {
            model.setApplicant(SpringApp.getBean(EmployeeService.class).getById(vo.getApplicantId()));
        }

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

        model.setApplyTime(vo.getApplyTime());
        model.setAuthorizationTime(vo.getAuthorizationTime());
    }

}
