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

import java.math.BigDecimal;
import java.util.Collections;
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.AreaJoinQuery;
import com.ruoyi.bst.areaJoin.domain.AreaJoinVO;
import com.ruoyi.bst.areaJoin.mapper.AreaJoinMapper;
import com.ruoyi.bst.areaJoin.service.AreaJoinDashboard;
import com.ruoyi.bst.areaJoin.service.AreaJoinValidator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MathUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;

@Service
public class AreaJoinValidatorImpl implements AreaJoinValidator {

    @Autowired
    private AreaJoinMapper areaJoinMapper;

    @Autowired
    private AreaJoinDashboard areaJoinDashboard;

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

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

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

    @Override
    public void afterCheck(Long id) {
        ServiceUtil.assertion(id == null, "ID不能为空");
        AreaJoinVO vo = areaJoinMapper.selectAreaJoinById(id);
        ServiceUtil.assertion(vo == null, "ID为%s的加盟数据不存在", id);

        // 查询剩余可分配比例
        BigDecimal remainPoint = areaJoinDashboard.selectRemainPoint(vo.getId(), vo.getAreaId(), vo.getType(), vo.getMchPoint());

        // 判断分成比例是否高于剩余可分配比例
        if (MathUtils.biggerThan(vo.getPoint(), remainPoint)) {
            throw new ServiceException("分成比例【" + vo.getPoint() + "】不能高于剩余可分配比例【" + remainPoint + "】");
        }

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

    private void checkRepeat(AreaJoinVO vo) {
        if (vo == null || vo.getUserId() == null || vo.getAreaId() == null) {
            return;
        }
        AreaJoinQuery query = new AreaJoinQuery();
        query.setUserId(vo.getUserId());
        query.setAreaId(vo.getAreaId());
        query.setExcludeId(vo.getId());
        int count = areaJoinMapper.selectCount(query);
        ServiceUtil.assertion(count > 0, "用户%s已加盟运营区%s，请勿重复操作", vo.getUserId(), vo.getAreaId());
    }

}
