package com.srs.routine.service.impl;

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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.doman.dto.ProcessResultDto;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.WeChatUtil;
import com.srs.flowable.domain.StuDropOutSchool;
import com.srs.flowable.service.IFlowDefinitionService;
import com.srs.routine.domain.RtStuQuitSchool;
import com.srs.system.mapper.SysUserMapper;
import org.flowable.engine.IdentityService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.routine.mapper.RtStuDropOutSchoolMapper;
import com.srs.routine.domain.RtStuDropOutSchool;
import com.srs.routine.service.IRtStuDropOutSchoolService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 学生退学申请记录Service业务层处理
 *
 * @author LSD
 * @date 2024-06-20
 */
@Service
public class RtStuDropOutSchoolServiceImpl extends ServiceImpl<RtStuDropOutSchoolMapper, RtStuDropOutSchool> implements IRtStuDropOutSchoolService {
    @Autowired
    private RtStuDropOutSchoolMapper rtStuDropOutSchoolMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    public WeChatUtil weChatUtil;

    /**
     * 查询学生退学申请记录
     *
     * @param dropOutSchoolId 学生退学申请记录主键
     * @return 学生退学申请记录
     */
    @Override
    public RtStuDropOutSchool selectRtStuDropOutSchoolByDropOutSchoolId(Long dropOutSchoolId) {
        return rtStuDropOutSchoolMapper.selectRtStuDropOutSchoolByDropOutSchoolId(dropOutSchoolId);
    }

    /**
     * 查询学生退学申请记录列表
     *
     * @param rtStuDropOutSchool 学生退学申请记录
     * @return 学生退学申请记录
     */
    @Override
    public List<RtStuDropOutSchool> selectRtStuDropOutSchoolList(RtStuDropOutSchool rtStuDropOutSchool) {
        return rtStuDropOutSchoolMapper.selectRtStuDropOutSchoolList(rtStuDropOutSchool);
    }

    /**
     * 新增学生退学申请记录
     *
     * @param rtStuDropOutSchool 学生退学申请记录
     * @return 结果
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRtStuDropOutSchool(RtStuDropOutSchool rtStuDropOutSchool) {
        rtStuDropOutSchool.setCreateTime(DateUtils.getNowDate());
        rtStuDropOutSchool.setCreateBy(SecurityUtils.getUsername());
        int i = rtStuDropOutSchoolMapper.insertRtStuDropOutSchool(rtStuDropOutSchool);
        if (rtStuDropOutSchool.getSubmissionStatus() != null && rtStuDropOutSchool.getSubmissionStatus().equals("1")) {
            // 开启工作流
            ProcessResultDto processResultDto = startDropOutrocess(rtStuDropOutSchool);

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

            return rtStuDropOutSchoolMapper.updateRtStuDropOutSchool(rtStuDropOutSchool);
        }
        return i;
    }

    /**
     * 修改学生退学申请记录
     *
     * @param rtStuDropOutSchool 学生退学申请记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int editRtStuDropOutSchool(RtStuDropOutSchool rtStuDropOutSchool) {
        rtStuDropOutSchool.setUpdateTime(DateUtils.getNowDate());
        int i = rtStuDropOutSchoolMapper.updateRtStuDropOutSchool(rtStuDropOutSchool);
        if (rtStuDropOutSchool.getSubmissionStatus() != null && rtStuDropOutSchool.getSubmissionStatus().equals("1")) {
            // 开启工作流
            ProcessResultDto processResultDto = startDropOutrocess(rtStuDropOutSchool);

            if (processResultDto != null) {
                rtStuDropOutSchool.setProcessInstanceId(processResultDto.getProcessInstanceId());
                rtStuDropOutSchool.setDeployId(processResultDto.getDeploymentId());
            }
            return rtStuDropOutSchoolMapper.updateRtStuDropOutSchool(rtStuDropOutSchool);
        } else {
            return i;
        }
    }

    @Override
    public List<RtStuDropOutSchool> selectRtStuDropOutSchoolListByXW(RtStuDropOutSchool rtStuDropOutSchool) {
        return rtStuDropOutSchoolMapper.selectRtStuDropOutSchoolListByXW(rtStuDropOutSchool);
    }

    @Override
    public int updateRtStuDropOutSchool(RtStuDropOutSchool rtStuDropOutSchool) {
        rtStuDropOutSchool.setUpdateTime(DateUtils.getNowDate());
        rtStuDropOutSchool.setUpdateBy(SecurityUtils.getUsername());
        return rtStuDropOutSchoolMapper.updateRtStuDropOutSchool(rtStuDropOutSchool);
    }

    @Autowired
    IFlowDefinitionService flowDefinitionService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

    /**
     * 开启处分工作流
     *
     * @param rtStuDropOutSchool
     */
    private ProcessResultDto startDropOutrocess(RtStuDropOutSchool rtStuDropOutSchool) {

        Map<String, Object> variables = new HashMap<>();
        variables.put("dropOutSchoolId", rtStuDropOutSchool.getDropOutSchoolId().toString());
        variables.put("quitType", rtStuDropOutSchool.getDropOutType());
        variables.put("stuUserId", SecurityUtils.getUserId());

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

        AjaxResult ajaxResult = flowDefinitionService.startProcessInstanceById("flow_l2pt4vap:7:922504", 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);

            // 标记是否有任务被完成
            boolean taskCompleted = false;
            // 完成待办任务列表
            for (Task task : tasks) {
                String taskId = task.getId();
                String dropOutSchoolId = taskService.getVariable(taskId, "dropOutSchoolId").toString();
                if (dropOutSchoolId.equals(rtStuDropOutSchool.getDropOutSchoolId().toString())) {
                    taskService.complete(task.getId(), variables);
                    taskCompleted = true;
                }
            }

            // 所有相关任务完成后，发送企业微信消息
            if (taskCompleted) {
                try {
                    // 获取申请人信息
                    String applicantName = rtStuDropOutSchool.getStuName();
                    String politicalStatus = rtStuDropOutSchool.getPoliticalStatus();

                    SysUser sysUser = new SysUser();
                    sysUser.setRoleId(118L);
                    List<SysUser> sysUsers = sysUserMapper.selectAllocatedList(sysUser);

                    // 提取二级学院的书记的账号
                    List<String> userNames = sysUsers.stream()
                            .map(SysUser::getUserName)
                            .collect(Collectors.toList());

                    // 只有政治面貌是团员时才发送企业微信消息
                    if ("团员".equals(politicalStatus)) {
                        // 消息内容
                        String messageContent = "【退学申请】" + applicantName + "的退学申请已通过审核。";
                        int batchSize = 10;
                        for (int i = 0; i < userNames.size(); i += batchSize) {
                            List<String> batch = userNames.subList(i, Math.min(i + batchSize, userNames.size()));
                            // 拼接成"user1|user2|user3"格式
                            String toUser = String.join("|", batch);
                            // 调用企业微信发送消息方法
                            weChatUtil.sendTextMessage(toUser, messageContent);
                        }
                    }
                } catch (Exception e) {
                    log.error("发送企业微信消息失败：", e);
                }
            }

            return dto;
        } else {
            return null;
        }
    }

    /**
     * 批量删除学生退学申请记录
     *
     * @param dropOutSchoolIds 需要删除的学生退学申请记录主键
     * @return 结果
     */
    @Override
    public int deleteRtStuDropOutSchoolByDropOutSchoolIds(Long[] dropOutSchoolIds) {
        return rtStuDropOutSchoolMapper.deleteRtStuDropOutSchoolByDropOutSchoolIds(dropOutSchoolIds);
    }

    /**
     * 删除学生退学申请记录信息
     *
     * @param dropOutSchoolId 学生退学申请记录主键
     * @return 结果
     */
    @Override
    public int deleteRtStuDropOutSchoolByDropOutSchoolId(Long dropOutSchoolId) {
        return rtStuDropOutSchoolMapper.deleteRtStuDropOutSchoolByDropOutSchoolId(dropOutSchoolId);
    }

    @Override
    public RtStuDropOutSchool selectRtStuDropOutSchoolByprocInsId(String procInsId) {
        return rtStuDropOutSchoolMapper.selectOne(new LambdaQueryWrapper<RtStuDropOutSchool>().eq(RtStuDropOutSchool::getProcessInstanceId, procInsId));
    }


}
