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

import com.ruoyi.bst.fault.domain.FaultQuery;
import com.ruoyi.bst.fault.domain.FaultVO;
import com.ruoyi.bst.fault.mapper.FaultMapper;
import com.ruoyi.bst.fault.service.FaultValidator;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class FaultValidatorImpl implements FaultValidator {

    @Autowired
    private FaultMapper faultMapper;

    @Override
    public boolean canEdit(Long faultId) {
        return canOperate(Arrays.asList(faultId));
    }

    private boolean canOperate(List<Long> faultIds) {
        if (SecurityUtils.isSysAdmin()){
            return true;
        }

        FaultQuery query = new FaultQuery();
        query.setId(faultIds.get(0));
        query.setScope(true);
        List<FaultVO> faultList = faultMapper.selectFaultList(query);
        Long userId = SecurityUtils.getUserId();

        // 判断是否可以处理故障
        for (Long faultId : faultIds) {
            FaultVO fault = faultList.stream()
                    .filter(item -> item.getId().equals(faultId))
                    .findFirst().orElse(null);
            if (fault == null) {
                return false;
            }
            boolean canOperate = isStore(fault, userId);
            if (!canOperate) {
                return false;
            }
        }
        return true;
    }

    private boolean isStore(FaultVO fault, Long userId) {
        return fault != null && fault.getStoreId() != null && fault.getStoreId().equals(userId);
    }
}
