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.SasDevice;
import com.usky.sas.domain.SasVideoMonitorGroupType;
import com.usky.sas.mapper.SasVideoMonitorGroupTypeMapper;
import com.usky.sas.service.SasDeviceService;
import com.usky.sas.service.SasVideoMonitorGroupTypeService;
import com.usky.sas.service.vo.VideoMonitorGroupPageRequest;
import com.usky.sas.service.vo.VideoMonitorGroupSaveRequest;
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 SasVideoMonitorGroupTypeServiceImpl extends AbstractCrudService<SasVideoMonitorGroupTypeMapper, SasVideoMonitorGroupType>
        implements SasVideoMonitorGroupTypeService {

    @Autowired
    private SasDeviceService sasDeviceService;

    @Override
    public List<SasVideoMonitorGroupType> listAll() {
        return this.list();
    }

    @Override
    public CommonPage<SasVideoMonitorGroupType> page(VideoMonitorGroupPageRequest request) {
        IPage<SasVideoMonitorGroupType> 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(VideoMonitorGroupSaveRequest request) {
        String id = UUID.randomUUID().toString();
        SasVideoMonitorGroupType group = new SasVideoMonitorGroupType();
        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, VideoMonitorGroupSaveRequest request) {
        SasVideoMonitorGroupType 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.setVideoGroupType(groupId);
            device.setUpdateTime(LocalDateTime.now());
            sasDeviceService.updateById(device);
        }
    }
}
