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

import com.ruoyi.bst.ad.domain.AdQuery;
import com.ruoyi.bst.ad.domain.AdVO;
import com.ruoyi.bst.ad.mapper.AdMapper;
import com.ruoyi.bst.ad.service.AdValidator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.collection.CollectionUtils;
import org.springframework.stereotype.Service;

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

@Service
public class AdValidatorImpl implements AdValidator {


    private final AdMapper adMapper;

    public AdValidatorImpl(AdMapper adMapper) {
        this.adMapper = adMapper;
    }

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

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

    // 是否可以操作运营区
    private boolean canOperate(List<Long> adIds) {

        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        if (CollectionUtils.isEmptyElement(adIds)) {
            return true;
        }

        // 查询广告
        AdQuery query = new AdQuery();
        query.setAdIds(adIds);
        query.setScope(true);
        List<AdVO> areaList = adMapper.selectAdList(query);
        Long userId = SecurityUtils.getUserId();

        // 判断是否可以操作广告
        for (Long adId : adIds) {
            AdVO ad = areaList.stream()
                    .filter(item -> item.getAdId().equals(adId))
                    .findFirst().orElse(null);

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

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

}
