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

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.bst.areaJoin.domain.enums.AreaJoinPermission;
import com.ruoyi.bst.creditUser.domain.CreditUserQuery;
import com.ruoyi.bst.creditUser.domain.CreditUserVO;
import com.ruoyi.bst.creditUser.mapper.CreditUserMapper;
import com.ruoyi.bst.creditUser.service.CreditUserValidator;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;

@Service
public class CreditUserValidatorImpl implements CreditUserValidator {

    @Autowired
    private CreditUserMapper creditUserMapper;
    
    @Override
    public boolean hasPermission(List<Long> ids, AreaJoinPermission permission) {
        if (CollectionUtils.isEmptyElement(ids)) {
            return true;
        }
        if (SecurityUtils.isSysAdmin()) {
            return true;
        }
        
        CreditUserQuery query = new CreditUserQuery();
        query.setIds(ids);
        query.setScope(true);
        query.addAreaPermission(permission.getCode());
        List<Long> creditUserIds = creditUserMapper.selectIdList(query);
        return new HashSet<>(creditUserIds).containsAll(ids);
    }


    @Override
    public void validate(Long id) {
        CreditUserVO creditUser = creditUserMapper.selectCreditUserById(id);
        ServiceUtil.assertion(creditUser == null, "挂账用户不存在");

        // 判断是否重复挂账
        boolean isRepeat = this.isRepeat(creditUser.getUserId(), creditUser.getCreditId(), creditUser.getId());
        ServiceUtil.assertion(isRepeat, "挂账用户%s已存在%s中，请勿重复挂账", creditUser.getUserName(), creditUser.getCreditName());
        
    }


    private boolean isRepeat(Long userId, Long creditId, Long id) {
        if (userId == null || creditId == null) {
            return false;
        }
        CreditUserQuery query = new CreditUserQuery();
        query.setUserId(userId);
        query.setCreditId(creditId);
        query.setExcludeId(id);
        int count = creditUserMapper.selectCount(query);
        return count > 0;
    }

    
}
