package com.sptg.permissions.biz.receiver;

import com.sptg.common.core.constant.OperationConstant;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.stream.OrgDisableReceiverInterface;
import com.sptg.permissions.biz.service.AccountServiceInterface;
import com.sptg.permissions.biz.service.OrgServiceInterface;
import com.sptg.permissions.biz.stream.OrgDisableProduceInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * title: OrgDisableReceiver
 * description: 机构禁用消费者
 *
 *                  
 *            
 */
@Component
@Slf4j
@RequiredArgsConstructor
@EnableBinding(value = { OrgDisableReceiverInterface.class, OrgDisableProduceInterface.class})
public class OrgDisableReceiver {

    private final AccountServiceInterface accountServiceInterface;
    private final OrgServiceInterface orgServiceInterface;

    @StreamListener(value = OrgDisableReceiverInterface.INPUT)
    public void input(Long orgId){
        Organization organization = this.orgServiceInterface.selectById(orgId);
        if (null == organization){
            return;
        }
        //  获取子机构列表
        List<Organization> organizationList = this.orgServiceInterface.selectByPosition(organization.getPosition());
        if (organizationList.size() > OperationConstant.ZERO) {
            organizationList.forEach(item -> {
                //  修改机构状态
                item.setIsEnable(organization.getIsEnable());
            });
            //  批量保存
            this.orgServiceInterface.updateBatchById(organizationList);
        }
        //  获取机构列表下的所有用户
        List<Account> accountList = this.accountServiceInterface.selectByOrgPosition(organization.getPosition());
        if (accountList.size() > OperationConstant.ZERO) {
            //  设置用户为禁用状态
            accountList.forEach(account -> account.setIsEnable(organization.getIsEnable()));
            //  保存修改
            this.accountServiceInterface.updateBatch(accountList);
        }
    }

}
