package com.bcxin.tenant.domain.services.commands;

import com.bcxin.Infrastructures.commands.CommandAbstract;
import com.bcxin.Infrastructures.exceptions.ArgumentTenantException;
import lombok.Getter;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Getter
public class BatchAssignEmployeeSuperiorCommand extends CommandAbstract {
    private final String organizationId;
    private final Collection<AssignEmployeeSuperiorItem> items;

    public BatchAssignEmployeeSuperiorCommand(String organizationId,
                                              Collection<AssignEmployeeSuperiorItem> items) {
        this.organizationId = organizationId;
        this.items = items;
    }

    @Override
    public void validate() {
        super.validate();

        if (CollectionUtils.isEmpty(this.getItems())) {
            throw new ArgumentTenantException("待转移上级职员列表不能为空");
        }

        if (!StringUtils.hasLength(this.getOrganizationId())) {
            throw new ArgumentTenantException("组织id不能为空");
        }

        this.getItems().forEach(item -> {
            if (!StringUtils.hasLength(item.getOriginalSuperiorId())) {
                throw new ArgumentTenantException("待父职员不能为空");
            }
        });
    }

    public Collection<String> getComputedIds() {
        if (CollectionUtils.isEmpty(this.getItems())) {
            return Collections.EMPTY_LIST;
        }

        return this.getItems().stream().flatMap(ii -> {
            return Stream.of(ii.getOriginalSuperiorId(), ii.getNewSuperiorId()).filter(ix -> StringUtils.hasLength(ix));
        }).collect(Collectors.toList());
    }

    public static BatchAssignEmployeeSuperiorCommand create(String organizationId,
                                                            Collection<AssignEmployeeSuperiorItem> employeeSuperiorItems) {
        return new BatchAssignEmployeeSuperiorCommand(organizationId, employeeSuperiorItems);
    }

    @Getter
    public static class AssignEmployeeSuperiorItem {
        private final String originalSuperiorId;
        private final String newSuperiorId;

        public AssignEmployeeSuperiorItem(String originalSuperiorId, String newSuperiorId) {
            this.originalSuperiorId = originalSuperiorId;
            this.newSuperiorId = newSuperiorId;
        }

        public static AssignEmployeeSuperiorItem create(String originalSuperiorId, String newSuperiorId) {
            return new AssignEmployeeSuperiorItem(originalSuperiorId, newSuperiorId);
        }
    }
}
