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

import com.ruoyi.bst.store.domain.StoreQuery;
import com.ruoyi.bst.store.domain.StoreVO;
import com.ruoyi.bst.store.service.StoreService;
import com.ruoyi.bst.store.service.StoreValidator;
import com.ruoyi.bst.suit.domain.SuitQuery;
import com.ruoyi.bst.suit.domain.SuitVO;
import com.ruoyi.bst.suit.service.SuitService;
import com.ruoyi.bst.suit.service.SuitValidator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class SuitValidatorImpl implements SuitValidator {

    @Autowired
    private SuitService suitService;

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

    @Override
    public boolean canDeleteAll(List<Long> suitIds) {
        return canOperate(suitIds);
    }

    @Override
    public boolean canCheckForSuit(Long storeId) {
        return canOperate(Arrays.asList(storeId));
    }

    // 是否可以操作店铺
    private boolean canOperate(List<Long> suitIds) {
        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        if (CollectionUtils.isEmptyElement(suitIds)) {
            return true;
        }
        // 查询店铺
        SuitQuery query = new SuitQuery();
        query.setSuitIds(suitIds);
        query.setScope(true);
        List<SuitVO> SuitVOList = suitService.selectSuitList(query);
        Long userId = SecurityUtils.getUserId();

        // 判断是否可以操作店铺
        for (Long suitId : suitIds) {
            SuitVO suit = SuitVOList.stream()
                    .filter(item -> item.getSuitId().equals(suitId))
                    .findFirst().orElse(null);

            if (suit == null) {
                return false;
            }
            boolean canOperate = isMch(suit, userId);
            if (!canOperate) {
                return false;
            }
        }
        return true;
    }

    private boolean isMch(SuitVO suit, Long userId) {
        return suit != null && suit.getUserId() != null && suit.getUserId().equals(userId);
    }
}

