package com.sptg.permissions.biz.receiver;

import com.sptg.common.core.constant.OperationConstant;
import com.sptg.permissions.api.dto.OrgDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Role;
import com.sptg.permissions.api.stream.OrgTransferReceiverInterface;
import com.sptg.permissions.biz.service.AccountServiceInterface;
import com.sptg.permissions.biz.service.DeviceAuthorizeServiceInterface;
import com.sptg.permissions.biz.service.RegionAuthorizeServiceInterface;
import com.sptg.permissions.biz.service.RoleServiceInterface;
import com.sptg.permissions.biz.stream.OrgTransferProduceInterface;
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: OrgTransferReceiver
 * description:
 *
 *                  
 *            
 */
@Component
@Slf4j
@RequiredArgsConstructor
@EnableBinding(value = { OrgTransferProduceInterface.class, OrgTransferReceiverInterface.class})
public class OrgTransferReceiver {

    private final AccountServiceInterface accountServiceInterface;
    private final RoleServiceInterface roleServiceInterface;
    private final DeviceAuthorizeServiceInterface deviceAuthorizeServiceInterface;
    private final RegionAuthorizeServiceInterface regionAuthorizeServiceInterface;

    @StreamListener(value = OrgTransferReceiverInterface.INPUT)
    public void input(OrgDto dto){
        if (null == dto){
            return;
        }
        //  旧的机构位置
        String oldPosition = dto.getOrgPosition();
        //  新的机构位置
        String newPosition = dto.getPosition();
        //  获取该机构以及子机构下的所有账号列表
        List<Account> accountList = this.accountServiceInterface.selectByOrgPosition(oldPosition);
        if (accountList.size() > OperationConstant.ZERO){
            accountList.forEach(account -> {
                String replace = account.getOrgPosition().replace(oldPosition, newPosition);
                account.setOrgPosition(replace);
            });
            this.accountServiceInterface.updateBatch(accountList);
        }
        //  获取该机构以及子机构下的所有角色列表
        List<Role> roleList = this.roleServiceInterface.selectByOrgPosition(oldPosition);
        if (roleList.size() > OperationConstant.ZERO){
            roleList.forEach(role -> {
                String replace = role.getOrgPosition().replace(oldPosition, newPosition);
                role.setOrgPosition(replace);
            });
            this.roleServiceInterface.updateBatch(roleList);
        }
        //  删除此机构下授权的所有设备
        this.deviceAuthorizeServiceInterface.deleteByOrgPositionOrResidentialId(oldPosition,dto.getId());
        //  删除此机构下的授权所有小区
        this.regionAuthorizeServiceInterface.deleteByOrgPositionOrResidentialId(oldPosition,dto.getId());
        //  其他关联表 ....

    }

}
