package com.trade.admin.workflow.service.impl;

import com.github.pagehelper.Page;
import com.trade.admin.workflow.service.FlowActivityDefinitionService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ValidatorException;
import com.trade.common.validate.ValidatorUtil;
import com.trade.common.validate.ValidatorGroup;
import com.trade.common.core.page.GridPage;
import com.trade.admin.workflow.dto.SearchFlowActivityDefinition;
import com.trade.admin.workflow.domain.FlowActivityDefinition;
import com.trade.admin.workflow.mapper.FlowActivityDefinitionMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.List;

@Service
public class FlowActivityDefinitionServiceImpl implements FlowActivityDefinitionService {

    @Resource(name = "flowActivityDefinitionMapper")
    private FlowActivityDefinitionMapper flowActDefMapper;

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

    @Override
    public GridPage<FlowActivityDefinition> findBySearch(SearchFlowActivityDefinition search) {
        if (null == search) {
            throw new ValidatorException(HttpStatus.ERROR, "列表分页条件不能为空！");
        }
        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(HttpStatus.ERROR, "所选ID为空");
        }
        // timeLimit为空，代表无时间限制
        if (timeLimit != null && timeLimit > 1000) {
            throw new ValidatorException(HttpStatus.ERROR, "时限不能大于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);
    }
}
