package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.controller.vo.VisitPageReqVO;
import cn.gintone.controller.vo.VisitSaveReqVO;
import cn.gintone.dal.VisitMapper;
import cn.gintone.entity.VisitDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 接口安全访问策略 Service 实现类
 *
 * @author 胡懿
 */
@Service
@Validated
public class VisitServiceImpl implements VisitService {

    @Resource
    private VisitMapper visitMapper;

    @Autowired
    private VisitInfoService visitInfoService;

    @Override
    public Long createVisit(VisitSaveReqVO createReqVO) {
        // 插入
        VisitDO visit = BeanUtils.toBean(createReqVO, VisitDO.class);
        visitMapper.insert(visit);
        // 返回
        return visit.getId();
    }

    @Override
    public void updateVisit(VisitSaveReqVO updateReqVO) {
        // 校验存在
        validateVisitExists(updateReqVO.getId());
        // 更新
        VisitDO updateObj = BeanUtils.toBean(updateReqVO, VisitDO.class);
        visitMapper.updateById(updateObj);
    }

    @Override
    public void deleteVisit(Long id) {
        // 校验存在
        validateVisitExists(id);
        // 删除
        visitMapper.deleteById(id);
        visitInfoService.deleteVisitInfo(id);
    }

    private void validateVisitExists(Long id) {
        if (visitMapper.selectById(id) == null) {
            throw exception(ErrorInfo.VISIT_NOT_EXISTS);
        }
    }

    @Override
    public VisitDO getVisit(Long id) {
        return visitMapper.selectById(id);
    }

    @Override
    public PageResult<VisitDO> getVisitPage(VisitPageReqVO pageReqVO) {
        return visitMapper.selectPage(pageReqVO);
    }

}