package com.ecep.contract.ds.project;

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.model.Company;
import com.ecep.contract.ds.project.model.Project;
import com.ecep.contract.ds.project.service.ProjectService;
import com.ecep.contract.util.BeanContext;
import com.ecep.contract.vo.ProjectVo;

public class ProjectCtx extends AbstractCtx {

    public ProjectCtx() {
        super();
    }

    public ProjectCtx(BeanContext ctx) {
        super(ctx);
    }

    public ProjectService getProjectService() {
        return getCachedBean(ProjectService.class);
    }

    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().getById(customer.getId());
            }
            holder.info("同步合同所属项目客户为：" + customer.getName());
            modified = true;
        }

        return modified;
    }

    public boolean updateCustomerId(ProjectVo project, Integer customerId, MessageHolder holder) {
        boolean modified = false;
        if (!Objects.equals(project.getCustomerId(), customerId)) {
            project.setCustomerId(customerId);
            var customer = getCompanyService().findById(customerId);
            holder.info("同步合同所属项目客户为：" + customer.getName());
            modified = true;
        }

        return modified;
    }


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

    public ProjectVo save(ProjectVo project) {
        ProjectService service = getProjectService();
        var v0 = service.getById(project.getId());
        service.updateByVo(v0, project);
        return service.save(v0).toVo();
    }
}
