package com.ecep.contract.ds.contract.model;

import com.ecep.contract.cloud.old.CompanyContactUtils;
import com.ecep.contract.ds.company.model.Company;
import com.ecep.contract.ds.company.model.CompanyBasedEntity;
import com.ecep.contract.ds.company.model.CompanyContact;
import com.ecep.contract.model.IdentityEntity;
import com.ecep.contract.model.Voable;
import com.ecep.contract.util.HibernateProxyUtils;
import com.ecep.contract.vo.CompanyContractVo;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Map;
import java.util.Objects;

@Getter
@Setter
@Entity
@Table(name = "COMPANY_CONTRACT", schema = "supplier_ms", indexes = {
        @Index(name = "RK_CONTRACT_ID", columnList = "CONTRACT_ID"),
        @Index(name = "RK_COMPANY_ID", columnList = "COMPANY_ID")
}, uniqueConstraints = {

})
@ToString(exclude = { "company", "contract" })
public class CompanyContract implements IdentityEntity, CompanyBasedEntity, Voable<CompanyContractVo> {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false)
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "COMPANY_ID")
    private Company company;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "CONTRACT_ID")
    private Contract contract;

    /**
     * 要和{@link CompanyContactUtils#getContactKey(Map)}一致
     */
    public static String getContactKey(CompanyContact contact) {
        if (contact == null) {
            return null;
        }
        return contact.getName() +
                contact.getPhone() +
                contact.getEmail();
    }

    @Override
    public final boolean equals(Object object) {
        if (this == object)
            return true;
        if (object == null)
            return false;
        if (HibernateProxyUtils.isNotEffectiveClassEquals(object, this)) {
            return false;
        }
        CompanyContract that = (CompanyContract) object;
        return getId() != null && Objects.equals(getId(), that.getId());
    }

    @Override
    public final int hashCode() {
        return HibernateProxyUtils.hashCode(this);
    }

    @Override
    public CompanyContractVo toVo() {
        CompanyContractVo vo = new CompanyContractVo();
        vo.setId(getId());
        vo.setCompanyId(getCompany() != null ? getCompany().getId() : null);
        vo.setContractId(getContract() != null ? getContract().getId() : null);
        vo.setContractCode(getContract() != null ? getContract().getCode() : null);
        vo.setContractName(getContract() != null ? getContract().getName() : null);
        return vo;
    }
}
