package com.zt.plat.module.qms.business.config.service;

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

import java.util.*;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.pojo.PageParam;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.qms.business.config.controller.vo.*;
import com.zt.plat.module.qms.business.config.dal.dataobject.ConfigRuleDO;
import com.zt.plat.module.qms.business.config.dal.mapper.ConfigRuleMapper;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.diffList;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 规则配置 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class ConfigRuleServiceImpl implements ConfigRuleService {

    @Resource
    private ConfigRuleMapper configRuleMapper;

    @Override
    public ConfigRuleRespVO createConfigRule(ConfigRuleSaveReqVO createReqVO) {
        // 插入
        ConfigRuleDO configRule = BeanUtils.toBean(createReqVO, ConfigRuleDO.class);
        configRuleMapper.insert(configRule);
        // 返回
        return BeanUtils.toBean(configRule, ConfigRuleRespVO.class);
    }

    @Override
    public void updateConfigRule(ConfigRuleSaveReqVO updateReqVO) {
        // 校验存在
        validateConfigRuleExists(updateReqVO.getId());
        // 更新
        ConfigRuleDO updateObj = BeanUtils.toBean(updateReqVO, ConfigRuleDO.class);
        configRuleMapper.updateById(updateObj);
    }

    @Override
    public void deleteConfigRule(Long id) {
        // 校验存在
        validateConfigRuleExists(id);
        // 删除
        configRuleMapper.deleteById(id);
    }

    @Override
        public void deleteConfigRuleListByIds(List<Long> ids) {
        // 校验存在
        validateConfigRuleExists(ids);
        // 删除
        configRuleMapper.deleteByIds(ids);
        }

    private void validateConfigRuleExists(List<Long> ids) {
        List<ConfigRuleDO> list = configRuleMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(CONFIG_RULE_NOT_EXISTS);
        }
    }

    private void validateConfigRuleExists(Long id) {
        if (configRuleMapper.selectById(id) == null) {
            throw exception(CONFIG_RULE_NOT_EXISTS);
        }
    }

    @Override
    public ConfigRuleDO getConfigRule(Long id) {
        return configRuleMapper.selectById(id);
    }

    @Override
    public PageResult<ConfigRuleDO> getConfigRulePage(ConfigRulePageReqVO pageReqVO) {
        return configRuleMapper.selectPage(pageReqVO);
    }

}