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

import com.aliyun.core.utils.StringUtils;
import com.ruoyi.bst.booth.domain.Booth;
import com.ruoyi.bst.booth.domain.BoothQuery;
import com.ruoyi.bst.booth.domain.BoothVO;
import com.ruoyi.bst.booth.mapper.BoothMapper;
import com.ruoyi.bst.booth.service.BoothValidator;
import com.ruoyi.bst.device.domain.DeviceQuery;
import com.ruoyi.bst.device.domain.DeviceVO;
import com.ruoyi.bst.storeStaff.domain.enums.StoreStaffPermission;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import org.springframework.stereotype.Service;

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

@Service
public class BoothValidatorImpl implements BoothValidator {

    private final BoothMapper boothMapper;

    public BoothValidatorImpl(BoothMapper boothMapper) {
        this.boothMapper = boothMapper;
    }

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

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

    @Override
    public void validate(Long boothId,String boothNo) {
        BoothVO booth = boothMapper.selectBoothByBoothId(boothId);
        ServiceUtil.assertion(booth == null, "卡座不存在");

        // 判断卡座编号是否重复
        this.validateNo(boothId, boothNo);
    }

    private void validateNo(Long boothId, String boothNo) {
        if (StringUtils.isBlank(boothNo)) {
            return;
        }
        BoothQuery query = new BoothQuery();
        query.setDeleted(false);
        query.setBoothId(boothId);
        query.setBoothNo(boothNo);
        int count = boothMapper.selectCount(query);
        ServiceUtil.assertion(count > 0,"卡座编号已存在");
    }


    // 是否可以操作卡座
    private boolean canOperate(List<Long> boothIds) {
        return hasPermission(boothIds);
    }

    // 是否有卡座权限
    private boolean hasPermission(List<Long> boothIds) {
        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        if (CollectionUtils.isEmptyElement(boothIds)) {
            return true;
        }
        // 查询卡座
        BoothQuery query = new BoothQuery();
        query.setIds(boothIds);
        query.setScope(true);
        query.addStorePermission(StoreStaffPermission.BOOTH_EDIT.getCode());
        List<Long> boothIdList = boothMapper.selectIdByQuery(query);
        return new HashSet<>(boothIdList).containsAll(boothIds);
    }

}
