package cn.iocoder.yudao.module.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.base.constant.SchoolBaseConstants;
import cn.iocoder.yudao.module.base.mapper.DlDriveSchoolCourseMapper;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseService;
import cn.iocoder.yudao.module.base.entity.DriveSchoolCourseDeduct;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseDeductService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolStudentService;
import cn.iocoder.yudao.module.base.service.SchoolNotifyMessageSendService;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolCourseVO;
import cn.iocoder.yudao.module.course.entity.Process;
import cn.iocoder.yudao.module.course.entity.SchoolCommission;
import cn.iocoder.yudao.module.course.entity.SchoolCourseOrder;
import cn.iocoder.yudao.module.course.mapper.ProcessMapper;
import cn.iocoder.yudao.module.course.service.ProcessService;
import cn.iocoder.yudao.module.course.service.SchoolCommissionService;
import cn.iocoder.yudao.module.course.service.SchoolCourseOrderService;
import cn.iocoder.yudao.module.course.vo.*;
import cn.iocoder.yudao.module.exam.vo.ExamVO;
import cn.iocoder.yudao.module.exam.mapper.ExamBatchItemMapper;
import cn.iocoder.yudao.module.exam.vo.ExamBatchItemNewVO;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolDeduct;
import cn.iocoder.yudao.module.jx.service.IDriveSchoolDeductService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.module.base.utils.DriveSchoolBaseUtil.getSubjectStr;


/**
 * 学员课程进度 Service 实现类
 *
 * @author 若依
 */
@Service
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {
    @Autowired
    private ProcessMapper processMapper;
//        @Resource
//    private IDriveSchoolDeductService deductService;
    @Resource
    private AdminUserApi userApi;
    @Resource
    private SchoolCommissionService schoolCommissionService;

    @Resource
    private SchoolCourseOrderService schoolCourseOrderService;
    @Lazy
    @Resource
    private DlDriveSchoolStudentService dlDriveSchoolStudentService;
    @Autowired
    private ExamBatchItemMapper examBatchItemMapper;

    @Autowired
    private SchoolNotifyMessageSendService schoolNotifyMessageSendService;

    @Resource
    private DlDriveSchoolCourseService courseService;

    @Autowired
    private DlDriveSchoolCourseDeductService deductService;


    /**
     * 教练查自己带教的课程和科目
     *
     * @return java.util.List<cn.iocoder.yudao.module.course.entity.Process>
     * @author vinjor-M
     * @date 11:05 2025/1/15
     **/
    @Override
    public List<Process> getMyCourseAndSubject() {
        //当前教练ID
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        LambdaQueryWrapper<Process> queryWrapper = new LambdaQueryWrapper<Process>()
                .eq(Process::getCoachId, userId)
                .notIn(Process::getSubject, Arrays.asList(1, 4))
                //状态不等于2-已完成的科目
//                .ne(Process::getStatus, "2")
                .groupBy(Process::getCourseId).groupBy(Process::getSubject);
        return this.list(queryWrapper);
    }

    /**
     * 教练查自己带教的课程和科目在训练中的学生-并且是未送考的
     *
     * @param process
     * @param page
     * @author vinjor-M
     * @date 17:11 2025/1/15
     **/
    @Override
    public IPage<Process> getMyCourseStudentPage(Process process, Page<Process> page) {
        //当前教练ID
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        LambdaQueryWrapper<Process> queryWrapper = new LambdaQueryWrapper<Process>()
                .eq(Process::getCoachId, userId)
                .eq(Process::getCourseId, process.getCourseId())
                .eq(Process::getSubject, process.getSubject());
        if (StringUtils.isNotEmpty(process.getUserName())) {
            queryWrapper.like(Process::getUserName, process.getUserName());
        }
        //状态等于1-训练中的
        queryWrapper.eq(Process::getStatus, "1")
                .and(wrapper -> wrapper.isNull(Process::getExamStatus).or().eq(Process::getExamStatus, "0"))
                .groupBy(Process::getUserId)
                .orderByDesc(BaseDO::getCreateTime);
        return this.page(page, queryWrapper);
    }

    /**
     * 查某个学员在某个教练的某个课程、某个科目的学习进度（当前在练习中的）
     *
     * @param userId   学生id
     * @param courseId 课程id
     * @param subject  科目
     * @param coachId  教练id
     * @return cn.iocoder.yudao.module.course.entity.Process
     * @author vinjor-M
     * @date 18:39 2025/1/16
     **/
    @Override
    public Process getByStudentAndCourse(Long userId, String courseId, Integer subject, Long coachId, String examStatus) {
        LambdaQueryWrapper<Process> queryWrapper = new LambdaQueryWrapper<Process>()
                .eq(Process::getUserId, userId)
                .eq(Process::getCoachId, coachId)
                .eq(Process::getCourseId, courseId)
                .eq(Process::getSubject, subject)
                .eq(Process::getStatus, "1");
        if (null != examStatus) {
            queryWrapper.eq(Process::getExamStatus, examStatus);
        }
        queryWrapper.orderByDesc(BaseDO::getCreateTime);
        List<Process> processList = this.list(queryWrapper);
        return processList.isEmpty() ? null : processList.get(0);
    }

    /**
     * 查学生当下正在学习中的学习进度
     *
     * @param userId TODO
     * @return cn.iocoder.yudao.module.course.entity.Process
     * @author vinjor-M
     * @date 15:18 2025/2/8
     **/
    @Override
    public Process selectByUserId(Long userId, Long coachId) {
        return processMapper.selectNewMaxByUserId(userId, coachId);
    }

    /**
     * 查询教练 每个科目已毕未毕业学生数量
     *
     * @param coachId 教练id
     * @return java.util.Map<java.lang.String, java.lang.Integer>
     * @author vinjor-M
     * @date 13:52 2025/2/10
     **/
    @Override
    public Map<String, Integer> selectByCoachId(Long coachId) {
        LambdaQueryWrapper<Process> queryWrapper = new LambdaQueryWrapper<Process>()
                .eq(Process::getCoachId, coachId);
        List<Process> allList = this.list(queryWrapper);
        //所有科目二的记录
        List<Process> subject2List = allList.stream().filter(item -> 2 == item.getSubject()).collect(Collectors.toList());
        //所有科目三的记录
        List<Process> subject3List = allList.stream().filter(item -> 3 == item.getSubject()).collect(Collectors.toList());
        //科目二未毕业学员id
        Set<Long> subject2No = new HashSet<>();
        //科目二已毕业学员id
        Set<Long> subject2Over = new HashSet<>();
        for (Process item : subject2List) {
            if ("2".equals(item.getStatus())) {
                //已完成
                if ("1".equals(item.getExamStatus())) {
                    //已通过考试
                    subject2Over.add(item.getUserId());
                }
            } else {
                //未完成
                subject2No.add(item.getUserId());
            }
        }
        //科目三未毕业学员id
        Set<Long> subject3No = new HashSet<>();
        //科目三已毕业学员id
        Set<Long> subject3Over = new HashSet<>();
        for (Process item : subject3List) {
            if ("2".equals(item.getStatus())) {
                //已完成
                if ("1".equals(item.getExamStatus())) {
                    //已通过考试
                    subject3Over.add(item.getUserId());
                }
            } else {
                //未完成
                subject3No.add(item.getUserId());
            }
        }
        Map<String, Integer> rtnMap = new HashMap<>();
        rtnMap.put("subject2No", subject2No.size());
        rtnMap.put("subject2Over", subject2Over.size());
        rtnMap.put("subject3No", subject3No.size());
        rtnMap.put("subject3Over", subject3Over.size());
        return rtnMap;
    }

    /**
     * 查某学生某课程累计总训练时长
     *
     * @param userId   学生ID
     * @param courseId 课程ID
     * @return java.lang.Double
     * @author vinjor-M
     * @date 14:17 2025/2/11
     **/
    @Override
    public Double getAllTrainTime(Long userId, String courseId) {
        return processMapper.selectAllTrainTime(userId, courseId);
    }

    /**
     * 分页查询学员课程进度
     *
     * @param page      分页参数
     * @param pageReqVO {@link ProcessVO}
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.course.vo.ProcessVO>
     * @author PQZ
     * @date 15:34 2025/2/17
     **/
    @Override
    public IPage<ProcessVO> pageProcess(Page<ProcessVO> page, ProcessVO pageReqVO) {
        return processMapper.pageProcess(pageReqVO, page);
    }

    /**
     * 财务审核
     *
     * @param process {@link Process}
     * @author PQZ
     * @date 15:24 2025/2/18
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkProcess(Process process) {
        //查询数据
        Process oldProcess = getById(process.getId());
        //查询当前登录用户信息
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO sysUser = userApi.getUser(userId);
        //如果是通过审核，需要保存考试记录
        if (process.getFinancePass()) {
            //根据科目查询规则
            if (null != process.getSubject()) {
                // 根据课程id查询配置
                DriveSchoolCourseDeduct deduct = deductService.getOne(Wrappers.<DriveSchoolCourseDeduct>lambdaQuery()
                        .eq(DriveSchoolCourseDeduct::getCourseId, process.getCourseId())
                        .eq(DriveSchoolCourseDeduct::getCourseSubject, process.getSubject()));
                //如果存在提成规则则生成提成记录
                if (null != deduct) {
                    SchoolCommission schoolCommission = new SchoolCommission();
                    //教练用户表id
                    schoolCommission.setCoachUserId(oldProcess.getCoachId());
                    //教练名称
                    schoolCommission.setCoachName(oldProcess.getCoachName());
                    //学生id
                    schoolCommission.setStudentId(oldProcess.getUserId());
                    //学生姓名
                    schoolCommission.setStudentName(oldProcess.getUserName());
                    //提成金额
                    schoolCommission.setCommissionAmount(deduct.getDeduct());
                    //课程id
                    schoolCommission.setCourseId(oldProcess.getCourseId());
                    //科目
                    schoolCommission.setSubject(oldProcess.getSubject().toString());
                    //审核人id
                    schoolCommission.setCheckId(sysUser.getId());
                    //审核人姓名
                    schoolCommission.setCheckName(sysUser.getNickname());
                    schoolCommissionService.save(schoolCommission);
                }
            }
        }
        updateById(process);
    }

    /**
     * 保存学员课程进度
     *
     * @param request {@link ProcessAddVO}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveProcess(ProcessAddVO request) {
        List<Process> processes = BeanUtil.copyToList(request.getProcessList(), Process.class);
        // 获取学生id和课程id
        String courseId = processes.get(0).getCourseId();
        Long userId = processes.get(0).getUserId();
        // 根据课程id和学生id查询进度
        List<Process> list = list(Wrappers.lambdaQuery(Process.class)
                .eq(Process::getCourseId, courseId)
                .eq(Process::getUserId, userId));

        //判断传递进来的进度集合中的课程id和教练id和课程id是否与查询出来的一致，如果一致在processes集合中删除
        for (Process process : list) {
            processes.removeIf(process1 -> process.getCourseId().equals(process1.getCourseId())
                    && process.getCoachId().equals(process1.getCoachId())
                    && process.getSubject().equals(process1.getSubject()));
        }

        if (CollUtil.isEmpty(processes)) {
            return;
        }
        // 校验详细信息
        verify(processes);
        // 保存信息
        this.saveBatch(processes);

        // 修改订单信息中的是否分配教练状态
        schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getId, request.getOrderId())
                .set(SchoolCourseOrder::getIfAssignmentCoach, SchoolBaseConstants.SCHOOL_COURSE_ORDER_IS_ASSIGN_COACH));

        // 查询进度
        List<Process> processList = list(Wrappers.lambdaQuery(Process.class)
                .eq(Process::getCourseId, courseId)
                .eq(Process::getUserId, userId));

        Process process = processList.stream()
                .filter(p -> "1".equals(p.getStatus()))
                .findFirst()
                .orElse(null);

        if (process == null) {
            // 没有进行中的
            Process maxCompleted = processList.stream()
                    .filter(p -> "2".equals(p.getStatus()))
                    .max(Comparator.comparing(Process::getSubject))
                    .orElse(null);

            if (maxCompleted != null) {
                // 尝试找 subject == maxCompleted + 1 的
                Process next = processList.stream()
                        .filter(p -> p.getSubject().equals(maxCompleted.getSubject() + 1))
                        .findFirst()
                        .orElse(null);

                process = next != null ? next : maxCompleted;
            } else {
                // 没有已完成的，找 subject 最小的
                process = processList.stream()
                        .min(Comparator.comparing(Process::getSubject))
                        .orElse(null);
            }
            process.setStatus("1");
            //更新
            updateById(process);
        }


        // 发送通知内容
        String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_ASSIGN_COACH,
                request.getProcessList().get(0).getCoachName(),
                request.getProcessList().get(1).getCoachName(),
                request.getProcessList().get(2).getCoachName(),
                request.getProcessList().get(3).getCoachName());

        // 发送消息给学员
        schoolNotifyMessageSendService.sendMessage(userId, message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_MEMBER, null);

        // 发送消息给对应教练
        AdminUserRespDTO user = userApi.getUser(userId);
        String userName = user.getNickname();
        String userPhone = user.getMobile();
        String messageToCoach = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_ASSIGN_COACH_TO_COACH, userName, userPhone);
        schoolNotifyMessageSendService.sendMessage(request.getProcessList().get(0).getCoachId(), messageToCoach, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, null);

    }

    /**
     * 科目一、科目四考试成绩录入
     * @param process
     */
    @Override
    public void updateProcess(Process process) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
        String userName = user.getNickname();
        update(Wrappers.lambdaUpdate(Process.class)
                .eq(Process::getUserId, process.getUserId())
                .eq(Process::getSubject, process.getSubject())
                .eq(Process::getCourseId, process.getCourseId())
                .eq(Process::getTenantId, process.getTenantId())
                .eq(Process::getDeleted, SchoolBaseConstants.COMMON_NO)
//                .set(process.getUserName() != null, Process::getUserName, process.getUserName())
                .set(process.getExamStatus() != null, Process::getExamStatus, process.getExamStatus())
                .set(process.getExamScore() != null, Process::getExamScore, process.getExamScore())
                .set(Process::getExamNum, process.getExamNum() + 1)
                .set(process.getRemark() != null, Process::getRemark, process.getRemark())
                .set(process.getExamTime() != null, Process::getExamTime, process.getExamTime())
                .set(process.getImages() != null, Process::getImages, process.getImages()));

        // 如果考试通过，则修改进度状态为已完成
        if (process.getExamStatus() != null && process.getExamStatus().equals("1")) {
            update(Wrappers.lambdaUpdate(Process.class)
                    .eq(Process::getUserId, process.getUserId())
                    .eq(Process::getSubject, process.getSubject())
                    .eq(Process::getCourseId, process.getCourseId())
                    .eq(Process::getTenantId, process.getTenantId())
                    .eq(Process::getDeleted, SchoolBaseConstants.COMMON_NO)
                    .set(Process::getStatus, 2));
            // 发送消息给教练
            String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_EXAM_SCORE, userName, "科目一", process.getExamScore(), "已通过");
            schoolNotifyMessageSendService.sendMessage(process.getCoachId(), message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, process.getTenantId());
        } else if (process.getExamStatus() != null && !process.getExamStatus().equals("0")) {
            String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_EXAM_SCORE, userName, "科目一", process.getExamScore(), "未通过");
            schoolNotifyMessageSendService.sendMessage(process.getCoachId(), message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, process.getTenantId());
        }
        // 如果是科目一且通过考试，修改科目二状态
        if (process.getSubject() == 1 && process.getExamStatus().equals("1")) {

            update(Wrappers.lambdaUpdate(Process.class)
                    .eq(Process::getUserId, process.getUserId())
                    .eq(Process::getSubject, 2)
                    .eq(Process::getCourseId, process.getCourseId())
                    .eq(Process::getDeleted, SchoolBaseConstants.COMMON_NO)
                    .set(Process::getStatus, SchoolBaseConstants.PROCESS_STATUS_IN_PROGRESS));
        }
        // 如果是科目四且通过考试，修改学员考试通过状态
        if (process.getSubject() == 4 && process.getExamStatus().equals("1")) {
            dlDriveSchoolStudentService.updateStudentPassAndGradTime(process.getExamTime(), process.getUserId(), process.getCourseId(), process.getTenantId());
            String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_EXAM_SCORE, userName, "科目四", process.getExamScore(), "已通过");
            schoolNotifyMessageSendService.sendMessage(process.getCoachId(), message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, process.getTenantId());
        } else if (process.getSubject() == 4 && process.getExamStatus().equals("0")) {
            String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_EXAM_SCORE, userName, "科目四", process.getExamScore(), "未通过");
            schoolNotifyMessageSendService.sendMessage(process.getCoachId(), message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, process.getTenantId());
        }

    }

    /**
     * 根据用户id和课程id查询所有进度
     *
     * @param userId   用户id
     * @param courseId 课程id
     * @return java.util.List<cn.iocoder.yudao.module.course.vo.ProcessVO>
     */
    @Override
    public List<ProcessVO> getAllByUserIdAndCourseId(Long userId, String courseId) {
        if (null != userId && null != courseId) {
            List<Process> processList = processMapper.selectList(Wrappers.lambdaQuery(Process.class)
                    .eq(Process::getUserId, userId)
                    .eq(Process::getCourseId, courseId));
            return BeanUtil.copyToList(processList, ProcessVO.class);
        }
        return null;
    }

    /**
     * 根据userId查询考试列表
     *
     * @param userId 用户id
     */
    @Override
    public List<ProcessVO> getExamListByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        List<Process> processList = processMapper.selectList(
                Wrappers.lambdaQuery(Process.class)
                        .eq(Process::getUserId, userId)
                        .in(Process::getStatus, Arrays.asList("1", "2"))
                        .in(Process::getSubject, Arrays.asList(1, 4))
                        .isNotNull(Process::getExamScore)
        );
        return BeanUtil.copyToList(processList, ProcessVO.class);
    }

    /**
     * 根据userId查询考试列表
     *
     * @param userId 用户id
     */
    @Override
    public List<ExamVO> getExamListByUserIdTest(Long userId) {
        if (userId == null) {
            return Collections.emptyList();
        }
        List<Process> processList = processMapper.selectList(
                Wrappers.lambdaQuery(Process.class)
                        .eq(Process::getUserId, userId)
                        .in(Process::getStatus, Arrays.asList("1", "2"))
                        .in(Process::getSubject, Arrays.asList(1, 4))
                        .isNotNull(Process::getExamScore)
                        .orderByDesc(Process::getExamTime)
        );
        List<ExamVO> examBatchItemNew = examBatchItemMapper.selectExamByUserIdAndCoachId(userId, null);

        List<ExamVO> result = new ArrayList<>();
        result.addAll(BeanUtil.copyToList(processList, ExamVO.class));
        result.addAll(examBatchItemNew);
        return result;
    }

    private static void verify(List<Process> processes) {
        for (Process process : processes) {
            // 校验状态
            if (StrUtil.isBlank(process.getStatus())) {
                throw new RuntimeException("状态不能为空");
            }
            // 校验科目
            if (null == process.getSubject()) {
                throw new RuntimeException("科目不能为空");
            }
            if (StrUtil.isBlank(process.getCourseId())) {
                throw new RuntimeException("课程ID不能为空");
            }
            if (StrUtil.isBlank(process.getCourseName())) {
                throw new RuntimeException("课程名称不能为空");
            }
            if (null == process.getUserId()) {
                throw new RuntimeException("用户ID不能为空");
            }
            if (StrUtil.isBlank(process.getUserName())) {
                throw new RuntimeException("用户名称不能为空");
            }
            if (StrUtil.isBlank(process.getUserMobile())) {
                throw new RuntimeException("用户手机号不能为空");
            }
            if (null == process.getCoachId()) {
                throw new RuntimeException("教练ID不能为空");
            }
            if (StrUtil.isBlank(process.getCoachName())) {
                throw new RuntimeException("教练名称不能为空");
            }
        }
    }

    /**
     * 教练自招自动分配教练
     */
    @Override
    public void autoAssignCoach(ProcessNewVO request){
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserRespDTO user = userApi.getUser(userId);
//        String userName = user.getNickname();
        String userName= request.getUserName();
        String  mobile = user.getMobile();

        DlDriveSchoolCourseVO dlDriveSchoolCourseVO = courseService.queryDetailById(request.getCourseId());
        ProcessAddVO processVo = new ProcessAddVO();
        List<ProcessVO> processList = new ArrayList<>();

        for (int subject = 1; subject <= 4; subject++) {
            ProcessVO processVO = new ProcessVO();
            processVO.setSubject(subject);
            if(subject == 1){
                processVO.setStatus("1");
            }else{
                processVO.setStatus("0");
            }
            processVO.setUserId(userId);
            processVO.setCourseId(dlDriveSchoolCourseVO.getId());
            processVO.setCourseName(dlDriveSchoolCourseVO.getName());
            processVO.setCourseType(dlDriveSchoolCourseVO.getType());
            processVO.setUserName(userName);
            processVO.setUserMobile(mobile);
            processVO.setCoachId(request.getCoachId());
            processVO.setCoachName(request.getCoachName());
            processVO.setExamStatus(null);

            processList.add(processVO);
        }

        // 组装ProcessAddVO

        processVo.setProcessList(processList);
        ProcessAddVO processAddVO = new ProcessAddVO();
        processAddVO.setProcessList(processList);
        processAddVO.setOrderId(request.getOrderId());

        // 修改订单状态为已支付
        schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getId, request.getOrderId())
                .set(SchoolCourseOrder::getIfAssignmentCoach, SchoolBaseConstants.SCHOOL_COURSE_ORDER_IS_ASSIGN_COACH)
                .set(SchoolCourseOrder::getPaymentStatus, "2"));
        this.saveProcess(processAddVO);
    }

    @Override
    public ProcessAndExamBatchVO getProcessAndBatch(String id) {
        ProcessAndExamBatchVO processAndExamBatchVO = new ProcessAndExamBatchVO();
        Process process = processMapper.selectById(id);
        BeanUtils.copyProperties(process, processAndExamBatchVO);
        if (process != null) {
           String courseId = process.getCourseId();
           Long coachId = process.getCoachId();
           int subject = process.getSubject();
           double fraction = process.getExamScore();
           Long userId = process.getUserId();
           ProcessAndExamBatchVO processAndBatch = processMapper.getProcessAndBatch(courseId, coachId, subject, fraction, userId);

            if (processAndBatch != null) {
                processAndExamBatchVO.setBatchId(processAndBatch.getBatchId());
                processAndExamBatchVO.setBatchItemId(processAndBatch.getBatchItemId());
                processAndExamBatchVO.setAddr(processAndBatch.getAddr());
                processAndExamBatchVO.setAddrId(processAndBatch.getAddrId());
                processAndExamBatchVO.setTransWay(processAndBatch.getTransWay());
                processAndExamBatchVO.setStartTime(processAndBatch.getStartTime());
                processAndExamBatchVO.setEndTime(processAndBatch.getEndTime());AdminUserRespDTO user = userApi.getUser(userId);
            }
        }

        return processAndExamBatchVO;
    }

}
