package com.sunxung.factoring.service.project.impl;

import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.CodeUtil;
import com.sunxung.factoring.component.util.ThreadLocalUtil;
import com.sunxung.factoring.component.util.ValidatorUtil;
import com.sunxung.factoring.entity.ValidatorEntity.ValidatorType;
import com.sunxung.factoring.entity.project.BusinessAssignee;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.mapper.project.BusinessAssigneeMapper;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BusinessAssigneeServiceImpl implements BusinessAssigneeService {

    @Autowired
    private BusinessAssigneeMapper assigneeMapper;

    @Override
    @Transactional
    public BusinessAssignee add(BusinessAssignee assignee) {
        ValidatorUtil.validator(ValidatorType.ADD, assignee);
        BusinessAssignee historic = assigneeMapper.getByBusiness(assignee.getBusinessKey(), assignee.getBusinessType(),
                assignee.getAssigneeType());
        if (null != historic) {
            throw new ValidatorException(CodeUtil.FAIL, "该流程业务处理人已存在，请联系管理员！");
        }
        User user = ThreadLocalUtil.getUser();
        if(user != null){
            assignee.setUserCreate(ThreadLocalUtil.getUser().getLoginName());
        }
        assigneeMapper.add(assignee);
        return assigneeMapper.get(assignee.getId());
    }

    @Override
    @Transactional
    public Boolean update(BusinessAssignee assignee) {
        ValidatorUtil.validator(ValidatorType.UPDATE, assignee);
        assignee.setUserModified(ThreadLocalUtil.getUser().getLoginName());
        return assigneeMapper.update(assignee) == 1;
    }

    @Override
    public BusinessAssignee getByBusiness(Long businessKey, String businessType, String assigneeType) {
        return assigneeMapper.getByBusiness(businessKey, businessType, assigneeType);
    }

    @Override
    public Long getIdByBusiness(Long businessKey, String businessType, String assigneeType) {
        BusinessAssignee assignee = assigneeMapper.getByBusiness(businessKey, businessType, assigneeType);
        return assignee != null ? assignee.getAssigneeId() : null;
    }

    @Override
    public String getCandidateByBusiness(Long businessKey, String businessType, String assigneeType) {
        BusinessAssignee assignee = assigneeMapper.getByBusiness(businessKey, businessType, assigneeType);
        return assignee != null ? assignee.getCandidateId() : null;
    }

    @Override
    public List<Long> findIdsByBusiness(Long businessKey, String businessType) {
        return assigneeMapper.findIdsByBusiness(businessKey, businessType);
    }
}
