package com.huigou.bpm.management.application.impl;

import com.huigou.bpm.management.application.ProcessVariableApplication;
import com.huigou.bpm.management.domain.model.ProcessVariable;
import com.huigou.bpm.management.domain.query.ProcessVariableQueryRequest;
import com.huigou.bpm.management.mapper.ProcessVariableMapper;
import com.huigou.bpm.management.repository.ProcessVariableRepository;
import com.huigou.data.domain.model.CommonDomainConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * @author yonghuan
 */
@Service
public class ProcessVariableApplicationImpl implements ProcessVariableApplication {

    private ProcessVariableRepository processVariableRepository;
    private ProcessVariableMapper processVariableMapper;

    @Autowired
    public void setProcessVariableRepository(ProcessVariableRepository processVariableRepository) {
        this.processVariableRepository = processVariableRepository;
    }

    @Autowired
    public void setProcessVariableMapper(ProcessVariableMapper processVariableMapper) {
        this.processVariableMapper = processVariableMapper;
    }

    @Override
    public ProcessVariable add(ProcessVariable variable) {
        checkCode(variable);
        return processVariableRepository.save(variable);
    }

    @Override
    public ProcessVariable updateById(ProcessVariable variable) {
        Assert.hasText(variable.getId(), CommonDomainConstants.ID_NOT_BLANK);
        checkCode(variable);
        return processVariableRepository.save(variable);
    }

    private void checkCode(ProcessVariable variable) {
        ProcessVariable variableInDb = processVariableRepository.findByProcdefIdAndCode(variable.getProcdefId(), variable.getCode());
        if(variableInDb == null) {
            return;
        }
        if (variable.isNew()) {
            Assert.isNull(variableInDb, CommonDomainConstants.CODE_NOT_DUPLICATE);
        } else {
            Assert.isTrue(variableInDb.getId().equals(variable.getId()), CommonDomainConstants.CODE_NOT_DUPLICATE);
        }
    }

    @Override
    public void deleteById(String id) {
        Assert.hasText(id, CommonDomainConstants.ID_NOT_BLANK);
        processVariableRepository.delete(id);
    }

    @Override
    public ProcessVariable findById(String id) {
        Assert.hasText(id, CommonDomainConstants.ID_NOT_BLANK);
        return processVariableRepository.findOne(id);
    }

    @Override
    public Page<?> sliceQuery(ProcessVariableQueryRequest queryRequest) {
        Assert.hasText(queryRequest.getProcdefId(), "流程定义id不能为空");
        return processVariableMapper.sliceQuery(queryRequest);
    }

    @Override
    public List<ProcessVariable> findByProcdefId(String procdefId) {
        return processVariableRepository.findByProcdefId(procdefId);
    }
}
