package com.tykj.dev.device.user.subject.service.impl;

import com.tykj.dev.device.user.subject.dao.GroupDao;
import com.tykj.dev.device.user.subject.entity.Groups;
import com.tykj.dev.device.user.subject.service.GroupService;
import com.tykj.dev.device.user.subject.service.UnitsService;
import com.tykj.dev.misc.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName GroupServiceImpl.java
 * @Description TODO
 * @createTime 2021年01月09日 12:16:00
 */
@Service
@Slf4j
public class GroupServiceImpl implements GroupService {
    @Autowired
    GroupDao groupDao;
    @Autowired
    UnitsService unitsService;
    @Override
    public void saveGroup(Groups group) {
        StringBuffer stringBuffer=new StringBuffer();
        group.getMembers().forEach(
                integer -> stringBuffer.append(",").append(integer)
        );
        group.setMemberId(stringBuffer.toString());
        groupDao.save(group);
    }

    @Override
    public List<Groups> findAll(Integer type) {
        List<Groups> list = groupDao.findAllByType(type);
        list.forEach(groups -> groups.setUnitsList(unitsService.findAllByIdIn(integerList(groups.getMemberId()))));
        return list;
    }

    private List<Integer> integerList(String ids){
        List<String> idStringList = Arrays.asList(ids.split(","));
        return idStringList.stream().filter(list2->!list2.equals("")).map(Integer::parseInt).collect(Collectors.toList());
    }
    @Override
    public void delectGroup(Integer id) {
      groupDao.deleteById(id);
    }

    @Override
    public List<Integer> findGroup(Integer id) {
        Groups group= groupDao.findById(id).get();
        return Arrays.asList(group.getMemberId().substring(2).split(",")).stream().map(Integer::parseInt).collect(Collectors.toList());
    }

    @Override
    public Groups findById(Integer id) {
        Optional<Groups> optionalGroups = groupDao.findById(id);
        if (optionalGroups.isPresent()){
            Groups groups = optionalGroups.get();
            groups.setUnitsList(unitsService.findAllByIdIn(integerList(groups.getMemberId())));
            return groups;
        }else {
            throw new ApiException(ResponseEntity.status(500).body("[组] 没有找到对应的id"));
        }
    }
}
