package com.srs.routine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.doman.dto.ProcessResultDto;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.flowable.service.IFlowDefinitionService;
import com.srs.routine.domain.RtStuReentrySchool;
import com.srs.routine.mapper.RtStuReentrySchoolMapper;
import com.srs.routine.service.IRtStuReentrySchoolService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 复学申请记录Service业务层处理
 *
 * @author srs
 * @date 2024-07-05
 */
@Service
public class RtStuReentrySchoolServiceImpl extends ServiceImpl<RtStuReentrySchoolMapper, RtStuReentrySchool> implements IRtStuReentrySchoolService {
    @Autowired
    private RtStuReentrySchoolMapper rtStuReentrySchoolMapper;

    /**
     * 查询复学申请记录
     *
     * @param reentryId 复学申请记录主键
     * @return 复学申请记录
     */
    @Override
    public RtStuReentrySchool selectRtStuReentrySchoolByReentryId(Long reentryId) {
        return rtStuReentrySchoolMapper.selectRtStuReentrySchoolByReentryId(reentryId);
    }

    /**
     * 查询复学申请记录列表
     *
     * @param rtStuReentrySchool 复学申请记录
     * @return 复学申请记录
     */
    @Override
    public List<RtStuReentrySchool> selectRtStuReentrySchoolList(RtStuReentrySchool rtStuReentrySchool) {
        return rtStuReentrySchoolMapper.selectRtStuReentrySchoolList(rtStuReentrySchool);
    }

    /**
     * 新增复学申请记录
     *
     * @param rtStuReentrySchool 复学申请记录
     * @return 结果
     */
    @Override
    public int insertRtStuReentrySchool(RtStuReentrySchool rtStuReentrySchool) {
        rtStuReentrySchool.setCreateTime(DateUtils.getNowDate());
        rtStuReentrySchool.setCreateBy(SecurityUtils.getUsername());
        rtStuReentrySchool.setStuId(SecurityUtils.getUserId());
        int i = rtStuReentrySchoolMapper.insertRtStuReentrySchool(rtStuReentrySchool);

        if (rtStuReentrySchool.getSubmissionStatus() != null && rtStuReentrySchool.getSubmissionStatus() == 1) {
            // 开启工作流
            ProcessResultDto processResultDto = startReentrySchoolProcess(rtStuReentrySchool);

            if (processResultDto != null) {
                rtStuReentrySchool.setProcessInstanceId(processResultDto.getProcessInstanceId());
                rtStuReentrySchool.setDeployId(processResultDto.getDeploymentId());
            }

            return rtStuReentrySchoolMapper.updateRtStuReentrySchool(rtStuReentrySchool);
        }
        return i;
    }

    /**
     * 修改复学申请记录
     *
     * @param rtStuReentrySchool 复学申请记录
     * @return 结果
     */
    @Override
    public int updateRtStuReentrySchool(RtStuReentrySchool rtStuReentrySchool) {
        rtStuReentrySchool.setUpdateTime(DateUtils.getNowDate());
        rtStuReentrySchool.setUpdateBy(SecurityUtils.getUsername());
        return rtStuReentrySchoolMapper.updateRtStuReentrySchool(rtStuReentrySchool);
    }

    /**
     * 批量删除复学申请记录
     *
     * @param reentryIds 需要删除的复学申请记录主键
     * @return 结果
     */
    @Override
    public int deleteRtStuReentrySchoolByReentryIds(Long[] reentryIds) {
        return rtStuReentrySchoolMapper.deleteRtStuReentrySchoolByReentryIds(reentryIds);
    }

    /**
     * 删除复学申请记录信息
     *
     * @param reentryId 复学申请记录主键
     * @return 结果
     */
    @Override
    public int deleteRtStuReentrySchoolByReentryId(Long reentryId) {
        return rtStuReentrySchoolMapper.deleteRtStuReentrySchoolByReentryId(reentryId);
    }

    @Override
    public int editRtStuReentrySchool(RtStuReentrySchool rtStuReentrySchool) {
        rtStuReentrySchool.setUpdateTime(DateUtils.getNowDate());
        rtStuReentrySchool.setUpdateBy(SecurityUtils.getUsername());
        int i = rtStuReentrySchoolMapper.updateRtStuReentrySchool(rtStuReentrySchool);
        if (rtStuReentrySchool.getSubmissionStatus() != null && rtStuReentrySchool.getSubmissionStatus()==1) {
            // 开启工作流
            ProcessResultDto processResultDto = startReentrySchoolProcess(rtStuReentrySchool);

            if (processResultDto != null) {
                rtStuReentrySchool.setProcessInstanceId(processResultDto.getProcessInstanceId());
                rtStuReentrySchool.setDeployId(processResultDto.getDeploymentId());
            }
            return rtStuReentrySchoolMapper.updateRtStuReentrySchool(rtStuReentrySchool);
        } else {
            return i;
        }
    }

    @Override
    public RtStuReentrySchool getRtStuReentrySchoolByProcInsId(String procInsId) {
        return rtStuReentrySchoolMapper.selectOne(new LambdaQueryWrapper<RtStuReentrySchool>().eq(RtStuReentrySchool::getProcessInstanceId, procInsId));
    }

    @Override
    public List<RtStuReentrySchool> selectRtStuReentrySchoolListByXW(RtStuReentrySchool rtStuReentrySchool) {
        return rtStuReentrySchoolMapper.selectRtStuReentrySchoolListByXW(rtStuReentrySchool);
    }

    @Override
    public List<RtStuReentrySchool> selectRtStuReentrySchoolListByFdy(RtStuReentrySchool rtStuReentrySchool) {
        return rtStuReentrySchoolMapper.selectRtStuReentrySchoolListByFdy(rtStuReentrySchool);
    }

    @Autowired
    IFlowDefinitionService flowDefinitionService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

    private ProcessResultDto startReentrySchoolProcess(RtStuReentrySchool rtStuReentrySchool) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("reentryId", rtStuReentrySchool.getReentryId().toString());
        variables.put("stuUserId", rtStuReentrySchool.getStuId());
        variables.put("reentryType", rtStuReentrySchool.getReentryType());

        variables.put("approval", SecurityUtils.getUserId());
        variables.put("deptId", SecurityUtils.getDeptId());

        AjaxResult ajaxResult = flowDefinitionService.startProcessInstanceById("flow_9ffew1pj:5:390063", variables);
        String code = ajaxResult.get("code").toString();
        if (code.equals("200")) {

            Object obj = ajaxResult.get("data");
            ProcessResultDto dto = (ProcessResultDto) obj;

            // 操作工作流
            // 设置当前用户
            identityService.setAuthenticatedUserId(SecurityUtils.getUserId().toString());
            // 查询待办任务列表
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(dto.getProcessInstanceId())
                    .taskAssignee(SecurityUtils.getUserId().toString())
                    .active()
                    .list();
            // 保存审核结果到任务变量中
            variables.put("approved", true);
            // 完成待办任务列表
            for (Task task : tasks) {
                String taskId = task.getId();
                String reentryId = taskService.getVariable(taskId, "reentryId").toString();
                if (reentryId.equals(rtStuReentrySchool.getReentryId().toString())) {
                    taskService.complete(task.getId(), variables);
                }
            }

            return dto;
        } else {
            return null;
        }
    }
}
