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

import com.ruoyi.bst.storeStaff.domain.StoreStaffQuery;
import com.ruoyi.bst.storeStaff.domain.StoreStaffVO;
import com.ruoyi.bst.storeStaff.mapper.StoreStaffMapper;
import com.ruoyi.bst.storeStaff.service.StoreStaffValidator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

@Service
public class StoreStaffValidatorImpl implements StoreStaffValidator {

    @Autowired
    private StoreStaffMapper storeStaffMapper;


    @Override
    public boolean canEdit(Long id) {
        return canView(Collections.singletonList(id));
    }

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

    @Override
    public void afterCheck(Long id) {
        ServiceUtil.assertion(id == null, "ID不能为空");
        StoreStaffVO vo = storeStaffMapper.selectStoreStaffById(id);
        ServiceUtil.assertion(vo == null, "ID为%s的运维员工数据不存在", id);

        // 校验用户是否重复绑定到一个运营区上
        this.checkRepeat(vo);
    }

    private void checkRepeat(StoreStaffVO vo) {
        if (vo == null || vo.getUserId() == null || vo.getStoreId() == null) {
            return;
        }
        StoreStaffQuery query = new StoreStaffQuery();
        query.setUserId(vo.getUserId());
        query.setStoreId(vo.getStoreId());
        query.setExcludeId(vo.getId());
        int count = storeStaffMapper.selectCount(query);
        ServiceUtil.assertion(count > 0, "用户%s已是%s的运维人员，请勿重复操作", vo.getUserId(), vo.getStoreId());
    }

    private boolean canView(List<Long> ids) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return true;
        }
        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        StoreStaffQuery query = new StoreStaffQuery();
        query.setIds(ids);
        query.setScope(true);
        List<Long> idList = storeStaffMapper.selectIdList(query);
        return new HashSet<>(idList).containsAll(ids);
    }



}
