package cn.iocoder.yudao.server.service;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.server.controller.admin.vo.FlowPageReqVO;
import cn.iocoder.yudao.server.controller.admin.vo.FlowSaveReqVO;
import cn.iocoder.yudao.server.dal.dataobject.FlowDO;
import cn.iocoder.yudao.server.dal.mysql.FlowMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

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

/**
 * 门户流程配置 Service 实现类
 *
 * @author 超级管理员
 */
@Service
@Validated
public class FlowServiceImpl implements FlowService {

    @Resource
    private FlowMapper flowMapper;

    @Override
    public Long createFlow(FlowSaveReqVO createReqVO) {
        // 插入
        FlowDO flow = BeanUtils.toBean(createReqVO, FlowDO.class);
        flow.setDeleted(false);
        flow.setStatus(0);
        flowMapper.insert(flow);
        // 返回
        return flow.getId();
    }

    @Override
    public void updateFlow(FlowSaveReqVO updateReqVO) {
        // 校验存在
        validateFlowExists(updateReqVO.getId());
        // 更新
        FlowDO updateObj = BeanUtils.toBean(updateReqVO, FlowDO.class);
        flowMapper.updateById(updateObj);
    }

    @Override
    public void deleteFlow(Long id) {
        // 校验存在
        validateFlowExists(id);
        // 删除
        flowMapper.deleteById(id);
    }

    private void validateFlowExists(Long id) {
        if (flowMapper.selectById(id) == null) {
            throw exception(new ErrorCode(1,"不存在"));
        }
    }

    @Override
    public FlowDO getFlow(Long id) {
        return flowMapper.selectById(id);
    }

    @Override
    public PageResult<FlowDO> getFlowPage(FlowPageReqVO pageReqVO) {
        return flowMapper.selectPage(pageReqVO);
    }

}