package com.sptg.permissions.biz.receiver;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.sptg.device.api.dto.DeviceDto;
import com.sptg.device.api.stream.DeviceAddReceiverInterface;
import com.sptg.permissions.api.entity.DeviceAuthorize;
import com.sptg.permissions.api.entity.RegionAuthorize;
import com.sptg.permissions.biz.service.DeviceAuthorizeServiceInterface;
import com.sptg.permissions.biz.service.RegionAuthorizeServiceInterface;
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.Date;
import java.util.List;

/**
 * title: DeviceAddReceiver
 * description:
 *
 *                  
 *            
 */
@Component
@Slf4j
@RequiredArgsConstructor
@EnableBinding(value = { DeviceAddReceiverInterface.class})
public class DeviceAddReceiver {


    private final DeviceAuthorizeServiceInterface deviceAuthorizeServiceInterface;
    private final RegionAuthorizeServiceInterface regionAuthorizeServiceInterface;

    @StreamListener(value = DeviceAddReceiverInterface.INPUT)
    public void input(DeviceDto dto){
        //  因为设备信息可能被重新录入,需要先删除原授权记录
        Wrapper<DeviceAuthorize> wrapper = new EntityWrapper<>();
        wrapper.eq("l_device_id",dto.getId());
        this.deviceAuthorizeServiceInterface.delete(wrapper);
        //  获取此设备所属小区的授权列表
        List<RegionAuthorize> regionAuthorizeList = this.regionAuthorizeServiceInterface.selectListByXqId(dto.getXqId());
        Date nowTime = new Date();
        if (regionAuthorizeList.size() > 0) {
            List<DeviceAuthorize> authorizeList = new ArrayList<>(regionAuthorizeList.size());
            //  构建设备的授权列表
            regionAuthorizeList.forEach(regionAuthorize -> {
                DeviceAuthorize authorize = this.deviceAuthorizeServiceInterface.createAuthorizeObj(dto);
                //  授权机构路径
                authorize.setOrgPosition(regionAuthorize.getOrgPosition());
                authorize.setCreateDate(nowTime);
                authorizeList.add(authorize);
            });
            //  批量授权
            this.deviceAuthorizeServiceInterface.insertBatch(authorizeList);
        }
        //  将设备授权与所属机构
        DeviceAuthorize authorize = this.deviceAuthorizeServiceInterface.createAuthorizeObj(dto);
        authorize.setOrgPosition(dto.getOrgPosition());
        authorize.setCreateDate(nowTime);
        this.deviceAuthorizeServiceInterface.insert(authorize);
    }

}
