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

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.businessalgorithm.vo.*;
import com.zt.plat.module.base.dal.dataobject.businessalgorithm.BusinessAlgorithmDO;
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.businessalgorithm.BusinessAlgorithmMapper;
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 BusinessAlgorithmServiceImpl implements BusinessAlgorithmService {

    @Resource
    private BusinessAlgorithmMapper businessAlgorithmMapper;

    @Override
    public BusinessAlgorithmRespVO createBusinessAlgorithm(BusinessAlgorithmSaveReqVO createReqVO) {
        // 插入
        BusinessAlgorithmDO businessAlgorithm = BeanUtils.toBean(createReqVO, BusinessAlgorithmDO.class);
        businessAlgorithmMapper.insert(businessAlgorithm);
        // 返回
        return BeanUtils.toBean(businessAlgorithm, BusinessAlgorithmRespVO.class);
    }

    @Override
    public void updateBusinessAlgorithm(BusinessAlgorithmSaveReqVO updateReqVO) {
        // 校验存在
        validateBusinessAlgorithmExists(updateReqVO.getId());
        // 更新
        BusinessAlgorithmDO updateObj = BeanUtils.toBean(updateReqVO, BusinessAlgorithmDO.class);
        businessAlgorithmMapper.updateById(updateObj);
    }

    @Override
    public void deleteBusinessAlgorithm(Long id) {
        // 校验存在
        validateBusinessAlgorithmExists(id);
        // 删除
        businessAlgorithmMapper.deleteById(id);
    }

    @Override
        public void deleteBusinessAlgorithmListByIds(List<Long> ids) {
        // 校验存在
        validateBusinessAlgorithmExists(ids);
        // 删除
        businessAlgorithmMapper.deleteByIds(ids);
        }

    private void validateBusinessAlgorithmExists(List<Long> ids) {
        List<BusinessAlgorithmDO> list = businessAlgorithmMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(BUSINESS_ALGORITHM_NOT_EXISTS);
        }
    }

    private void validateBusinessAlgorithmExists(Long id) {
        if (businessAlgorithmMapper.selectById(id) == null) {
            throw exception(BUSINESS_ALGORITHM_NOT_EXISTS);
        }
    }

    @Override
    public BusinessAlgorithmDO getBusinessAlgorithm(Long id) {
        return businessAlgorithmMapper.selectById(id);
    }

    @Override
    public PageResult<BusinessAlgorithmDO> getBusinessAlgorithmPage(BusinessAlgorithmPageReqVO pageReqVO) {
        return businessAlgorithmMapper.selectPage(pageReqVO);
    }

}