package com.cf.imes.module.system.service.process;

import com.cf.imes.module.system.controller.admin.process.vo.processUser.ProcessAndUserSaveReqVO;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import com.cf.imes.module.system.dal.dataobject.process.ProcessUserDO;
import com.cf.imes.framework.common.util.object.BeanUtils;

import com.cf.imes.module.system.dal.mysql.process.ProcessUserMapper;

import java.util.List;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.PROCESS_USER_EXISTS;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.PROCESS_USER_NOT_EXISTS;

/**
 * 工序用户表 process_user Service 实现类
 *
 * @author 晨丰科技
 */
@Service
@Validated
public class ProcessUserServiceImpl implements ProcessUserService {

    @Resource
    private ProcessUserMapper processUserMapper;

    @Override
    public Long createProcessUser(ProcessAndUserSaveReqVO createReqVO) {
//        判断是否有
        if (processUserMapper.selectById(createReqVO.getProcessId(), createReqVO.getUserId()).size() != 0) {
            throw exception(PROCESS_USER_EXISTS);
        }
        // 插入
        ProcessUserDO processUser = BeanUtils.toBean(createReqVO, ProcessUserDO.class);
        processUserMapper.insert(processUser);
        // 返回
        return processUser.getProcessId();
    }

    @Override
    public void updateProcessUser(ProcessAndUserSaveReqVO updateReqVO) {
        // 校验存在
        if (processUserMapper.selectById(updateReqVO.getProcessId(), updateReqVO.getUserId()).size() != 0) {
            throw exception(PROCESS_USER_EXISTS);
        }
        // 更新
        ProcessUserDO updateObj = BeanUtils.toBean(updateReqVO, ProcessUserDO.class);
        processUserMapper.updateById(updateObj);
    }

    @Override
    public void deleteProcessUserByProcess(Long processId) {
        // 校验存在
//        validateProcessUserExists(processId);
        // 删除
        processUserMapper.deleteUserByProcessId(processId);
    }

    private void validateProcessUserExists(Long id) {
        if (processUserMapper.selectByProcessId(id).size() == 0) {
            throw exception(PROCESS_USER_NOT_EXISTS);
        }
    }

    @Override
    public List<ProcessUserDO> getProcessUser(Long id) {
        return processUserMapper.selectByProcessId(id);
    }


}