package com.ruoyi.base.protocol.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.base.protocol.domain.Protocol;
import com.ruoyi.base.protocol.domain.bo.ProtocolBo;
import com.ruoyi.base.protocol.domain.vo.ProtocolVo;
import com.ruoyi.base.protocol.exception.ProtocolExceptionEnum;
import com.ruoyi.base.protocol.mapper.ProtocolMapper;
import com.ruoyi.base.protocol.service.IProtocolService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.BeanCopyUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 协议管理Service业务层处理
 *
 * @author xiechao
 * @date 2023-12-21
 */
@RequiredArgsConstructor
@Service
public class ProtocolServiceImpl implements IProtocolService {

    private final ProtocolMapper baseMapper;

    /**
     * 查询协议详情
     *
     * @param protocolCode 协议code
     * @return 协议
     */
    @Override
    public Protocol loadByProtocolCode(String protocolCode, Boolean tw){
        Protocol info = this.baseMapper.selectOne(new LambdaQueryWrapper<Protocol>()
            .eq(Protocol::getProtocolCode, protocolCode)
        );
        if(ObjectUtil.isNull(info) && tw){
            throw new ServiceException(ProtocolExceptionEnum.PROTOCOL_IS_NOT_EXISTS);
        }
        return info;
    }

    /**
     * 通过协议code查询协议信息
     *
     * @param protocolCode 协议code
     * @return 协议
     */
    @Override
    public ProtocolVo getByProtocolCode(String protocolCode) {
        //查询协议
        Protocol protocol= this.loadByProtocolCode(protocolCode,false);
        return BeanCopyUtils.copy(protocol, ProtocolVo.class);
    }

    /**
     * 保存协议信息
     * @param bo
     */
    @Override
    public Boolean save(ProtocolBo bo) {
        Protocol protocol = this.loadByProtocolCode(bo.getProtocolCode().toString(),false);
        if (ObjectUtil.isNull(protocol)) {
            protocol = BeanUtil.toBean(bo, Protocol.class);
        } else {
            BeanCopyUtils.copyPropertiesIgnoreNull(bo, protocol);
        }
       return   this.baseMapper.insertOrUpdate(protocol);
    }


}
