package com.ruoyi.project.training.bccnew.service.impl;

import com.ruoyi.common.jpush.JiGuangPushService;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.training.bccnew.domain.TTsApprove;
import com.ruoyi.project.training.bccnew.domain.TTsNew;
import com.ruoyi.project.training.bccnew.mapper.*;
import com.ruoyi.project.training.bccnew.service.ITTsApproveService;
import com.ruoyi.project.training.bccnew.service.ITTsNewService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 导师带徒审批Service业务层处理
 *
 * @author ssy
 * @date 2024-06-25
 */
@Service
public class TTsApproveServiceImpl implements ITTsApproveService {
    @Autowired
    private TTsApproveMapper tTsApproveMapper;

    @Autowired
    private TTsFirstplanMapper tTsFirstplanMapper;

    @Autowired
    private TTsLjplanMapper tTsLjplanMapper;

    @Autowired
    private TTsYsplanMapper tTsYsplanMapper;

    @Autowired
    private TTsFlplanMapper tTsFlplanMapper;

    @Autowired
    private TTsFtplanMapper tTsFtplanMapper;

    @Autowired
    private ITTsNewService tTsNewService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;
    @Autowired
    private JiGuangPushService jiGuangPushService;


    /**
     * 查询导师带徒审批
     *
     * @param id 导师带徒审批ID
     * @return 导师带徒审批
     */
    @Override
    public TTsApprove selectTTsApproveById(Long id) {
        return tTsApproveMapper.selectTTsApproveById(id);
    }

    @Override
    public List<TTsApprove> selectTTsApproveByNewId(Long id) {
        return tTsApproveMapper.selectTTsApproveByNewId(id);
    }

    @Override
    public List<TTsApprove> selectTTsApproveByContentId(Long id) {
        return tTsApproveMapper.selectTTsApproveByContentId(id);
    }

    @Override
    public AjaxResult doApprove(Long id, String planType, Long userId, String userName, String processName) {
        TTsApprove tTsApprove = new TTsApprove();
        tTsApprove.setPlanType(planType);
        if (processName.equals("dsdtTraining")) {
            tTsApprove.setTrainingId(id);
        } else {
            tTsApprove.setContentId(id);
        }
        tTsApproveMapper.insertTTsApprove(tTsApprove);
        // 开始申请流程
        tTsApprove.setApNo(DateUtils.dateTimeNow() + userId);
        long businessKey = tTsApprove.getId();
        String applyUser = userId.toString();
        //开始工作流、监听
        Authentication.setAuthenticatedUserId(applyUser);//设置当前申请人
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyuser", applyUser);
//        variables.put("xyuser", sysUser.getUserId());
        TStaffmgr tStaffmgr = new TStaffmgr();
        tStaffmgr.setActualposts("24");
        tStaffmgr.setDeptId(103L);
        StringBuilder executor = new StringBuilder();
        for (SysUser user : userMapper.selectUserPost(tStaffmgr)) {
            executor.append(user.getUserId().toString()).append(",");
        }
        if (StringUtils.isNotEmpty(executor.toString())) {
            executor = new StringBuilder(executor.substring(0, executor.length() - 1));
        }
        jiGuangPushService.send("新的审批流程","您有一个导师带徒审批流程待完成，快去看看吧",executor.toString());
        variables.put("jluser", executor.toString());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey(processName, String.valueOf(businessKey), variables);
        tTsApprove.setProcessId(pi.getProcessInstanceId());
        tTsApprove.setApplicantName(userName);
        tTsApprove.setApplicant(userId.toString());
        tTsApprove.setApplicationTime(new Date());
        tTsApprove.setCreaterCode(userId.toString());
        tTsApprove.setCreatedate(new Date());
        tTsApproveMapper.updateTTsApprove(tTsApprove);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult handle(DevTask devTask, String username, String userId) {
        TTsApprove tTsApprove = devTask.gettTsApprove();
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String taskName = task.getName();//实例名
        String processInstancesId = task.getProcessInstanceId();
        TTsNew tTsNew = tTsApprove.gettTsNew();
        // 判断流程
        if ("1".equals(devTask.getCondition())) {
            devTask.setComment("通过");
        } else if ("0".equals(devTask.getCondition())) {
            devTask.setComment("拒绝");
        }
        // 处理流程节点
        Map<String, Object> param = new HashMap<>();
//        if (taskName.equals("学员确认")) {
//            tTsApprove.setStudentName(username);
//            tTsApprove.setStudentId(userId);
//            tTsApprove.setStudentConfirmTime(new Date());
//            param.put("condition1", "1");
//        }
        if (taskName.equals("装置经理")) {
            tTsApprove.setApproverName(username);
            tTsApprove.setApprover(userId);
            tTsApprove.setApproveTime(new Date());
            if (tTsNew.getPlanStatus() == 4)
                tTsNew.setPlanStatus(1L);
            if (tTsNew.getPlanStatus() == 5)
                tTsNew.setPlanStatus(3L);
            param.put("condition", devTask.getCondition());
        }
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()
                .claim(taskId, userId);
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        taskService.complete(taskId, param);
        tTsNewService.updateTTsNew(tTsNew);
        tTsApproveMapper.updateTTsApprove(tTsApprove);
        return AjaxResult.success();
    }


    /**
     * 查询导师带徒审批列表
     *
     * @param tTsApprove 导师带徒审批
     * @return 导师带徒审批
     */
    @Override
    public List<TTsApprove> selectTTsApproveList(TTsApprove tTsApprove) {
        return tTsApproveMapper.selectTTsApproveList(tTsApprove);
    }

    /**
     * 新增导师带徒审批
     *
     * @param tTsApprove 导师带徒审批
     * @return 结果
     */
    @Override
    public int insertTTsApprove(TTsApprove tTsApprove) {
        return tTsApproveMapper.insertTTsApprove(tTsApprove);
    }

    /**
     * 修改导师带徒审批
     *
     * @param tTsApprove 导师带徒审批
     * @return 结果
     */
    @Override
    public int updateTTsApprove(TTsApprove tTsApprove) {
        return tTsApproveMapper.updateTTsApprove(tTsApprove);
    }

    /**
     * 批量删除导师带徒审批
     *
     * @param ids 需要删除的导师带徒审批ID
     * @return 结果
     */
    @Override
    public int deleteTTsApproveByIds(Long[] ids) {
        return tTsApproveMapper.deleteTTsApproveByIds(ids);
    }

    /**
     * 删除导师带徒审批信息
     *
     * @param id 导师带徒审批ID
     * @return 结果
     */
    @Override
    public int deleteTTsApproveById(Long id) {
        return tTsApproveMapper.deleteTTsApproveById(id);
    }
}
