package com.yd.csf.api.service.impl;

import com.yd.common.exception.BusinessException;
import com.yd.common.result.Result;
import com.yd.csf.api.service.ApiCommissionRuleBindingService;
import com.yd.csf.feign.request.rulebind.ApiCommissionRuleBindingRequest;
import com.yd.csf.service.model.CommissionRuleBinding;
import com.yd.csf.service.service.ICommissionRuleBindingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApiCommissionRuleBindingServiceImpl implements ApiCommissionRuleBindingService {

    @Resource
    private ICommissionRuleBindingService bindingService;

    /**
     * 保存基本法绑定信息
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveCommissionRuleBinding(ApiCommissionRuleBindingRequest request) {
        //校验入参参数
        verifyRuleBindingRequest(request);

        //通过目标ID删除记录
        bindingService.del(request.getTargetId());

        //新增基本法绑定记录
        List<CommissionRuleBinding> saveList = request.getRuleBizIdList()
                .stream()
                .map(ruleBizId -> {
                    CommissionRuleBinding binding = new CommissionRuleBinding();
                    BeanUtils.copyProperties(request,binding);
                    binding.setRuleBizId(ruleBizId);
                    return binding;
                }).collect(Collectors.toList());
        bindingService.saveOrUpdateBatch(saveList);
        return Result.success();
    }

    /**
     * 校验基本法绑定信息入参参数
     * @param request
     */
    public void verifyRuleBindingRequest(ApiCommissionRuleBindingRequest request){
        if (CollectionUtils.isEmpty(request.getRuleBizIdList())) {
            throw new BusinessException("基本法配置表唯一业务ID列表不能为空");
        }
        if (StringUtils.isBlank(request.getTargetType())) {
            throw new BusinessException("绑定目标类型不能为空");
        }
        if (StringUtils.isBlank(request.getTargetId())) {
            throw new BusinessException("绑定目标ID不能为空");
        }
        if (StringUtils.isBlank(request.getTargetName())) {
            throw new BusinessException("绑定目标名称不能为空");
        }
    }

}
