package com.sunxung.factoring.service.sys.flowable.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ValidatorUtil;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.ValidatorEntity.ValidatorType;
import com.sunxung.factoring.entity.sys.flowable.FlowActivityDefinition;
import com.sunxung.factoring.entity.sys.flowable.vo.SearchFlowActivityDefinition;
import com.sunxung.factoring.mapper.sys.flowable.FlowActivityDefinitionMapper;
import com.sunxung.factoring.service.sys.flowable.FlowActivityDefinitionService;

@Service
public class FlowActivityDefinitionServiceImpl implements FlowActivityDefinitionService {

    @Autowired
    private FlowActivityDefinitionMapper flowActDefMapper;

    @Override
    @Transactional
    public Boolean add(FlowActivityDefinition flowActDef) {
        ValidatorUtil.validator(ValidatorType.ADD, flowActDef);
        return flowActDefMapper.add(flowActDef) > 0;
    }

    @Override
    public GridPage<FlowActivityDefinition> findBySearch(SearchFlowActivityDefinition search) {
        if (null == search) {
            throw new ValidatorException(CodeUtil.FAIL, "列表分页条件不能为空！");
        }
        Page<FlowActivityDefinition> page = PageHelper.startPage(search.getPage(), search.getRows());
        List<FlowActivityDefinition> rows = flowActDefMapper.findBySearch(search);
        return new GridPage<>(search.getRows(), search.getPage(), page.getTotal(), rows);
    }

    @Override
    @Transactional
    public Boolean updateTimeLimit(Long id, Float timeLimit, boolean workingDay) {
        if (null == id) {
            throw new ValidatorException(CodeUtil.FAIL, "所选ID为空");
        }
        // timeLimit为空，代表无时间限制
        if (timeLimit != null && timeLimit > 1000) {
            throw new ValidatorException(CodeUtil.FAIL, "时限不能大于1000");
        }
        return flowActDefMapper.updateTimeLimit(id, timeLimit, workingDay) == 1;
    }

    @Override
    public FlowActivityDefinition get(Long id) {
        return flowActDefMapper.get(id);
    }

    @Override
    public FlowActivityDefinition getByProcActKey(String procDefId, String activityKey) {
        return flowActDefMapper.getByProcActKey(procDefId, activityKey);
    }

    @Override
    public FlowActivityDefinition getMaxTimeLimitByProcDefKeyActKey(String procDefKey, String activityKey) {
        return flowActDefMapper.getMaxTimeLimitByProcDefKeyActKey(procDefKey, activityKey);
    }
}
