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

import com.ruoyi.bst.store.domain.StoreQuery;
import com.ruoyi.bst.store.mapper.StoreMapper;
import com.ruoyi.bst.store.service.StoreService;
import com.ruoyi.bst.store.service.StoreValidator;
import com.ruoyi.bst.storeStaff.domain.enums.StoreStaffPermission;
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.HashSet;
import java.util.List;

@Service
public class StoreValidatorImpl implements StoreValidator {

    @Autowired
    private StoreService storeService;
    @Autowired
    private StoreMapper storeMapper;

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

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

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

    private boolean hasPermission(List<Long> storeIds, String permission) {
        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        if (CollectionUtils.isEmptyElement(storeIds)) {
            return true;
        }
        // 查询运营区
        StoreQuery query = new StoreQuery();
        query.setStoreIds(storeIds);
        query.setScope(true);
        query.addStorePermission(permission);
        List<Long> areaIdList = storeMapper.selectIdByQuery(query);
        return new HashSet<>(areaIdList).containsAll(storeIds);
    }

    // 是否可以操作店铺
    private boolean canOperate(List<Long> storeIds) {
        return hasPermission(storeIds, StoreStaffPermission.STORE_EDIT.getCode());
    }

}

