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.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.routine.domain.RtStuDisqualification;
import com.srs.routine.mapper.RtStuDisqualificationMapper;
import com.srs.routine.service.IRtStuDisqualificationService;
import com.srs.system.mapper.SysUserMapper;
import com.srs.system.service.ISysUserService;
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;
import java.util.stream.Collectors;

/**
 * 给予学生退学申请Service业务层处理
 *
 * @author LSD
 * @date 2024-07-31
 */
@Service
public class RtStuDisqualificationServiceImpl extends ServiceImpl<RtStuDisqualificationMapper, RtStuDisqualification> implements IRtStuDisqualificationService {
    @Autowired
    private RtStuDisqualificationMapper rtStuDisqualificationMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    public WeChatUtil weChatUtil;

    /**
     * 查询给予学生退学申请
     *
     * @param disqualificationId 给予学生退学申请主键
     * @return 给予学生退学申请
     */
    @Override
    public RtStuDisqualification selectRtStuDisqualificationByDisqualificationId(Long disqualificationId) {
        return rtStuDisqualificationMapper.selectRtStuDisqualificationByDisqualificationId(disqualificationId);
    }

    /**
     * 查询给予学生退学申请列表
     *
     * @param rtStuDisqualification 给予学生退学申请
     * @return 给予学生退学申请
     */
    @Override
    public List<RtStuDisqualification> selectRtStuDisqualificationList(RtStuDisqualification rtStuDisqualification) {
        return rtStuDisqualificationMapper.selectRtStuDisqualificationList(rtStuDisqualification);
    }



    /**
     * 修改给予学生退学申请
     *
     * @param rtStuDisqualification 给予学生退学申请
     * @return 结果
     */
    @Override
    public int updateRtStuDisqualification(RtStuDisqualification rtStuDisqualification) {
        rtStuDisqualification.setUpdateTime(DateUtils.getNowDate());
        return rtStuDisqualificationMapper.updateRtStuDisqualification(rtStuDisqualification);
    }

    /**
     * 批量删除给予学生退学申请
     *
     * @param disqualificationIds 需要删除的给予学生退学申请主键
     * @return 结果
     */
    @Override
    public int deleteRtStuDisqualificationByDisqualificationIds(Long[] disqualificationIds) {
        return rtStuDisqualificationMapper.deleteRtStuDisqualificationByDisqualificationIds(disqualificationIds);
    }

    /**
     * 删除给予学生退学申请信息
     *
     * @param disqualificationId 给予学生退学申请主键
     * @return 结果
     */
    @Override
    public int deleteRtStuDisqualificationByDisqualificationId(Long disqualificationId) {
        return rtStuDisqualificationMapper.deleteRtStuDisqualificationByDisqualificationId(disqualificationId);
    }

    @Override
    public int editRtStuDisqualification(RtStuDisqualification rtStuDisqualification) {
        rtStuDisqualification.setUpdateTime(DateUtils.getNowDate());
        rtStuDisqualification.setUpdateBy(SecurityUtils.getUsername());
        if (rtStuDisqualification.getSubmissionStatus() != null && rtStuDisqualification.getSubmissionStatus() == 1) {
            ProcessResultDto processResultDto = startDisqualificarocess(rtStuDisqualification);
            if (processResultDto != null) {
                rtStuDisqualification.setProcessInstanceId(processResultDto.getProcessInstanceId());
                rtStuDisqualification.setDeployId(processResultDto.getDeploymentId());
            }
        }
        return rtStuDisqualificationMapper.updateRtStuDisqualification(rtStuDisqualification);
    }

    @Override
    public RtStuDisqualification getRtStuDisqualificationByProcInsId(String procInsId) {
        return rtStuDisqualificationMapper.selectOne(new LambdaQueryWrapper<RtStuDisqualification>().eq(RtStuDisqualification::getProcessInstanceId, procInsId));
    }

    @Override
    public List<RtStuDisqualification> selectRtStuDisqualificationListByXW(RtStuDisqualification rtStuDisqualification) {
        return rtStuDisqualificationMapper.selectRtStuDisqualificationListByXW(rtStuDisqualification);
    }


    /**
     * 新增给予学生退学申请
     *
     * @param rtStuDisqualification 给予学生退学申请
     * @return 结果
     */
    @Override
    public int insertRtStuDisqualification(RtStuDisqualification rtStuDisqualification) {
        rtStuDisqualification.setCreateTime(DateUtils.getNowDate());
        rtStuDisqualification.setCreateBy(SecurityUtils.getUsername());
        String stuNo = rtStuDisqualification.getStuNo();
        SysUser sysUser = sysUserService.selectUserByUserName(stuNo);
        rtStuDisqualification.setStuId(sysUser.getUserId());
        int i = rtStuDisqualificationMapper.insertRtStuDisqualification(rtStuDisqualification);

        if (rtStuDisqualification.getSubmissionStatus() != null && rtStuDisqualification.getSubmissionStatus() == 1) {

            ProcessResultDto processResultDto = startDisqualificarocess(rtStuDisqualification);

            if (processResultDto != null) {

                rtStuDisqualification.setProcessInstanceId(processResultDto.getProcessInstanceId());

                rtStuDisqualification.setDeployId(processResultDto.getDeploymentId());
            }
            return rtStuDisqualificationMapper.updateRtStuDisqualification(rtStuDisqualification);
        }

       return i;
    }

    @Autowired
    IFlowDefinitionService flowDefinitionService;

    @Autowired
    TaskService taskService;

    @Autowired
    IdentityService identityService;

    /**
     * 开启处分工作流
     *
     * @param rtStuDisqualification
     */
    private ProcessResultDto startDisqualificarocess(RtStuDisqualification rtStuDisqualification) {

        Map<String, Object> variables = new HashMap<>();
        variables.put("disqualificationId", rtStuDisqualification.getDisqualificationId().toString());
        variables.put("stuUserId", rtStuDisqualification.getStuId());

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

        // todo 企业微信推送消息

        AjaxResult ajaxResult = flowDefinitionService.startProcessInstanceById("flow_8mod6d6a:17:915004", 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 disqualificationId = taskService.getVariable(taskId, "disqualificationId").toString();
                if (disqualificationId.equals(rtStuDisqualification.getDisqualificationId().toString())) {
                    taskService.complete(task.getId(), variables);
                    taskCompleted = true;
                }
            }
            // 所有相关任务完成后，发送企业微信消息
            if (taskCompleted) {
                try {
                    // 获取申请人信息
                    String applicantName = rtStuDisqualification.getStuName();
                    String politicalStatus = rtStuDisqualification.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;
        }
    }
}
