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.service.IFlowDefinitionService;
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.RtStuQuitSchoolMapper;
import com.srs.routine.domain.RtStuQuitSchool;
import com.srs.routine.service.IRtStuQuitSchoolService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 休学申请记录Service业务层处理
 *
 * @author LSD
 * @date 2024-06-12
 */
@Service
public class RtStuQuitSchoolServiceImpl extends ServiceImpl<RtStuQuitSchoolMapper, RtStuQuitSchool> implements IRtStuQuitSchoolService {
    @Autowired
    private RtStuQuitSchoolMapper rtStuQuitSchoolMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    public WeChatUtil weChatUtil;

    /**
     * 查询休学申请记录
     *
     * @param quitSchoolId 休学申请记录主键
     * @return 休学申请记录
     */
    @Override
    public RtStuQuitSchool selectRtStuQuitSchoolByQuitSchoolId(Long quitSchoolId) {
        return rtStuQuitSchoolMapper.selectRtStuQuitSchoolByQuitSchoolId(quitSchoolId);
    }

    /**
     * 查询休学申请记录列表
     *
     * @param rtStuQuitSchool 休学申请记录
     * @return 休学申请记录
     */
    @Override
    public List<RtStuQuitSchool> selectRtStuQuitSchoolList(RtStuQuitSchool rtStuQuitSchool) {
        return rtStuQuitSchoolMapper.selectRtStuQuitSchoolList(rtStuQuitSchool);
    }

    /**
     * 新增休学申请记录
     *
     * @param rtStuQuitSchool 休学申请记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertRtStuQuitSchool(RtStuQuitSchool rtStuQuitSchool) {
        rtStuQuitSchool.setCreateTime(DateUtils.getNowDate());
        rtStuQuitSchool.setCreateBy(SecurityUtils.getUsername());
        rtStuQuitSchool.setStuId(SecurityUtils.getUserId());
        int i = rtStuQuitSchoolMapper.insertRtStuQuitSchool(rtStuQuitSchool);

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

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

            return rtStuQuitSchoolMapper.updateRtStuQuitSchool(rtStuQuitSchool);
        }
        return i;
    }

    @Autowired
    IFlowDefinitionService flowDefinitionService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

    /**
     * 开启处分工作流
     *
     * @param rtStuQuitSchool
     */
    private ProcessResultDto startQuitProcess(RtStuQuitSchool rtStuQuitSchool) {

        Map<String, Object> variables = new HashMap<>();
        variables.put("quitSchoolId", rtStuQuitSchool.getQuitSchoolId().toString());
        variables.put("quitType", rtStuQuitSchool.getQuitType());
        variables.put("stuUserId", rtStuQuitSchool.getStuId());

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

        AjaxResult ajaxResult = flowDefinitionService.startProcessInstanceById("flow_vxuubvdh:20:962552", 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 quitSchoolId = taskService.getVariable(taskId, "quitSchoolId").toString();
                if (quitSchoolId.equals(rtStuQuitSchool.getQuitSchoolId().toString())) {
                    taskService.complete(task.getId(), variables);
                    taskCompleted = true;
                }
            }
            // 所有相关任务完成后，发送企业微信消息
            if (taskCompleted) {
                try {
                    // 获取申请人信息
                    String applicantName = rtStuQuitSchool.getStuName();
                    String politicalStatus = rtStuQuitSchool.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 rtStuQuitSchool 休学申请记录
     * @return 结果
     */
    @Override
    public int  editRtStuQuitSchool(RtStuQuitSchool rtStuQuitSchool) {
        rtStuQuitSchool.setUpdateTime(DateUtils.getNowDate());
        rtStuQuitSchool.setUpdateBy(SecurityUtils.getUsername());
        int i = rtStuQuitSchoolMapper.updateRtStuQuitSchool(rtStuQuitSchool);
        if (rtStuQuitSchool.getSubmissionStatus() != null && rtStuQuitSchool.getSubmissionStatus()==1) {
            // 开启工作流
            ProcessResultDto processResultDto = startQuitProcess(rtStuQuitSchool);

            if (processResultDto != null) {
                rtStuQuitSchool.setProcessInstanceId(processResultDto.getProcessInstanceId());
                rtStuQuitSchool.setDeployId(processResultDto.getDeploymentId());
            }
            return rtStuQuitSchoolMapper.updateRtStuQuitSchool(rtStuQuitSchool);
        } else {
            return i;
        }
    }

    @Override
    public int updateRtStuQuitSchool(RtStuQuitSchool rtStuQuitSchool) {
        rtStuQuitSchool.setUpdateTime(DateUtils.getNowDate());
        rtStuQuitSchool.setUpdateBy(SecurityUtils.getUsername());
        return rtStuQuitSchoolMapper.updateRtStuQuitSchool(rtStuQuitSchool);
    }

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

    /**
     * 删除休学申请记录信息
     *
     * @param quitSchoolId 休学申请记录主键
     * @return 结果
     */
    @Override
    public int deleteRtStuQuitSchoolByQuitSchoolId(Long quitSchoolId) {
        return rtStuQuitSchoolMapper.deleteRtStuQuitSchoolByQuitSchoolId(quitSchoolId);
    }

    @Override
    public RtStuQuitSchool getRtStuQuitSchoolByProcInsId(String procInsId) {
        return rtStuQuitSchoolMapper.selectOne(new LambdaQueryWrapper<RtStuQuitSchool>().eq(RtStuQuitSchool::getProcessInstanceId, procInsId));
    }

    @Override
    public List<RtStuQuitSchool> selectRtStuQuitSchoolListByXW(RtStuQuitSchool rtStuQuitSchool) {
        return rtStuQuitSchoolMapper.selectRtStuQuitSchoolListByXW(rtStuQuitSchool);
    }

    @Override
    public List<RtStuQuitSchool> selectRtStuQuitSchoolListByFdy(RtStuQuitSchool rtStuQuitSchool) {
        return rtStuQuitSchoolMapper.selectRtStuQuitSchoolListByFdy(rtStuQuitSchool);
    }

}
