package com.usky.sas.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.sas.domain.SasAlarsasGroupType;
import com.usky.sas.domain.SasDevice;
import com.usky.sas.mapper.SasAlarsasGroupTypeMapper;
import com.usky.sas.service.SasAlarsasGroupTypeService;
import com.usky.sas.service.SasDeviceService;
import com.usky.sas.service.vo.AlarmGroupPageRequest;
import com.usky.sas.service.vo.AlarmGroupSaveRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class SasAlarsasGroupTypeServiceImpl extends AbstractCrudService<SasAlarsasGroupTypeMapper, SasAlarsasGroupType>
        implements SasAlarsasGroupTypeService {

    @Autowired
    private SasDeviceService sasDeviceService;

    @Override
    public CommonPage<SasAlarsasGroupType> page(AlarmGroupPageRequest request) {
        IPage<SasAlarsasGroupType> page = new Page<>(request.getCurrent(), request.getSize());
        page = this.page(page);
        return new CommonPage<>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public String create(AlarmGroupSaveRequest request) {
        String id = UUID.randomUUID().toString();
        SasAlarsasGroupType group = new SasAlarsasGroupType();
        group.setId(id);
        group.setName(request.getName());
        group.setNote(request.getNote());
        this.save(group);

        bindDevices(id, request.getDeviceIds());
        return id;
    }

    @Override
    public void update(String id, AlarmGroupSaveRequest request) {
        SasAlarsasGroupType group = this.getById(id);
        if (group == null) {
            return;
        }
        group.setName(request.getName());
        group.setNote(request.getNote());
        this.updateById(group);

        bindDevices(id, request.getDeviceIds());
    }

    @Override
    public void delete(String id) {
        this.removeById(id);
    }

    private void bindDevices(String groupId, List<String> deviceIds) {
        if (deviceIds == null) {
            return;
        }
        for (String deviceId : deviceIds) {
            SasDevice device = sasDeviceService.getById(deviceId);
            if (device == null) {
                continue;
            }
            device.setAlarsasGroupType(groupId);
            device.setUpdateTime(LocalDateTime.now());
            sasDeviceService.updateById(device);
        }
    }
}

