package com.zt.plat.module.base.service.businessrule;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.zt.plat.module.base.controller.admin.businessrule.vo.*;
import com.zt.plat.module.base.dal.dataobject.businessrule.BusinessRuleDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.base.dal.dao.businessrule.BusinessRuleMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.base.enums.ErrorCodeConstants.*;

/**
 * 业务规则 Service 实现类
 *
 * @author yangxiaofeng
 */
@Service
@Validated
public class BusinessRuleServiceImpl implements BusinessRuleService {

    @Resource
    private BusinessRuleMapper businessRuleMapper;

    @Override
    public BusinessRuleRespVO createBusinessRule(BusinessRuleSaveReqVO createReqVO) {
        // 插入
        BusinessRuleDO businessRule = BeanUtils.toBean(createReqVO, BusinessRuleDO.class);
        businessRuleMapper.insert(businessRule);
        // 返回
        return BeanUtils.toBean(businessRule, BusinessRuleRespVO.class);
    }

    @Override
    public void updateBusinessRule(BusinessRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessRuleExists(updateReqVO.getId());
        // 更新
        BusinessRuleDO updateObj = BeanUtils.toBean(updateReqVO, BusinessRuleDO.class);
        businessRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessRule(Long id) {
        // 校验存在
        validateBusinessRuleExists(id);
        // 删除
        businessRuleMapper.deleteById(id);
    }

    @Override
        public void deleteBusinessRuleListByIds(List<Long> ids) {
        // 校验存在
        validateBusinessRuleExists(ids);
        // 删除
        businessRuleMapper.deleteByIds(ids);
        }

    private void validateBusinessRuleExists(List<Long> ids) {
        List<BusinessRuleDO> list = businessRuleMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUSINESS_RULE_NOT_EXISTS);
        }
    }

    private void validateBusinessRuleExists(Long id) {
        if (businessRuleMapper.selectById(id) == null) {
            throw exception(BUSINESS_RULE_NOT_EXISTS);
        }
    }

    @Override
    public BusinessRuleDO getBusinessRule(Long id) {
        return businessRuleMapper.selectById(id);
    }

    @Override
    public PageResult<BusinessRuleDO> getBusinessRulePage(BusinessRulePageReqVO pageReqVO) {
        return businessRuleMapper.selectPage(pageReqVO);
    }

}