package com.sptg.permissions.biz.receiver;

import com.sptg.device.api.entity.Device;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.permissions.api.dto.RegionAuthorizeDto;
import com.sptg.permissions.api.entity.DeviceAuthorize;
import com.sptg.permissions.api.stream.XqAuthorizeReceiverInterface;
import com.sptg.permissions.biz.service.DeviceAuthorizeServiceInterface;
import com.sptg.permissions.biz.stream.XqAuthorizeProduceInterface;
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.ArrayList;
import java.util.List;

/**
 * title: XqAuthorizeReceiver
 * description: 小区授权消费者
 *
 *                  
 *            
 */
@Component
@Slf4j
@RequiredArgsConstructor
@EnableBinding(value = { XqAuthorizeProduceInterface.class, XqAuthorizeReceiverInterface.class})
public class XqAuthorizeReceiver {

    private final DeviceFeign deviceFeign;
    private final DeviceAuthorizeServiceInterface deviceAuthorizeServiceInterface;

    @StreamListener(value = XqAuthorizeReceiverInterface.INPUT)
    public void input(RegionAuthorizeDto dto){
        if (null == dto){
            return;
        }
        //  授权的小区Id列表
        List<Long> orgIdList = dto.getOrgIdList();
        //  获取每个小区下的所有设备,将其授权与该机构
        orgIdList.forEach(orgId -> {
            //  获取小区下的所有设备
            List<Device> deviceList = this.deviceFeign.getListByXqId(orgId);
            if (null == deviceList){
                throw new RuntimeException("查询小区下所有设备接口,请求超时.");
            }
            if (deviceList.size() > 0){
                //  构建授权列表
                List<DeviceAuthorize> authorizeList = new ArrayList<>(deviceList.size());
                //  填充字段
                deviceList.forEach(device -> {
                    DeviceAuthorize authorize = this.deviceAuthorizeServiceInterface.createAuthorizeObj(device);
                    //  授权机构路径
                    authorize.setOrgPosition(dto.getOrgPosition());
                    //  创建者信息
                    authorize.setCreateAccountId(dto.getCreateAccountId());
                    authorize.setCreateDate(dto.getCreateDate());
                    authorizeList.add(authorize);
                });
                //  批量授权
                this.deviceAuthorizeServiceInterface.insertBatch(authorizeList);
            }
        });
    }


}
