package com.bcxin.tenant.domain.entities;

import com.bcxin.Infrastructures.TenantContext;
import com.bcxin.Infrastructures.TenantUserContext;
import com.bcxin.Infrastructures.entities.EntityAbstract;
import com.bcxin.Infrastructures.entities.IAggregate;
import com.bcxin.Infrastructures.exceptions.ForbidTenantException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.sql.Timestamp;
import java.time.Instant;

@Getter
@Setter(AccessLevel.PROTECTED)
@Table(name = "tenant_organization_types")
@Entity
public class OrganizationTypeEntity extends EntityAbstract implements IAggregate {

    @Id
    @Column(nullable = false)
    private long id;


    @Column(name = "name",length = 100,nullable = false)
    private String name;

    @Column(name = "note")
    private String note;

    @Column(name = "organization_id",length = 50,nullable = false)
    private String organizationId;

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

    @Column(name = "creator_id",length = 50,nullable = false)
    private String creatorId;

    @Column(name = "last_updator_id",length = 50,nullable = false)
    private String lastUpdatorId;

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

    public OrganizationTypeEntity() {
        this.setCreatedTime(Timestamp.from(Instant.now()));
    }

    public OrganizationTypeEntity(String name, String note, String organizationId, String creatorId, String lastUpdateId, Timestamp lastUpdateTime) {
        this();
        this.setName(name);
        this.setNote(note);
        this.setOrganizationId(organizationId);
        this.setCreatorId(creatorId);
        this.setLastUpdatorId(lastUpdateId);
        this.setLastUpdatedTime(lastUpdateTime);
    }

    public static OrganizationTypeEntity create(String name, String note, String organizationId, String creatorId, String lastUpdateId) {
        Timestamp timestamp = Timestamp.from(Instant.now());
        OrganizationTypeEntity organizationTypeEntity = new OrganizationTypeEntity(name,note,organizationId,creatorId,lastUpdateId,timestamp);
        return organizationTypeEntity;
    }

    public void change(String name, String note, String organizationId) {
        if (name != null){
            this.setName(name);
        }
        if (note != null){
            this.setNote(note);
        }
        if (organizationId != null){
            this.setOrganizationId(organizationId);
        }
        this.setLastUpdatedTime(Timestamp.from(Instant.now()));
        TenantUserContext.UserModel currentUser = TenantContext.getInstance().getUserContext().get();
        if (currentUser == null) {
            throw new ForbidTenantException("必须有人来操作离职");
        }
        this.setLastUpdatorId(currentUser.getId());
    }
}
