package com.ruoyi.project.activiti.service.impl;

import com.github.pagehelper.Page;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.PageDomain;
import com.ruoyi.framework.web.page.TableSupport;
import com.ruoyi.project.activiti.domain.BizLeaveVo;
import com.ruoyi.project.activiti.mapper.AcSysUserMapper;
import com.ruoyi.project.activiti.mapper.BizLeaveMapper;
import com.ruoyi.project.activiti.service.IBizLeaveService;
import com.ruoyi.project.activiti.service.IBizTodoItemService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假业务Service业务层处理
 *
 * @author Xianlu Tech
 * @date 2019-10-11
 */
@Service
public class BizLeaveServiceImpl implements IBizLeaveService {


    @Autowired
    private BizLeaveMapper bizLeaveMapper;


    @Autowired
    private TaskService taskService;

    @Override
    public int insertBizLeave(BizLeaveVo bizLeave) {
        bizLeave.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        bizLeave.setCreateTime(DateUtils.getNowDate());
        return bizLeaveMapper.insertBizLeave(bizLeave);
    }

    @Override
    public int updateBizLeave(BizLeaveVo bizLeave) {
        bizLeave.setUpdateTime(DateUtils.getNowDate());
        return bizLeaveMapper.updateBizLeave(bizLeave);
    }

    @Override
    public BizLeaveVo get(Long id) {
        BizLeaveVo bizLeaveVo = bizLeaveMapper.selectBizLeaveById(id);
        return bizLeaveVo;
    }

    @Autowired
    private IdentityService identityService;

    @Autowired

    private RuntimeService runtimeService;

    @Autowired
    private FormService formService;


    @Autowired
    private IBizTodoItemService bizTodoItemService;

    @Override
    public void submitApply(BizLeaveVo entity, String applyUserId) {

        entity.setApplyUser(applyUserId);
        entity.setApplyTime(DateUtils.getNowDate());
        entity.setUpdateBy(applyUserId);
        bizLeaveMapper.updateBizLeave(entity);
        String businessKey = entity.getId().toString(); // 实体类 ID，作为流程的业务 key
        // 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
        identityService.setAuthenticatedUserId(applyUserId);
        ProcessInstance processInstance = runtimeService // 启动流程时设置业务 key
                .startProcessInstanceByKey("leave", businessKey);
        String processInstanceId = processInstance.getId();

        entity.setInstanceId(processInstanceId); // 建立双向关系
        bizLeaveMapper.updateBizLeave(entity);
        // 下一节点处理人待办事项
        bizTodoItemService.insertTodoItem(processInstanceId, entity, "leave");
    }


    @Autowired
    private AcSysUserMapper userMapper;

    @Override
    public List<BizLeaveVo> selectBizLeaveList(BizLeaveVo bizLeave) {


        // PageHelper 仅对第一个 List 分页
        Page<BizLeaveVo> list = (Page<BizLeaveVo>) bizLeaveMapper.selectBizLeaveList(bizLeave);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Page<BizLeaveVo> returnList = new Page<>();
        for (BizLeaveVo leave : list) {
            SysUser sysUser = userMapper.selectUserByLoginName(leave.getCreateBy());
            if (sysUser != null) {
                leave.setCreateUserName(sysUser.getUserName());
            }
            SysUser sysUser2 = userMapper.selectUserByLoginName(leave.getApplyUser());
            if (sysUser2 != null) {
                leave.setApplyUserName(sysUser2.getUserName());
            }
            // 当前环节
            if (StringUtils.isNotBlank(leave.getInstanceId())) {
                List<Task> taskList = taskService.createTaskQuery()
                        .processInstanceId(leave.getInstanceId())
//                        .singleResult();
                        .list();    // 例如请假会签，会同时拥有多个任务
                if (!CollectionUtils.isEmpty(taskList)) {
                    Task task = taskList.get(0);
                    leave.setTaskId(task.getId());
                    leave.setTaskName(task.getName());
                } else {
                    leave.setTaskName("已办结");
                }
            } else {
                leave.setTaskName("未启动");
            }
            returnList.add(leave);
        }
        returnList.setTotal(CollectionUtils.isEmpty(list) ? 0 : list.getTotal());
        returnList.setPageNum(pageNum);
        returnList.setPageSize(pageSize);
        return returnList;
    }

    @Override
    public int deleteBizLeaveByIds(List<String> ids) {
        return bizLeaveMapper.deleteBizLeaveByIds(ids);
    }


    @Override
    public List<BizLeaveVo> findTodoTasks(BizLeaveVo leave, String userId) {
        List<BizLeaveVo> results = new ArrayList<>();
        List<Task> tasks = new ArrayList<Task>();
        // 根据当前人的ID查询
        List<Task> todoList = taskService.createTaskQuery().processDefinitionKey("leave").taskAssignee(userId).list();
        // 根据当前人未签收的任务
        List<Task> unsignedTasks = taskService.createTaskQuery().processDefinitionKey("leave").taskCandidateUser(userId).list();
        // 合并
        tasks.addAll(todoList);
        tasks.addAll(unsignedTasks);
        // 根据流程的业务ID查询实体并关联
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            // 条件过滤 1
            if (StringUtils.isNotBlank(leave.getInstanceId()) && !leave.getInstanceId().equals(processInstanceId)) {
                continue;
            }
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            String businessKey = processInstance.getBusinessKey();
            BizLeaveVo leave2 = bizLeaveMapper.selectBizLeaveById(new Long(businessKey));

            // 条件过滤 2
            if (StringUtils.isNotBlank(leave.getType()) && !leave.getType().equals(leave2.getType())) {
                continue;
            }

            leave2.setTaskId(task.getId());
            leave2.setTaskName(task.getName());

            SysUser sysUser = userMapper.selectUserByLoginName(leave2.getApplyUser());
            leave2.setApplyUserName(sysUser.getUserName());

            results.add(leave2);
        }
        return results;
    }

    @Override
    public void taskComplete(Map<String,Object> map) {
        String taskId = map.get("taskId").toString();
        String instanceId = map.get("instanceId").toString();
        taskService.addComment(taskId,instanceId,"人事同意");
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userId = user.getUserId().toString();
        //设置代理人
        taskService.claim(taskId, userId);
        taskService.complete(taskId, map);

    }
    @Autowired
    private HistoryService historyService;

    @Override
    public List<BizLeaveVo> taskDoneList(BizLeaveVo bizLeave, SysUser sysUser) {
        List<BizLeaveVo> results = new ArrayList<>();
        String userId = sysUser.getUserId().toString();
        String groupId = sysUser.getDeptId().toString();
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processDefinitionKey("leave")
                .taskAssignee(userId)
                .finished()
                .orderByHistoricTaskInstanceEndTime()
                .desc()
                .list();
        // 根据流程的业务ID查询实体并关联
        for (HistoricTaskInstance instance : list) {
            String processInstanceId = instance.getProcessInstanceId();

            // 条件过滤 1
            if (StringUtils.isNotBlank(bizLeave.getInstanceId()) && !bizLeave.getInstanceId().equals(processInstanceId)) {
                continue;
            }

            HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();

            String businessKey = processInstance.getBusinessKey();
            BizLeaveVo leave2 = bizLeaveMapper.selectBizLeaveById(new Long(businessKey));

            // 条件过滤 2
            if (StringUtils.isNotBlank(bizLeave.getType()) && !bizLeave.getType().equals(leave2.getType())) {
                continue;
            }

            leave2.setTaskId(instance.getId());
            leave2.setTaskName(instance.getName());
            leave2.setDoneTime(instance.getEndTime());

            sysUser = userMapper.selectUserByLoginName(leave2.getApplyUser());
            leave2.setApplyUserName(sysUser.getUserName());

            results.add(leave2);
        }
        return results;
    }

}
