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

import java.util.List;

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.customer.service.CompanyCustomerEvaluationFormFileService;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.ds.project.repository.ProjectBidRepository;
import com.ecep.contract.ds.project.model.Project;
import com.ecep.contract.ds.project.model.ProjectBid;
import com.ecep.contract.service.VoableService;
import com.ecep.contract.util.SpecificationUtils;
import com.ecep.contract.vo.ProjectBidVo;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "project-bid")
public class ProjectBidService implements IEntityService<ProjectBid>, QueryService<ProjectBidVo>,
        VoableService<ProjectBid, ProjectBidVo> {
    @Lazy
    @Autowired
    private ProjectBidRepository repository;

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

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

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

    @Override
    public Page<ProjectBidVo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ProjectBid> 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<ProjectBid> page = findAll(spec, pageable);
        return page.map(ProjectBid::toVo);
    }

    @Override
    public Specification<ProjectBid> 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("bidName"), "%" + searchText + "%"));
        };
    }

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

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

    public List<ProjectBid> findByProjectId(Integer projectId) {
        Project project = SpringApp.getBean(ProjectService.class).getById(projectId);
        if (project != null) {
            return repository.findAllByProject(project);
        }
        return java.util.Collections.emptyList();
    }

    @Override
    public void updateByVo(ProjectBid model, ProjectBidVo vo) {
        model.setLevel(vo.getLevel());
        model.setAmount(vo.getAmount());
        model.setStandardPayWay(vo.isStandardPayWay());
        model.setNoStandardPayWayText(vo.getNoStandardPayWayText());
        model.setStandardContractText(vo.isStandardContractText());
        model.setNoStandardContractText(vo.getNoStandardContractText());
        model.setAuthorizationFile(vo.getAuthorizationFile());
        model.setBidAcceptanceLetterFile(vo.getBidAcceptanceLetterFile());
        model.setApplyTime(vo.getApplyTime());
        model.setAuthorizationTime(vo.getAuthorizationTime());
        model.setDescription(vo.getDescription());

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

        if (vo.getEvaluationFileId() != null) {
            CompanyCustomerEvaluationFormFileService evaluationFileService = SpringApp
                    .getBean(CompanyCustomerEvaluationFormFileService.class);
            model.setEvaluationFile(evaluationFileService.findById(vo.getEvaluationFileId()));
        } else {
            model.setEvaluationFile(null);
        }

        if (vo.getCostId() != null) {
            ProjectCostService costService = SpringApp.getBean(ProjectCostService.class);
            model.setCost(costService.getById(vo.getCostId()));
        } else {
            model.setCost(null);
        }

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

        if (vo.getAuthorizerId() != null) {
            model.setAuthorizer(employeeService.getById(vo.getAuthorizerId()));
        } else {
            model.setAuthorizer(null);
        }
    }

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