package com.bcxin.tenant.domain.entities;

import com.bcxin.Infrastructures.entities.EntityAbstract;
import com.bcxin.Infrastructures.entities.IAggregate;
import com.bcxin.Infrastructures.enums.OrgRelationStatus;
import com.bcxin.Infrastructures.utils.UUIDUtil;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.sql.Timestamp;
import java.time.Instant;

@Getter
@Setter(AccessLevel.PROTECTED)
@Table(name = "tenant_org_relation")
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class OrgRelationEntity extends EntityAbstract implements IAggregate {

    @Id
    @Column(length = 20)
    private String id;

    /**
     * 状态
     */
    @Column(name = "relation_status",nullable = false)
    @Enumerated(EnumType.ORDINAL)
    private OrgRelationStatus relationStatus;

    @Column(name = "created_time", nullable = false)
    private Timestamp createdTime;

    @Column(name = "last_updated_time")
    private Timestamp lastUpdatedTime;

    @ManyToOne(cascade = CascadeType.DETACH,fetch = FetchType.LAZY)
    @JoinColumn(name = "org_id",referencedColumnName = "id", nullable = false,
            foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    private OrganizationEntity organization;


    /**
     * 上级组织
     */
    @ManyToOne(cascade = CascadeType.DETACH,fetch = FetchType.LAZY)
    @JoinColumn(name = "parent_org_id",referencedColumnName = "id", nullable = false,
            foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    private OrganizationEntity parentOrg;

    public OrgRelationEntity(){}

    public OrgRelationEntity(OrganizationEntity organizationEntity, OrganizationEntity parentOrg){
        this.setOrganization(organizationEntity);
        this.setParentOrg(parentOrg);
    }

    public static OrgRelationEntity create(OrganizationEntity organizationEntity, OrganizationEntity parentOrg) {
        OrgRelationEntity orgRelationEntity = new OrgRelationEntity(organizationEntity,parentOrg);
        orgRelationEntity.setId(UUIDUtil.getShortUuid());
        orgRelationEntity.setRelationStatus(OrgRelationStatus.BIND);
        orgRelationEntity.setCreatedTime(Timestamp.from(Instant.now()));
        orgRelationEntity.setOrganization(organizationEntity);
        orgRelationEntity.setParentOrg(parentOrg);
        return orgRelationEntity;
    }


    public void change(OrgRelationStatus relationStatus){
        this.setRelationStatus(relationStatus);
        this.setLastUpdatedTime(Timestamp.from(Instant.now()));
    }
}
