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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.base.constant.SchoolBaseConstants;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolCourse;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolStudent;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCoachService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolStudentService;
import cn.iocoder.yudao.module.base.service.SchoolNotifyMessageSendService;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachRespVO;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolStudentVO;
import cn.iocoder.yudao.module.course.entity.Process;
import cn.iocoder.yudao.module.course.entity.SchoolCourseOrder;
import cn.iocoder.yudao.module.course.entity.SchoolCourseScheme;
import cn.iocoder.yudao.module.course.mapper.SchoolCourseOrderMapper;
import cn.iocoder.yudao.module.course.service.ProcessService;
import cn.iocoder.yudao.module.course.service.SchoolCourseOrderService;
import cn.iocoder.yudao.module.course.service.SchoolCourseSchemeService;
import cn.iocoder.yudao.module.course.vo.*;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
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.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 驾照报名订单 Service 实现类
 *
 * @author 若依
 */
@Service
@Validated
public class SchoolCourseOrderServiceImpl extends ServiceImpl<SchoolCourseOrderMapper, SchoolCourseOrder> implements SchoolCourseOrderService {

    @Resource
    private SchoolCourseOrderMapper schoolCourseOrderMapper;

    @Resource
    private ProcessService processService;

    @Autowired
    private SchoolNotifyMessageSendService schoolNotifyMessageSendService;

    @Resource
    private AdminUserApi userApi;
    @Resource
    @Lazy
    private RoleApi roleApi;

    @Lazy
    @Resource
    private DlDriveSchoolStudentService schoolStudentService;

    @Resource
    private SchoolCourseSchemeService schoolCourseSchemeService;

    @Resource
    private DlDriveSchoolCoachService dlDriveSchoolCoachService;


    @Override
    public String createSchoolCourseOrder(SchoolCourseOrderVO createReqVO) {
        // 插入
        SchoolCourseOrder schoolCourseOrder = BeanUtils.toBean(createReqVO, SchoolCourseOrder.class);
        schoolCourseOrderMapper.insert(schoolCourseOrder);
        // 返回
        return schoolCourseOrder.getId();
    }

    @Override
    public void updateSchoolCourseOrder(SchoolCourseOrderVO updateReqVO) {
        // 更新
        SchoolCourseOrder updateObj = BeanUtils.toBean(updateReqVO, SchoolCourseOrder.class);
        if(updateReqVO.getIsSign() != null){
            this.sendMessage(updateReqVO);
            this.updateSignTime(updateReqVO);
        }
        schoolCourseOrderMapper.updateById(updateObj);
    }

    // 判断是否面签，发送消息
    public void sendMessage(SchoolCourseOrderVO updateReqVO) {
        SchoolCourseOrder schoolCourseOrder = schoolCourseOrderMapper.selectById(updateReqVO.getId());
        DlDriveSchoolStudent studentByUserId = schoolStudentService.getStudentByUserId(Long.valueOf(updateReqVO.getUserId()));
        if(studentByUserId != null){
            if(("01".equals(studentByUserId.getSource()) || "04".equals(studentByUserId.getSource())) && studentByUserId.getSourceUserId() != null){
                if(schoolCourseOrder != null){
                    // 面签成功
                    if(schoolCourseOrder.getIsSign() == 0 && updateReqVO.getIsSign() == 1){
                        String messageToCoach = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_SIGN_TO_COACH, studentByUserId.getName());
                        schoolNotifyMessageSendService.sendMessage(studentByUserId.getSourceUserId(), messageToCoach, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN,updateReqVO.getTenantId());
                    } else if (schoolCourseOrder.getIsSign() == 1 && updateReqVO.getIsSign() == 0) {
                        // 取消面签
                        String messageToCoach = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_CANCEL_SIGN_TO_COACH, studentByUserId.getName());
                        schoolNotifyMessageSendService.sendMessage(studentByUserId.getSourceUserId(), messageToCoach, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN,updateReqVO.getTenantId());
                    } else if ("0".equals(schoolCourseOrder.getPaymentStatus()) && "2".equals(updateReqVO.getPaymentStatus())) {
                        // 支付成功
                        String messageToCoach = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_PAY_TO_MEMBER, studentByUserId.getName());
                        schoolNotifyMessageSendService.sendMessage(studentByUserId.getSourceUserId(), messageToCoach, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN,updateReqVO.getTenantId());
                    }
                }
            }

        }

    }

    /**
     * 更新面签时间
     * @param updateReqVO
     */
    public void updateSignTime(SchoolCourseOrderVO updateReqVO){
        SchoolCourseOrder schoolCourseOrder = schoolCourseOrderMapper.selectById(updateReqVO.getId());
        if(updateReqVO.getIsSign() == 1 && schoolCourseOrder != null && schoolCourseOrder.getIsSign() == 0){
            schoolCourseOrder.setSignTime(LocalDateTime.now());
            schoolCourseOrderMapper.updateById(schoolCourseOrder);
        }
        if(updateReqVO.getIsSign() == 0 && schoolCourseOrder != null && schoolCourseOrder.getIsSign() == 1){
            schoolCourseOrder.setSignTime(null);
            schoolCourseOrderMapper.updateById(schoolCourseOrder);
        }

    }

    @Override
    public void deleteSchoolCourseOrder(String id) {
        // 删除
        schoolCourseOrderMapper.deleteById(id);
    }


    @Override
    public SchoolCourseOrder getSchoolCourseOrder(String id) {
        return schoolCourseOrderMapper.selectById(id);
    }


    /**
     * 获得驾照报名订单分页
     *
     * @param page      分页参数
     * @param pageReqVO SchoolCourseOrderVO
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.course.vo.SchoolCommissionVO>
     * @author PQZ
     * @date 10:10 2025/2/25
     **/
    @Override
    public IPage<SchoolCourseOrderVO> queryPage(Page<SchoolCommissionVO> page, SchoolCourseOrderVO pageReqVO) {
        return schoolCourseOrderMapper.queryPage(pageReqVO, page);
    }

    @Override
    public IPage<SchoolCourseOrderVO> queryPageNew(Page<SchoolCommissionVO> page, SchoolCourseOrderVO pageReqVO) {
        return schoolCourseOrderMapper.queryPageNew(pageReqVO, page);
    }

    /**
     * 终止订单
     *
     * @param orderNo   订单号
     * @param endReason 终止原因
     * @param endTime   终止时间
     */
    @Override
    @Transactional
    public void endOrder(String orderNo, String endReason, LocalDateTime endTime) {
        // 修改订单表
        baseMapper.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getOrderNo, orderNo)
                .set(SchoolCourseOrder::getEndReason, endReason)
                .set(SchoolCourseOrder::getEndTime, endTime)
                .set(SchoolCourseOrder::getIfEnd, SchoolBaseConstants.COMMON_YES));

        // 查询学员信息
        SchoolCourseOrder schoolCourseOrder = baseMapper.selectOne(Wrappers.lambdaQuery(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getOrderNo, orderNo));

        // 删除学员未开始和训练中的科目
        /*processService.remove(Wrappers.lambdaQuery(Process.class)
                .eq(Process::getUserId, schoolCourseOrder.getUserId())
                .eq(Process::getCourseId, schoolCourseOrder.getCourseId())
                .and(q -> q.eq(Process::getStatus, SchoolBaseConstants.PROCESS_STATUS_NOT_START)
                         .or()
                        .eq(Process::getStatus, SchoolBaseConstants.PROCESS_STATUS_IN_PROGRESS))
        );*/

        DlDriveSchoolStudent studentByUserId = schoolStudentService.getStudentByUserId(Long.valueOf(schoolCourseOrder.getUserId()));
        if (studentByUserId != null) {
            // 如果为业务经理招生，发送消息给业务经理
            if("04".equals(studentByUserId.getSource()) && studentByUserId.getSourceUserId() != null){
                String messageToCoach = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_COURSE_END_TO_MEMBER, studentByUserId.getName(), endReason);
                schoolNotifyMessageSendService.sendMessage(studentByUserId.getSourceUserId(), messageToCoach, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN,schoolCourseOrder.getTenantId());
            }

        }

        // 准备消息内容
        String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_COURSE_END, schoolCourseOrder.getCourseName());

        // 发送消息给学员
        schoolNotifyMessageSendService.sendMessage(Long.valueOf(schoolCourseOrder.getUserId()), message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_MEMBER, schoolCourseOrder.getTenantId());

    }

    /**
     * 快速创建订单
     *
     * @param createReqVO 创建信息
     * @return 编号
     */
    @Override
    public String fastCreateSchoolCourseOrder(SchoolCourseOrderVO createReqVO) {
        // 根据订单id查询旧订单信息
        SchoolCourseOrder oldOrder = baseMapper.selectById(createReqVO.getId());

        if (oldOrder == null) {
            throw new RuntimeException("订单不存在");
        }

        // 检查是否需要更新进度记录
        boolean isCourseChanged = !oldOrder.getCourseId().equals(createReqVO.getCourseId());
        boolean isCoachChanged = !oldOrder.getCoachUserId().equals(createReqVO.getCoachUserId());
        if (isCourseChanged || isCoachChanged) {
            // 查询所有进度记录
            List<Process> processList = processService.lambdaQuery()
                    .eq(Process::getUserId, oldOrder.getUserId())
                    .eq(Process::getCourseId, oldOrder.getCourseId())
                    .list();

            if (!processList.isEmpty()) {
                for (Process process : processList) {
                    // 如果课程变化，更新课程信息
                    if (isCourseChanged) {
                        process.setCourseId(createReqVO.getCourseId());
                        process.setCourseName(createReqVO.getCourseName());
                    }
                    // 如果教练变化，更新教练信息
                    if (isCoachChanged) {
                        if (createReqVO.getCoachUserId() != null) {
                            process.setCoachId(Long.valueOf(createReqVO.getCoachUserId()));
                        }
                        process.setCoachName(createReqVO.getCoachUserName());
                    }
                    processService.updateById(process);
                }
            }
        }
        /*//判断新订单课程与旧订单课程是否一致
        if (!oldOrder.getCourseId().equals(createReqVO.getCourseId())) {
            // 查询所有进度
            List<Process> processList = processService.lambdaQuery()
                    .eq(Process::getUserId, oldOrder.getUserId())
                    .eq(Process::getCourseId, oldOrder.getCourseId())
                    .list();

            if (!processList.isEmpty()) {
                for (Process process : processList) {
                    // 更新课程ID
                    process.setCourseId(createReqVO.getCourseId());
                    // 更新课程名称
                    process.setCourseName(createReqVO.getCourseName());
                    // 更新教练ID
                    process.setCoachId(Long.valueOf(createReqVO.getCoachUserId()));
                    // 更新教练名称
                    process.setCoachName(createReqVO.getCoachUserName());
                    processService.updateById(process);
                }
            }
        }
        // 如果课程一直，判断教练是否一致
        if (!oldOrder.getCoachUserId().equals(createReqVO.getCoachUserId())) {
            // 查询所有进度
            List<Process> processList = processService.lambdaQuery()
                    .eq(Process::getUserId, oldOrder.getUserId())
                    .eq(Process::getCourseId, oldOrder.getCourseId())
                    .list();

            if (!processList.isEmpty()) {
                for (Process process : processList) {
                    // 更新教练ID
                    process.setCoachId(Long.valueOf(createReqVO.getCoachUserId()));
                    // 更新教练名称
                    process.setCoachName(createReqVO.getCoachUserName());
                    processService.updateById(process);
                }
            }
        }*/
        //判断新订单课程与旧订单课程是否一致
//        if (!oldOrder.getCourseId().equals(createReqVO.getCourseId())) {
//            // 删除学习记录表中的课程记录
//            processService.remove(Wrappers.lambdaQuery(Process.class)
//                    .eq(Process::getUserId, oldOrder.getUserId())
//                    .eq(Process::getCourseId, oldOrder.getCourseId()));
//        }

        // 查询新课程默认方案
        SchoolCourseScheme courseScheme = schoolCourseSchemeService.lambdaQuery().eq(SchoolCourseScheme::getCourseId, createReqVO.getCourseId()).eq(SchoolCourseScheme::getIsDefault, true).eq(SchoolCourseScheme::getDeleted, false).one();
        String schemeId = courseScheme != null ? courseScheme.getId() : null;
        SchoolCourseOrder schoolCourseOrder = BeanUtil.copyProperties(oldOrder, SchoolCourseOrder.class);
        schoolCourseOrder.setOldOrderId(oldOrder.getId());
        //生成订单号
        schoolCourseOrder.setOrderNo(generateOrderNumber());
        schoolCourseOrder.setCourseId(createReqVO.getCourseId());
        schoolCourseOrder.setCourseName(createReqVO.getCourseName());
        schoolCourseOrder.setCourseType(createReqVO.getCourseType());
        schoolCourseOrder.setCoachUserId(createReqVO.getCoachUserId());
        schoolCourseOrder.setCoachUserName(createReqVO.getCoachUserName());
        schoolCourseOrder.setSchemeId(schemeId);

        schoolCourseOrder.setId(null);
        schoolCourseOrder.setCreateTime(createReqVO.getCreateTime());
        schoolCourseOrder.setUpdateTime(LocalDateTime.now());
        schoolCourseOrder.setDeleted(SchoolBaseConstants.COMMON_NO);
        schoolCourseOrder.setIfAssignmentCoach(SchoolBaseConstants.SCHOOL_COURSE_ORDER_IS_ASSIGN_COACH);
        schoolCourseOrder.setIfEnd(SchoolBaseConstants.COMMON_NO);
        schoolCourseOrder.setEndReason(null);
        schoolCourseOrder.setEndTime(null);
        schoolCourseOrderMapper.insert(schoolCourseOrder);
        return null;
    }

    /**
     * 根据用户id获取订单信息
     *
     * @param loginUserId 用户id
     * @return List<SchoolCourseOrderVO>
     */
    @Override
    public List<SchoolCourseOrderVO> getCourseByLoginUser(Long loginUserId) {
        List<SchoolCourseOrder> list = list(Wrappers.lambdaQuery(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getUserId, loginUserId)
                .eq(SchoolCourseOrder::getIfEnd, SchoolBaseConstants.COMMON_NO)
                .eq(SchoolCourseOrder::getIfAssignmentCoach, SchoolBaseConstants.SCHOOL_COURSE_ORDER_IS_ASSIGN_COACH));
        return BeanUtil.copyToList(list, SchoolCourseOrderVO.class);
    }

    /**
     * 查询学员代报名且没有确认的订单
     * @param loginUserId
     * @return
     */
    public List<SchoolCourseOrderVO> getCourseIfProxyOrders(Long loginUserId) {
        List<SchoolCourseOrder> list = list(Wrappers.lambdaQuery(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getUserId, loginUserId)
                .eq(SchoolCourseOrder::getIfEnd, SchoolBaseConstants.COMMON_NO)
                .isNotNull(SchoolCourseOrder::getSignType)
                .isNotNull(SchoolCourseOrder::getIfAgree)
                .eq(SchoolCourseOrder::getIfAgree, 0)
                .eq(SchoolCourseOrder::getDeleted, SchoolBaseConstants.COMMON_NO));
        return BeanUtil.copyToList(list, SchoolCourseOrderVO.class);
    }

    /**
     * 根据获取订单信息
     *
     * @param userId 用户id
     * @return List<SchoolCourseOrderVO>
     */
    @Override
    public List<SchoolCourseOrderVO> getCourseByInfo(Long userId, String courseId) {
        List<SchoolCourseOrder> list = list(Wrappers.lambdaQuery(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getUserId, userId)
                .eq(SchoolCourseOrder::getCourseId, courseId)
                .eq(SchoolCourseOrder::getIfEnd, SchoolBaseConstants.COMMON_NO)
                .eq(SchoolCourseOrder::getIfAssignmentCoach, SchoolBaseConstants.SCHOOL_COURSE_ORDER_IS_ASSIGN_COACH));
        return BeanUtil.copyToList(list, SchoolCourseOrderVO.class);
    }

    /**
     * 报名之后发送对应消息
     */
    @Override
    public Boolean sendOrderMessage(String studentName, String courseName, Long coachId) {
        DlDriveSchoolCoachRespVO dlDriveSchoolCoachByUserId = dlDriveSchoolCoachService.getDlDriveSchoolCoachByUserId(coachId);
        Long tenantId = null;
        if(dlDriveSchoolCoachByUserId != null){
            tenantId = dlDriveSchoolCoachByUserId.getTenantId();
        }

        if (coachId != null) {
            // 准备消息内容
            String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_ENROLL, studentName, courseName);

            // 发送消息给教练
            schoolNotifyMessageSendService.sendMessage(coachId, message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, tenantId);
        }


        // 发送消息给所有办公室人员
//        Long tenantId = TenantContextHolder.getTenantId();
        List<UserDTO> officeStaffList = roleApi.selectUserListByRoleCode(tenantId, "bgs");

        if (officeStaffList != null && !officeStaffList.isEmpty()) {
            String officeMessage = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_ENROLL_TO_OFFICE, studentName, courseName);

            for (UserDTO staff : officeStaffList) {
                schoolNotifyMessageSendService.sendMessage(staff.getId(), officeMessage, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_ADMIN, tenantId);
            }
        }

        return Boolean.TRUE;
    }

    /**
     * 教练修改学员毕业时间
     */
    @Override
    public void updateStudentGradTime(String studentId, String gradTime) {
        Long coachId = SecurityFrameworkUtils.getLoginUserId();
        List<SchoolCourseOrder> students = schoolCourseOrderMapper.selectList(new LambdaQueryWrapper<SchoolCourseOrder>()
                .eq(SchoolCourseOrder::getUserId, studentId)
                .eq(SchoolCourseOrder::getCoachUserId, coachId)
                .orderByDesc(SchoolCourseOrder::getUpdateTime)
        );
        if (students != null && !students.isEmpty()) {
            SchoolCourseOrder latestStudent = students.get(0);

            // 字符串转 Date
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date gradTimeDate;
            try {
                gradTimeDate = sdf.parse(gradTime);
            } catch (ParseException e) {
                throw new RuntimeException("毕业时间格式错误，应为 yyyy-MM-dd", e);
            }

            SchoolCourseOrder updateEntity = new SchoolCourseOrder();
            updateEntity.setId(latestStudent.getId());
            updateEntity.setGradTime(gradTimeDate);

            schoolCourseOrderMapper.updateById(updateEntity);
        }
    }

    /**
     * 教练修改学员拿证时间
     */
    @Override
    public void updateStudentPassTime(String studentId, String passTime) {
        Long coachId = SecurityFrameworkUtils.getLoginUserId();
        List<SchoolCourseOrder> students = schoolCourseOrderMapper.selectList(new LambdaQueryWrapper<SchoolCourseOrder>()
                .eq(SchoolCourseOrder::getUserId, studentId)
                .eq(SchoolCourseOrder::getCoachUserId, coachId)
                .orderByDesc(SchoolCourseOrder::getUpdateTime)
        );
        if (students != null && !students.isEmpty()) {
            SchoolCourseOrder latestStudent = students.get(0);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date passTimeDate;
            try {
                passTimeDate = sdf.parse(passTime);
            } catch (ParseException e) {
                throw new RuntimeException("毕业时间格式错误，应为 yyyy-MM-dd", e);
            }

            SchoolCourseOrder updateEntity = new SchoolCourseOrder();
            updateEntity.setId(latestStudent.getId());
            updateEntity.setPassTime(passTimeDate);

            schoolCourseOrderMapper.updateById(updateEntity);
        }
    }

    public String generateOrderNumber() {
        return "ORDER" + UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    }

    public String generateOrderNum() {
        return "DBM" + UUID.randomUUID().toString().replace("-", "").substring(0, 10);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long businessManagerCreateSchoolCourseOrder(SchoolCourseOrderBusinessVO createReqVO) {
        DlDriveSchoolStudent studentByIdNo = schoolStudentService.getStudentByIdNo(createReqVO.getIdCard());
        Long userId = null;
        if (studentByIdNo == null) {
            DlDriveSchoolStudentVO dlDriveSchoolStudentVO = new DlDriveSchoolStudentVO();
            dlDriveSchoolStudentVO.setName(createReqVO.getUserName());
            dlDriveSchoolStudentVO.setAge(createReqVO.getAge());
            dlDriveSchoolStudentVO.setSource(createReqVO.getSource());
            dlDriveSchoolStudentVO.setSourceUserId(SecurityFrameworkUtils.getLoginUserId());
            dlDriveSchoolStudentVO.setSex(createReqVO.getUserSex());
            dlDriveSchoolStudentVO.setPhone(createReqVO.getUserPhone());
            dlDriveSchoolStudentVO.setIdCard(createReqVO.getIdCard());
            dlDriveSchoolStudentVO.setIdPhoto(createReqVO.getIdCardImage());
            dlDriveSchoolStudentVO.setRegistAddress(createReqVO.getAddress());
            String studentId = schoolStudentService.createDlDriveSchoolStudent(dlDriveSchoolStudentVO);
            DlDriveSchoolStudent dlDriveSchoolStudent = schoolStudentService.getDlDriveSchoolStudent(studentId);
            userId = dlDriveSchoolStudent.getUserId();
        } else {
            userId = studentByIdNo.getUserId();
        }

        createReqVO.setUserId(Math.toIntExact(userId));
        createReqVO.setOrderNo(generateOrderNum());
        schoolCourseOrderMapper.insert(createReqVO);
        return userId;


    }

    @Override
    public boolean updateOrderifAgree(List<String> orderIds) {
        if (CollectionUtils.isEmpty(orderIds)) {
            return false;
        }
        LambdaUpdateWrapper<SchoolCourseOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(SchoolCourseOrder::getId, orderIds)
                .set(SchoolCourseOrder::getIfAgree, 1);
        return this.update(updateWrapper);
    }

    /**
     * 根据学员id获取订单提成方案
     */
    @Override
    public String getSchemeByStudentId(Long studentId, String courseId, Integer subject) {
        return schoolCourseOrderMapper.getSchemeByStudentId(studentId, courseId, subject);
    }


    /**
     * 查询是否有订单使用该提成方案
     */
    @Override
    public Integer getOrderCountBySchemeId(String schemeId){
        return schoolCourseOrderMapper.getOrderCountBySchemeId(schemeId);
    }


    /**
     * 根据教练id获取对应招生
     */
    @Override
    public IPage<SchoolCourseOrderVO> getOrderByCoachId(SchoolCourseOrderVO pageReqVO, Page<SchoolCourseOrderVO> page) {
        String startTime = "";
        String endTime = "";
        if ("more".equals(pageReqVO.getTimeType())) {
            if (StringUtils.isNotEmpty(pageReqVO.getStartTimeStr())) {
                startTime = pageReqVO.getStartTimeStr() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(pageReqVO.getEndTimeStr())) {
                endTime = pageReqVO.getEndTimeStr() + " 23:59:59";
            }
        } else if ("month".equals(pageReqVO.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(pageReqVO.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        pageReqVO.setStartTimeStr(startTime);
        pageReqVO.setEndTimeStr(endTime);
        return schoolCourseOrderMapper.getOrderByCoachId(pageReqVO, page);
    }

    /**
     * 获取教练的订单总金额
     * @param pageReqVO
     * @return
     */
    @Override
    public List<SchoolCourseOrderVO> getCoachMoney(SchoolCourseOrderVO pageReqVO) {
        String startTime = "";
        String endTime = "";
        if ("more".equals(pageReqVO.getTimeType())) {
            if (StringUtils.isNotEmpty(pageReqVO.getStartTimeStr())) {
                startTime = pageReqVO.getStartTimeStr() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(pageReqVO.getEndTimeStr())) {
                endTime = pageReqVO.getEndTimeStr() + " 23:59:59";
            }
        } else if ("month".equals(pageReqVO.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(pageReqVO.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        pageReqVO.setStartTimeStr(startTime);
        pageReqVO.setEndTimeStr(endTime);
        return schoolCourseOrderMapper.getCoachMoney(pageReqVO);
    }

    /**
     * 获取教练的订单明细
     * @param pageReqVO
     * @return
     */
    @Override
    public IPage<SchoolCourseOrderVO> getOrderMoneyByCoachId(SchoolCourseOrderVO pageReqVO, Page<SchoolCourseOrderVO> page) {
        String startTime = "";
        String endTime = "";
        if ("more".equals(pageReqVO.getTimeType())) {
            if (StringUtils.isNotEmpty(pageReqVO.getStartTimeStr())) {
                startTime = pageReqVO.getStartTimeStr() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(pageReqVO.getEndTimeStr())) {
                endTime = pageReqVO.getEndTimeStr() + " 23:59:59";
            }
        } else if ("month".equals(pageReqVO.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(pageReqVO.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        pageReqVO.setStartTimeStr(startTime);
        pageReqVO.setEndTimeStr(endTime);
        return schoolCourseOrderMapper.getOrderMoneyByCoachId(pageReqVO, page);
    }

    /**
     * 获取需要导出的数据
     * @param exportVO
     * @param page
     * @return
     */
    @Override
    public IPage<CourseOrderExportVO> getOrderExportData(CourseOrderExportVO exportVO, Page<CourseOrderExportVO> page) {
        return schoolCourseOrderMapper.getOrderExportData(exportVO, page);
    }

    @Override
    public CourseOrderStatisticsVO getOrderStatistics(CourseOrderExportVO exportVO) {
        return schoolCourseOrderMapper.getOrderStatistics(exportVO);
    }

    /**
     * 导出的三种形式
     * @param exportVO
     * @return
     */
    @Override
    public List<CourseOrderExportVO> getOrderList(CourseOrderExportVO exportVO) {
        // 分页查询当前页
        Page<CourseOrderExportVO> page = new Page<>(exportVO.getPageNo(), exportVO.getPageSize());
        IPage<CourseOrderExportVO> result = schoolCourseOrderMapper.getOrderExportData(exportVO, page);
        return result.getRecords();
    }

    @Override
    public List<CourseOrderExportVO> getAllOrderList(CourseOrderExportVO exportVO) {
        // 不分页查询全部数据
        Page<CourseOrderExportVO> page = new Page<>(1, Integer.MAX_VALUE);
        IPage<CourseOrderExportVO> result = schoolCourseOrderMapper.getOrderExportData(exportVO, page);
        return result.getRecords();
    }

    @Override
    public List<CourseOrderExportVO> getOrderListByRange(CourseOrderExportVO exportVO) {
        List<CourseOrderExportVO> allData = new ArrayList<>();

        // 循环查询指定范围内的数据
        for (int i = exportVO.getStartPage(); i <= exportVO.getEndPage(); i++) {
            Page<CourseOrderExportVO> page = new Page<>(i, exportVO.getPageSize());
            IPage<CourseOrderExportVO> result = schoolCourseOrderMapper.getOrderExportData(exportVO, page);
            allData.addAll(result.getRecords());

            if (i >= result.getPages()) {
                break;
            }
        }
        return allData;
    }


    /**
     * 首页财务详细列表
     */
    @Override
    public List<FinanceInfoOnCoachAndStudent> getMoneyInfoOnFinance(FinanceInfoOnCoachAndStudent entity) {

        String startTime = "";
        String endTime = "";
        if ("more".equals(entity.getTimeType())) {
            if (StringUtils.isNotEmpty(entity.getStartTime())) {
                startTime = entity.getStartTime() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(entity.getEndTime())) {
                endTime = entity.getEndTime() + " 23:59:59";
            }
        } else if ("month".equals(entity.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(entity.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        entity.setStartTime(startTime);
        entity.setEndTime(endTime);
        return schoolCourseOrderMapper.getMoneyInfoOnFinance(entity);
    }

    @Override
    public IPage<FinanceInfoOnCoachAndStudent> getFinanceStudentByCoachId(FinanceInfoOnCoachAndStudent entity, Page<FinanceInfoOnCoachAndStudent> page) {

        String startTime = "";
        String endTime = "";
        if ("more".equals(entity.getTimeType())) {
            if (StringUtils.isNotEmpty(entity.getStartTime())) {
                startTime = entity.getStartTime() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(entity.getEndTime())) {
                endTime = entity.getEndTime() + " 23:59:59";
            }
        } else if ("month".equals(entity.getTimeType())) {
            //当月
            startTime = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTime = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(entity.getTimeType())) {
            //当天
            startTime = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTime = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        entity.setStartTime(startTime);
        entity.setEndTime(endTime);
        return schoolCourseOrderMapper.getFinanceStudentByCoachId(entity, page);
    }

}
