package com.ruoyi.bst.model.service.impl;

import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.bst.model.domain.ModelQuery;
import com.ruoyi.bst.model.domain.ModelVO;
import com.ruoyi.bst.model.mapper.ModelMapper;
import com.ruoyi.bst.model.service.ModelValidator;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;

@Service
public class ModelValidatorImpl implements ModelValidator {

    @Autowired
    private ModelMapper modelMapper;

    @Override
    public boolean canEdit(Long id) {
        return this.canView(Collections.singletonList(id));
    }

    @Override
    public boolean canDeleteAll(List<Long> ids) {
        return this.canView(ids);
    }
    
    /**
     * 当前用户是否可以查看
     * @param ids
     * @return
     */
    private boolean canView(List<Long> ids) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return true;
        }
        ModelQuery query = new ModelQuery();
        query.setIds(ids);
        List<Long> idList = modelMapper.selectIdList(query);
        return new HashSet<>(idList).containsAll(ids);
    }

    @Override
    public void validate(Long id) {
        ModelVO model = modelMapper.selectModelById(id);
        ServiceUtil.assertion(model == null, "ID为%s的车型不存在", id);

        ServiceUtil.assertion(MathUtils.equals(model.getLowVoltage(), model.getFullVoltage()), "满电电压与亏电电压不允许相等");
    }

    @Override
    public boolean isUser(Long modelId, Long userId) {
        ModelVO model = modelMapper.selectModelById(modelId);
        return isUser(model, userId);
    }

    private boolean isUser(ModelVO model, Long userId) {
        if (model == null || model.getUserId() == null || userId == null) {
            return false;
        }
        return model.getUserId().equals(userId);
    }
}
