package com.bcxin.tenant.domain.entities;
import cn.hutool.core.util.RandomUtil;
import com.bcxin.Infrastructures.entities.OpEntityAbstract;
import com.bcxin.Infrastructures.entities.IAggregate;
import com.bcxin.Infrastructures.utils.UUIDUtil;
import com.bcxin.Infrastructures.enums.ApprovedStatus;
import com.bcxin.tenant.domain.enums.EmployeeEventType;
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_employee_events")
@Entity
public class EmployeeEventEntity extends OpEntityAbstract implements IAggregate {
    @Id
    private String id;

    @Column(name = "event_type", nullable = false)
    @Enumerated(EnumType.ORDINAL)
    private EmployeeEventType eventType;

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

    /**
     * 设置为ALL的话,则可以实现先持久化EmployeeEventEntity，在持久化EmployeeEntity
     * 否则一定要先调用EmployeeEntity的save
     */
    @ManyToOne(cascade = {CascadeType.DETACH})
    @JoinColumn(name = "employee_id", referencedColumnName = "id", nullable = false)
    private EmployeeEntity employee;

    @Column(name = "note", length = 2000)
    private String note;


    @Column(name = "attachment", length = 2000)
    private String attachment;

    @Column(name = "event_time", nullable = false)
    private Timestamp eventTime;

    @Enumerated(EnumType.ORDINAL)
    private ApprovedStatus status;

    @Column(name = "approved_note", length = 2000)
    private String approvedNote;

    @Column(name = "approved_time", nullable = true)
    private Timestamp approvedTime;

    protected EmployeeEventEntity() {
        this.setCreatedTime(Timestamp.from(Instant.now()));
    }

    public static EmployeeEventEntity create(EmployeeEntity employee, EmployeeEventType eventType, Timestamp eventTime, String note) {
        EmployeeEventEntity employeeEvent = new EmployeeEventEntity();
        employeeEvent.setEmployee(employee);
        employeeEvent.setId(String.format("%s-%s", Instant.now().getEpochSecond(), UUIDUtil.getShortUuid()));
        employeeEvent.setEventType(eventType);
        employeeEvent.setEventTime(eventTime);
        employeeEvent.setNote(note);

        return employeeEvent;
    }

    public void changeStatus(ApprovedStatus status, String approvedNote) {
        this.setStatus(status);
        this.setApprovedNote(approvedNote);
        this.setApprovedTime(Timestamp.from(Instant.now()));
    }

    public void change(String note, String attachment) {
        this.setNote(note);
        this.setAttachment(attachment);
    }

    public void changeEventTime(Timestamp date) {
        this.setEventTime(date);
    }
}
