package com.ecep.contract.ds.project;

import static com.ecep.contract.SpringApp.getBean;

import java.util.Objects;

import org.hibernate.Hibernate;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.cloud.AbstractCtx;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.project.service.ProjectService;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.Project;

import lombok.Setter;

public class ProjectCtx extends AbstractCtx {
    @Setter
    private ProjectService projectService;
    @Setter
    CompanyService companyService;

    ProjectService getProjectService() {
        if (projectService == null) {
            projectService = getBean(ProjectService.class);
        }
        return projectService;
    }

    CompanyService getCompanyService() {
        if (companyService == null) {
            companyService = getBean(CompanyService.class);
        }
        return companyService;
    }

    public boolean updateCustomer(Project project, Company customer, MessageHolder holder) {
        boolean modified = false;
        if (!Objects.equals(project.getCustomer(), customer)) {
            project.setCustomer(customer);
            if (!Hibernate.isInitialized(customer)) {
                customer = getCompanyService().findById(customer.getId());
            }
            holder.info("同步合同所属项目客户为：" + customer.getName());
            modified = true;
        }

        return modified;
    }

    public Project initialize(Project project) {
        if (Hibernate.isInitialized(project)) {
            return project;
        }
        return getProjectService().findById(project.getId());
    }

    public Project save(Project project) {
        return getProjectService().save(project);
    }
}
