package com.bonus.canteen.core.device.manage.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.canteen.core.device.door.dto.door.BindDto;
import com.bonus.canteen.core.device.manage.mapper.DeviceDcDoorMapper;
import com.bonus.canteen.core.device.manage.model.DeviceDcDoor;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class DeviceDcDoorService {
   @Resource
   private DeviceDcDoorMapper deviceDcDoorMapper;


   public List<Long> getAllDeviceIds() {
      return this.deviceDcDoorMapper.selectObjs(Wrappers.lambdaQuery(DeviceDcDoor.class)
                      .select(DeviceDcDoor::getDeviceId)).stream()
              .map(item -> (Long) item)
              .collect(Collectors.toList());
   }

   public void updateByIndexAndDevice(Long parendDeviceId, List<BindDto> doors) {
      doors = (Optional.ofNullable(doors).orElse(Lists.newArrayList())).stream().filter((item) -> {
         return item.getDoorId() != null && item.getDoorIndex() != null;
      }).collect(Collectors.toList());
      this.deviceDcDoorMapper.update(null, ((Wrappers.lambdaUpdate(DeviceDcDoor.class).set(DeviceDcDoor::getDoorIndex, (Object)null)).set(DeviceDcDoor::getParentDeviceId, (Object)null)).eq(DeviceDcDoor::getParentDeviceId, parendDeviceId));
      if (CollectionUtil.isNotEmpty(doors)) {
         doors.forEach((item) -> {
            this.deviceDcDoorMapper.update(null, ((Wrappers.lambdaUpdate(DeviceDcDoor.class).set(DeviceDcDoor::getDoorIndex, item.getDoorIndex())).set(DeviceDcDoor::getParentDeviceId, parendDeviceId)).eq(DeviceDcDoor::getDeviceId, item.getDoorId()));
         });
      }

   }

   public void insert(DeviceDcDoor deviceDcDoor) {
      this.deviceDcDoorMapper.insert(deviceDcDoor);
   }

   public void deleteByDeviceId(Long deviceId) {
      this.deviceDcDoorMapper.delete(Wrappers.lambdaQuery(DeviceDcDoor.class)
              .eq(DeviceDcDoor::getDeviceId, deviceId));
   }
}
