package cn.iocoder.yudao.module.system.service.agreement;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.system.controller.admin.agreement.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.agreement.AgreementDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.system.dal.mysql.agreement.AgreementMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 平台协议 Service 实现类
 *
 * @author dp
 */
@Service
@Validated
public class AgreementServiceImpl implements AgreementService {

    @Resource
    private AgreementMapper agreementMapper;

    @Override
    public Long createAgreement(AgreementSaveReqVO createReqVO) {
        // 插入
        AgreementDO agreement = BeanUtils.toBean(createReqVO, AgreementDO.class);
        agreementMapper.insert(agreement);
        // 返回
        return agreement.getId();
    }

    @Override
    public void updateAgreement(AgreementSaveReqVO updateReqVO) {
        // 校验存在
        validateAgreementExists(updateReqVO.getId());
        // 更新
        AgreementDO updateObj = BeanUtils.toBean(updateReqVO, AgreementDO.class);
        agreementMapper.updateById(updateObj);
    }

    @Override
    public void deleteAgreement(Long id) {
        // 校验存在
        validateAgreementExists(id);
        // 删除
        agreementMapper.deleteById(id);
    }

    private void validateAgreementExists(Long id) {
        if (agreementMapper.selectById(id) == null) {
            throw exception(AGREEMENT_NOT_EXISTS);
        }
    }

    @Override
    public AgreementDO getAgreement(Long id) {
        return agreementMapper.selectById(id);
    }

    @Override
    public AgreementDO getAgreementByType(Integer type) {
        LambdaQueryWrapper<AgreementDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AgreementDO::getType, type);
        return agreementMapper.selectOne(queryWrapper);
    }

    @Override
    public PageResult<AgreementDO> getAgreementPage(AgreementPageReqVO pageReqVO) {
        return agreementMapper.selectPage(pageReqVO);
    }

}