package com.ruoyi.project.common.service.impl;

import com.ruoyi.common.exception.ServiceErrorException;
import com.ruoyi.common.utils.Tools;
import com.ruoyi.project.common.dto.ExclusiveDto;
import com.ruoyi.project.common.mapper.ExclusiveMapper;
import com.ruoyi.project.common.service.IExclusiveService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author lidl
 */
@Service
public class ExclusiveServiceImpl implements IExclusiveService {

    @Resource
    private ExclusiveMapper exclusiveMapper;

    @Override
    public void exclusive(ExclusiveDto exclusiveDto) {
        if(Objects.isNull(exclusiveDto.getId())){
            return;
        }
        ExclusiveDto temp = exclusiveMapper.getExclusive(exclusiveDto);
        if (Objects.isNull(temp)){
            // TODO i18n
            throw new ServiceErrorException("数据已被删除，请刷新后重试");
        }
        if(Tools.compareUpdateDt(exclusiveDto.getUpdateTime(),temp.getUpdateTime())){
            throw new ServiceErrorException("当前数据已被修改，请刷新后重试");
        }
    }

    @Override
    public void exclusives(ExclusiveDto exclusiveDto, List<ExclusiveDto> exclusiveDtoList) {
        Map<Long,ExclusiveDto> map = exclusiveDtoList.stream().collect(Collectors.toMap(ExclusiveDto::getId, item -> item));

        List<ExclusiveDto> checkList = exclusiveMapper.getExclusives(exclusiveDto,exclusiveDtoList);
        if(checkList.size() != exclusiveDtoList.size()){
            throw new ServiceErrorException( (exclusiveDtoList.size() == 1 ? "": "部分") + "数据已被删除，请刷新后重试");
        }
        for(ExclusiveDto check:checkList){
            if(Tools.compareUpdateDt(map.get(check.getId()).getUpdateTime(), check.getUpdateTime())){
                throw new ServiceErrorException("数据已更新，请刷新后重试");
            }
        }
    }
}
