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

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

import java.util.Collection;

@Getter
public class BatchAssignImPermissionCommand extends CommandAbstract {
    private final String organizationId;
    private final Collection<String> departIds;
    private final DepartImPermissionType permissionType;
    private final Collection<String> allowedDepartIds;

    public BatchAssignImPermissionCommand(String organizationId,
                                          Collection<String> departIds,
                                          DepartImPermissionType permissionType,
                                          Collection<String> allowedDepartIds) {
        this.organizationId = organizationId;
        this.departIds = departIds;
        this.permissionType = permissionType;
        this.allowedDepartIds = allowedDepartIds;
    }

    @Override
    public void validate() {
        if (!StringUtils.hasLength(this.getOrganizationId())) {
            throw new BadTenantException("所在组织无效!");
        }

        if (CollectionUtils.isEmpty(departIds)) {
            throw new BadTenantException("批量设置权限的部门列表不能为空!");
        }

        if (this.getPermissionType() == null) {
            throw new BadTenantException("通讯录权限类型不能为空!");
        }

        if (this.getPermissionType() == DepartImPermissionType.Special && CollectionUtils.isEmpty(this.getAllowedDepartIds())) {
            throw new BadTenantException("通讯录权限为: 可见指定部门时, 必须选择要授权的部门列表");
        }
    }

    public static BatchAssignImPermissionCommand create(String organizationId,
                                                        Collection<String> departIds,
                                                        DepartImPermissionType permissionType,
                                                        Collection<String> allowedDepartIds) {
        return new BatchAssignImPermissionCommand(organizationId, departIds, permissionType, allowedDepartIds);
    }
}
