package cn.gintone.service;

import cn.gintone.ErrorInfo;
import cn.gintone.controller.vo.VisitPageReqVO;
import cn.gintone.controller.vo.VisitSaveReqVO;
import cn.gintone.dal.VisitInfoMapper;
import cn.gintone.dal.VisitMapper;
import cn.gintone.entity.VisitDO;
import cn.gintone.entity.VisitInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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 VisitInfoMapper visitInfoMapper;

    @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);
        // 删除
        visitInfoMapper.delete(new UpdateWrapper<VisitInfoDO>()
                .lambda()
                .eq(VisitInfoDO::getVisitId, id)
        );
        visitMapper.deleteById(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);
    }

}