package com.tykj.dev.device.sendback.service.impl;

import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.sendback.entity.domain.DeviceRepel;
import com.tykj.dev.device.sendback.repository.DeviceRepelDao;
import com.tykj.dev.device.sendback.service.DeviceRepelService;
import com.tykj.dev.device.user.subject.entity.Units;
import com.tykj.dev.device.user.subject.service.UnitsService;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.StringUtils;
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.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName DeviceRepelServiceImpl.java
 * @Description 清退通知详情业务层 发起清退任务 生成一次 转发生成一次
 * @createTime 2021年01月07日 09:52:00
 */
@Service
@Slf4j
public class DeviceRepelServiceImpl implements DeviceRepelService {
    @Autowired
    DeviceRepelDao deviceRepelDao;

    @Autowired
    UnitsService unitsService;

    @Override
    public DeviceRepel saveDeviceRepel(DeviceRepel deviceRepel) {
        return deviceRepelDao.save(deviceRepel);
    }

    @Override
    public DeviceRepel findDeviceRepel(Integer repelId) {
        Optional<DeviceRepel> optional = deviceRepelDao.findById(repelId);
        if (optional.isPresent()){
            DeviceRepel deviceRepel = optional.get();
            deviceRepel.setFileRets(FilesUtil.stringFileToList(deviceRepel.getFiles()));
            deviceRepel.setFieldingIds(StringUtils.stringToList(deviceRepel.getFielding()));
            List<String> unitNames= unitsService.findAllByIdIn(StringUtils.stringToList(deviceRepel.getTaskScope())).stream().map(Units::getName).collect(Collectors.toList());
            deviceRepel.setUnitNames(unitNames);
            return deviceRepel;
        }else {
            throw new ApiException(ResponseEntity.status(500).body("[清退] 未找到清退账单："+repelId));
        }
    }

    @Override
    public List<DeviceRepel> findNotEndDeviceRepel() {
        return deviceRepelDao.findAll().stream().filter(deviceRepel -> deviceRepel.getStatus()==0).collect(Collectors.toList());
    }
}
