package com.bbd.bpm.listener;

import com.bbd.bpm.domain.BpmEmployee;
import com.bbd.bpm.repository.UserRepository;
import com.bbd.bpm.result.Result;
import com.bbd.bpm.service.UserInfoService;
import com.bbd.bpm.serviceImpl.UserInfoServiceImpl;
import com.bbd.bpm.util.ApplicationContextHolder;
import com.bbd.bpm.util.ContextUtils;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.el.FixedValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Optional;

/**
 * Created by houkang on 2019/1/28.
 */
@Component
public class PutAssigneeListener   implements Serializable, TaskListener {
    private FixedValue job;

    private FixedValue userId;

    private FixedValue department;

    private FixedValue company;



    @Override
    public void notify(DelegateTask delegateTask) {

        Object obj_userID = delegateTask.getVariable("userId");
        String userId = null;
        if(obj_userID != null ){
            userId = String.valueOf(obj_userID);
        }

        UserInfoServiceImpl userService =  ContextUtils.getBean(UserInfoServiceImpl.class);



        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();

        UserInfoService userInfoService = ApplicationContextHolder.getBean(UserInfoService.class).orElse(null);


        BpmEmployee bpmEmployee=new BpmEmployee();
        BpmEmployee bpmEmployee1=new BpmEmployee();
        if(job!=null){
            //判断职位是否为空
            if(!"".equals(job.getExpressionText())){
                bpmEmployee1.setPosition(job.getExpressionText());
                 bpmEmployee=userInfoService.getUserId(bpmEmployee1);
                //判断部门是否为空
                if(department!=null){
                    if(!"".equals(department.getExpressionText())){
                        //将部门和职位传值
                        bpmEmployee1.setDepartment(Integer.valueOf(department.getExpressionText()));
                        bpmEmployee=userInfoService.getUserId(bpmEmployee1);
                    }
                }
                //判断公司是否为空
                if(company!=null){
                    if(!"".equals(company.getExpressionText())){
                        //将部门 公司 和职位传值
                        bpmEmployee1.setCodeId(Integer.valueOf(company.getExpressionText()));
                        bpmEmployee=userInfoService.getUserId(bpmEmployee1);
                    }
                }
                //取出查到的userId 标识
                taskService.setAssignee(delegateTask.getId(),bpmEmployee.getUserCode());
            }
        }else{
            taskService.setAssignee(delegateTask.getId(),"hr");
        }
    }
}
