package com.bcxin.tenant.domain.events.handlers;

import cn.hutool.core.date.DateUtil;
import com.bcxin.Infrastructures.components.JsonProvider;
import com.bcxin.Infrastructures.events.handlers.DomainEventHandlerAbstract;
import com.bcxin.tenant.domain.entities.EmployeeEventEntity;
import com.bcxin.tenant.domain.entities.EmployeeRecordEntity;
import com.bcxin.tenant.domain.enums.EmployeeEventType;
import com.bcxin.tenant.domain.enums.EventAction;
import com.bcxin.tenant.domain.events.EmployeeAfterCreatedEvent;
import com.bcxin.tenant.domain.repositories.EmployeeEventRepository;
import com.bcxin.tenant.domain.repositories.EmployeeRecordRepository;
import com.bcxin.tenant.domain.services.TenantEventService;
import com.bcxin.tenant.domain.services.commands.CreateTenantEventCommand;
import com.bcxin.tenant.domain.snapshots.TenantEmployeeSnapshot;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;

@Component
public class EmployeeAfterCreatedEvent_Handler extends DomainEventHandlerAbstract<EmployeeAfterCreatedEvent> {
    private final TenantEventService tenantEventService;
    private final JsonProvider jsonProvider;
    private final EmployeeEventRepository employeeEventRepository;
    private final EmployeeRecordRepository employeeRecordRepository;

    public EmployeeAfterCreatedEvent_Handler(TenantEventService tenantEventService, JsonProvider jsonProvider,
                                             EmployeeEventRepository employeeEventRepository,
                                             EmployeeRecordRepository employeeRecordRepository) {
        this.tenantEventService = tenantEventService;
        this.jsonProvider = jsonProvider;
        this.employeeEventRepository = employeeEventRepository;
        this.employeeRecordRepository = employeeRecordRepository;
    }

    @Override
    protected void execute(EmployeeAfterCreatedEvent event) {
        TenantEmployeeSnapshot snapshot = TenantEmployeeSnapshot.create(
                event.getData().getId()
        );

        String json = this.jsonProvider.getJson(snapshot);
        this.tenantEventService.create(
                CreateTenantEventCommand.create(EventAction.EmployeeCreated, json, event.getTelephone()));


        Timestamp hiredDate = null;
        if (event.getData() != null && event.getData().getHiredDate() != null) {
            hiredDate = Timestamp.valueOf(DateUtil.toLocalDateTime(event.getData().getHiredDate()));
        } else {
            hiredDate = event.getData() == null ? new Timestamp(System.currentTimeMillis()) : event.getData().getCreatedTime();
        }

        this.employeeEventRepository.save(
                EmployeeEventEntity.create(event.getData(),
                        EmployeeEventType.EntryJob, hiredDate, "入职"));

        /**
         * 产生入职记录
         */
        EmployeeRecordEntity record = EmployeeRecordEntity.create(event.getData());
        this.employeeRecordRepository.save(record);
    }
}
