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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.common.BaseConstants;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.base.constant.SchoolBaseConstants;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolCoach;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolStudent;
import cn.iocoder.yudao.module.base.mapper.DlDriveSchoolStudentMapper;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCoachService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolStudentService;
import cn.iocoder.yudao.module.base.service.SchoolNotifyMessageSendService;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolStaffVO;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolStudentVO;
import cn.iocoder.yudao.module.base.vo.DriveSchoolStudentExportVo;
import cn.iocoder.yudao.module.base.vo.StudentCountVO;
import cn.iocoder.yudao.module.constant.InspectionConstants;
import cn.iocoder.yudao.module.course.entity.Process;
import cn.iocoder.yudao.module.course.entity.SchoolCourseOrder;
import cn.iocoder.yudao.module.course.service.ProcessService;
import cn.iocoder.yudao.module.course.service.SchoolCourseOrderService;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.inspection.entity.InspectionFile;
import cn.iocoder.yudao.module.inspection.service.IInspectionFileService;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCourseOrder;
import cn.iocoder.yudao.module.jx.utils.uuid.UUID;
import cn.iocoder.yudao.module.staff.service.UniqueCodeService;
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 cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.time.LocalDate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.config.CommonStr.USER_TYPE_CUS;

/**
 * 驾校学员 Service 实现类
 *
 * @author pqz
 */
@Service
@Validated
public class DlDriveSchoolStudentServiceImpl extends ServiceImpl<DlDriveSchoolStudentMapper, DlDriveSchoolStudent> implements DlDriveSchoolStudentService {

    @Resource
    private DlDriveSchoolStudentMapper dlDriveSchoolStudentMapper;

    @Resource
    private ProcessService processService;

    @Resource
    private SchoolCourseOrderService schoolCourseOrderService;

    @Resource
    private SchoolNotifyMessageSendService schoolNotifyMessageSendService;

    @Resource
    private UniqueCodeService uniqueCodeService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DlDriveSchoolCoachService dlDriveSchoolCoachService;

    @Autowired
    private IInspectionFileService inspectionFileService;

    @Autowired
    private AdminUserService userService;

    @Override
    public String createDlDriveSchoolStudent(DlDriveSchoolStudentVO createReqVO) {
        // 插入
        DlDriveSchoolStudent dlDriveSchoolStudent = BeanUtils.toBean(createReqVO, DlDriveSchoolStudent.class);
        DlDriveSchoolStudent studentByIdCard = this.getStudentByIdCard(dlDriveSchoolStudent.getUserId());

        //查询当前学生的手机号是否存在users表中
        AdminUserRespDTO userByMobile = adminUserApi.getUserByMobile(dlDriveSchoolStudent.getPhone());
        //如果存在直接将userId赋值
        if (ObjectUtil.isNotEmpty(userByMobile)) {
            dlDriveSchoolStudent.setUserId(userByMobile.getId());
        } else {
            // 如果不存在则创建用户
            UserDTO userDTO = new UserDTO();
            userDTO.setMobile(dlDriveSchoolStudent.getPhone());
            userDTO.setUsername(dlDriveSchoolStudent.getPhone());
            userDTO.setPassword(BaseConstants.PASSWORD_DEFAULT);
            userDTO.setNickname(dlDriveSchoolStudent.getName());
            userDTO.setSex(dlDriveSchoolStudent.getSex());
            userDTO.setUserType(USER_TYPE_CUS);
            Long user = adminUserApi.createUser(userDTO);
            dlDriveSchoolStudent.setUserId(user);
        }

        if (studentByIdCard == null) {
            // 生成唯一推广码
            String uniqueCode = uniqueCodeService.createUniqueCode();
            dlDriveSchoolStudent.setUniqueCode(uniqueCode);
            // 生成学员编码
            dlDriveSchoolStudent.setDrivingStudentCode(generateDrivingStudentCode());
            dlDriveSchoolStudentMapper.insert(dlDriveSchoolStudent);
            return dlDriveSchoolStudent.getId();
        } else {
            dlDriveSchoolStudent.setId(studentByIdCard.getId());
            dlDriveSchoolStudent.setUniqueCode(studentByIdCard.getUniqueCode());
            dlDriveSchoolStudentMapper.updateById(dlDriveSchoolStudent);
            return studentByIdCard.getId();
        }
    }

    @Override
    public DlDriveSchoolStudent getStudentByIdCard(Long userId) {
        return lambdaQuery()
                .eq(DlDriveSchoolStudent::getUserId, userId)
                .orderByDesc(DlDriveSchoolStudent::getCreateTime)
                .last("LIMIT 1")
                .one();
    }

    /**
     * 生成学员编码 年份 + 五位递增数字
     * @return
     *//*
    private String generateDrivingStudentCode() {
        String year = String.valueOf(LocalDate.now().getYear());

        QueryWrapper<DlDriveSchoolStudent> wrapper = new QueryWrapper<>();
        wrapper.select("driving_student_code")
                .likeRight("driving_student_code", year)
                .orderByDesc("driving_student_code")
                .last("LIMIT 1");

        DlDriveSchoolStudent maxStudent = dlDriveSchoolStudentMapper.selectOne(wrapper);

        int next = 1;
        if (maxStudent != null && StringUtils.isNotBlank(maxStudent.getDrivingStudentCode())) {
            String code = maxStudent.getDrivingStudentCode();
            String suffix = code.substring(4);
            next = Integer.parseInt(suffix) + 1;
        }

        return year + String.format("%05d", next);
    }*/

    /**
     * 生成学员编码：年份 + 月份 + 四位递增数字
     */
    private String generateDrivingStudentCode() {
        String yearMonth = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMM"));
        Long tenantId = TenantContextHolder.getTenantId();

        QueryWrapper<DlDriveSchoolStudent> wrapper = new QueryWrapper<>();
        wrapper.select("driving_student_code")
                .likeRight("driving_student_code", yearMonth)
                .eq("tenant_id", tenantId)
                .orderByDesc("driving_student_code")
                .last("LIMIT 1");

        DlDriveSchoolStudent maxStudent = dlDriveSchoolStudentMapper.selectOne(wrapper);

        int next = 1;
        if (maxStudent != null && StringUtils.isNotBlank(maxStudent.getDrivingStudentCode())) {
            String code = maxStudent.getDrivingStudentCode();
            String suffix = code.substring(6);
            next = Integer.parseInt(suffix) + 1;
        }

        return yearMonth + String.format("%04d", next);
    }


    /**
     * 获取学员详细信息
     *
     * @param id 学员id
     * @return cn.iocoder.yudao.module.base.vo.DlDriveSchoolStudentVO
     * @author PQZ
     * @date 9:58 2025/2/10
     **/
    @Override
    public DlDriveSchoolStudentVO queryStudentById(String id) {
        //学员基本信息
        DlDriveSchoolStudent student = getById(id);
        DlDriveSchoolStudentVO result = BeanUtils.toBean(student, DlDriveSchoolStudentVO.class);
        return result;
    }

    @Override
    public void updateDlDriveSchoolStudent(DlDriveSchoolStudentVO updateReqVO) {
        // 更新
        DlDriveSchoolStudent updateObj = BeanUtils.toBean(updateReqVO, DlDriveSchoolStudent.class);
        dlDriveSchoolStudentMapper.updateById(updateObj);
    }

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


    @Override
    public DlDriveSchoolStudent getDlDriveSchoolStudent(String id) {
        return dlDriveSchoolStudentMapper.selectById(id);
    }

    /**
     * 根据userID查学员详情
     *
     * @param userId 用户ID
     * @return cn.iocoder.yudao.module.base.entity.DlDriveSchoolStudent
     * @author vinjor-M
     * @date 22:17 2025/1/20
     **/
    @Override
    public DlDriveSchoolStudent getStudentByUserId(Long userId) {
        DlDriveSchoolStudent student = getOne(Wrappers.<DlDriveSchoolStudent>lambdaQuery()
                .eq(DlDriveSchoolStudent::getUserId, userId)
                .orderByDesc(DlDriveSchoolStudent::getCreateTime)
                .last("limit 1"));

        // 如果没有找到，则返回null
        if (ObjectUtil.isEmpty(student)) {
            return null;
        } else {
            // 判断是否有唯一码
            if (StringUtils.isBlank(student.getUniqueCode())) {
                // 生成唯一推广码
                String uniqueCode = uniqueCodeService.createUniqueCode();
                student.setUniqueCode(uniqueCode);
                dlDriveSchoolStudentMapper.updateById(student);
            }
            return student;
        }
    }

    /**
     * 分页查询学生列表
     *
     * @param pageReqVO {@link DlDriveSchoolStudentVO}
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<?>
     * @author PQZ
     * @date 10:41 2025/1/18
     **/
    @Override
    public IPage<DlDriveSchoolStudentVO> queryListPage(DlDriveSchoolStudentVO pageReqVO, Page<DlDriveSchoolStudentVO> page) {
        return dlDriveSchoolStudentMapper.queryListPage(pageReqVO, page);
    }

    /**
     * 获取可以考试的学员列表
     *
     * @param courseId 课程ID
     * @param subject  科目
     * @return List<DlDriveSchoolStudent>
     * @author vinjor-M
     * @date 23:16 2025/1/20
     **/
    @Override
    public List<DlDriveSchoolStudent> getCanExamStudentList(String courseId, Integer subject, String userName) {
        //教练ID
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        return dlDriveSchoolStudentMapper.selectCanExamStudentList(courseId, userId, subject, userName);
    }

    /**
     * 手机端获取学员
     *
     * @param staffVO {@link DlDriveSchoolStaffVO}
     * @param page    分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.base.vo.DlDriveSchoolStaffVO>
     * @author PQZ
     * @date 14:47 2025/2/6
     **/
    @Override
    public IPage<DlDriveSchoolStaffVO> pageStaffStudent(DlDriveSchoolStaffVO staffVO, Page<DlDriveSchoolStaffVO> page) {
        return dlDriveSchoolStudentMapper.pageStaffStudent(staffVO, page);
    }

    /**
     * 教练查自己所有学生列表
     *
     * @param pageReqVO {@link DlDriveSchoolStudentVO}
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<?>
     * @author PQZ
     * @date 10:41 2025/1/18
     **/
    @Override
    public IPage<DlDriveSchoolStudentVO> queryCoachListPage(DlDriveSchoolStudentVO pageReqVO, Page<DlDriveSchoolStudentVO> page) {
        //默认查全部数据
        String startTimeStr = "";
        String endTimeStr = "";
        if ("more".equals(pageReqVO.getTimeType())) {
            if (StringUtils.isNotEmpty(pageReqVO.getStartTime())) {
                startTimeStr = pageReqVO.getStartTime() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(pageReqVO.getEndTime())) {
                endTimeStr = pageReqVO.getEndTime() + " 23:59:59";
            }
        } else if ("month".equals(pageReqVO.getTimeType())) {
            //当月
            startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(pageReqVO.getTimeType())) {
            //当天
            startTimeStr = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTimeStr = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        pageReqVO.setStartTime(startTimeStr);
        pageReqVO.setStartTime(endTimeStr);
        IPage<DlDriveSchoolStudentVO> pageResult = dlDriveSchoolStudentMapper.selectByCoachId(pageReqVO, page);
        pageResult.getRecords().forEach(item -> {
            //查每个学生的当前所处的科目
            List<Process> list = processService.list(Wrappers.<Process>lambdaQuery()
                    .eq(Process::getUserId, item.getUserId())
                    .eq(Process::getCoachId, item.getCoachId())
                    .eq(Process::getCourseId, item.getCourseId())
                    .orderByDesc(Process::getCreateTime));

            Process newProcess = new Process();
            if (CollUtil.isNotEmpty(list)) {
                // 查询正在进行的课程
                newProcess = list.stream().filter(process -> process.getStatus().equals("1")).findFirst().orElse(null);
                if (ObjectUtil.isNotEmpty(newProcess)) {
                    item.setProcess(newProcess);
                } else {
                    // 判断所有进度是否都是已完成
//                    boolean flag = list.stream().allMatch(process -> process.getStatus().equals("2"));
                    boolean flag = list.stream()
                            .filter(process -> process.getSubject() == 2 || process.getSubject() == 3)
                            .allMatch(process -> "2".equals(process.getStatus()));
                    if (flag) {
                        newProcess = list.stream().max(Comparator.comparing(Process::getSubject)).orElse(null);
                    } else {
                        newProcess = list.stream().min(Comparator.comparing(Process::getSubject)).orElse(null);
                    }
                }
            }

            item.setProcess(newProcess);
        });
        return pageResult;
    }

    /**
     * 教练查自己所有学生列表
     *
     * @param pageReqVO {@link DlDriveSchoolStudentVO}
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<?>
     * @author PQZ
     * @date 10:41 2025/1/18
     **/
    @Override
    public IPage<DlDriveSchoolStudentVO> queryBusinessListPage(DlDriveSchoolStudentVO pageReqVO, Page<DlDriveSchoolStudentVO> page) {
        //默认查全部数据
        String startTimeStr = "";
        String endTimeStr = "";
        if ("more".equals(pageReqVO.getTimeType())) {
            if (StringUtils.isNotEmpty(pageReqVO.getStartTime())) {
                startTimeStr = pageReqVO.getStartTime() + " 00:00:01";
            }
            if (StringUtils.isNotEmpty(pageReqVO.getEndTime())) {
                endTimeStr = pageReqVO.getEndTime() + " 23:59:59";
            }
        } else if ("month".equals(pageReqVO.getTimeType())) {
            //当月
            startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 00:00:01";
            endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()), "yyyy-MM-dd") + " 23:59:59";
        } else if ("day".equals(pageReqVO.getTimeType())) {
            //当天
            startTimeStr = DateUtil.formatDate(DateUtil.date()) + " 00:00:01";
            endTimeStr = DateUtil.formatDate(DateUtil.date()) + " 23:59:59";
        }
        pageReqVO.setStartTime(startTimeStr);
        pageReqVO.setStartTime(endTimeStr);
        IPage<DlDriveSchoolStudentVO> pageResult = dlDriveSchoolStudentMapper.selectByBusinessId(pageReqVO, page);
        /*pageResult.getRecords().forEach(item -> {
            //查每个学生的当前所处的科目
            List<Process> list = processService.list(Wrappers.<Process>lambdaQuery()
                    .eq(Process::getUserId, item.getUserId())
                    .eq(Process::getCoachId, item.getCoachId())
                    .eq(Process::getCourseId, item.getCourseId())
                    .orderByDesc(Process::getCreateTime));

            Process newProcess = new Process();
            if (CollUtil.isNotEmpty(list)) {
                // 查询正在进行的课程
                newProcess = list.stream().filter(process -> process.getStatus().equals("1")).findFirst().orElse(null);
                if (ObjectUtil.isNotEmpty(newProcess)) {
                    item.setProcess(newProcess);
                } else {
                    // 判断所有进度是否都是已完成
//                    boolean flag = list.stream().allMatch(process -> process.getStatus().equals("2"));
                    boolean flag = list.stream()
                            .filter(process -> process.getSubject() == 2 || process.getSubject() == 3)
                            .allMatch(process -> "2".equals(process.getStatus()));
                    if (flag) {
                        newProcess = list.stream().max(Comparator.comparing(Process::getSubject)).orElse(null);
                    } else {
                        newProcess = list.stream().min(Comparator.comparing(Process::getSubject)).orElse(null);
                    }
                }
            }

            item.setProcess(newProcess);
        });*/
        return pageResult;
    }

    /**
     * @param type      时间查询类型（01驾校统招，02教练自招，03自来客户）
     * @param coachId   教练id
     * @param startTime 查询时间范围--开始
     * @param endTime   查询时间范围--结束
     * @return java.util.List<cn.iocoder.yudao.module.base.vo.StudentCountVO>
     * @author PQZ
     * @date 17:08 2025/2/19
     **/
    @Override
    public List<StudentCountVO> indexGetTrainList(String type, Long coachId, String startTime, String endTime) {
        if ("03".equals(type)) {
            //自来的学生
            return dlDriveSchoolStudentMapper.indexCusStudentList(startTime, endTime);
        } else {
            return dlDriveSchoolStudentMapper.indexGetTrainList(type, coachId, startTime, endTime);
        }
    }

    /**
     * 查自来客户
     *
     * @param startTimeStr 查询时间范围--开始
     * @param endTimeStr   查询时间范围--结束
     * @return cn.iocoder.yudao.module.base.vo.DlDriveSchoolStaffVO
     * @author PQZ
     * @date 11:43 2025/2/20
     **/
    @Override
    public List<DlDriveSchoolStaffVO> indexGetFormList(String startTimeStr, String endTimeStr) {
        return dlDriveSchoolStudentMapper.indexGetFormList(startTimeStr, endTimeStr);
    }

    /**
     * 更新学员拿证时间
     *
     * @param passTime 拿证日期
     * @param userId   学员id
     * @param courseId 课程id
     * @param tenantId 租户id
     */
    @TenantIgnore
    @Override
    @Transactional
    public Boolean updateStudentPassAndGradTime(Date passTime, Long userId, String courseId, Long tenantId) {
        if (ObjectUtils.isEmpty(passTime) || ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(tenantId)) {
            return false;
        }
        // 更新学员拿证时间
        schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getUserId, userId)
                .eq(SchoolCourseOrder::getCourseId, courseId)
                .set(SchoolCourseOrder::getPassTime, passTime)
                .set(SchoolCourseOrder::getGradTime, new Date()));

        // 消息准备
        String message = String.format(SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TEMPLATE_MEMBER_DRIVER_LICENSE, DateUtil.format(passTime, "yyyy-MM-dd HH:mm:ss"));

        // 发送消息
        schoolNotifyMessageSendService.sendMessage(userId, message, SchoolBaseConstants.SCHOOL_NOTIFY_MESSAGE_TYPE_MEMBER, tenantId);

        return true;
    }

    /**
     * 更新学员拿证时间
     *
     * @param userId   学员id
     * @param courseId 课程id
     * @param tenantId 租户id
     */
    @TenantIgnore
    @Override
    @Transactional
    public Boolean updateStudentGradTime(Long userId, String courseId, Long tenantId) {
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(tenantId)) {
            return false;
        }
        // 更新学员拿证时间
        schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getUserId, userId)
                .eq(SchoolCourseOrder::getCourseId, courseId)
                .set(SchoolCourseOrder::getGradTime, new Date()));

        return true;
    }

    @Override
    @Transactional
    public Boolean adminUpdateStudentPassAndGradTime(Date passTime, Date gradTime, Long userId, String courseId, Long tenantId) {
        // 更新学员拿证时间
        schoolCourseOrderService.update(Wrappers.lambdaUpdate(SchoolCourseOrder.class)
                .eq(SchoolCourseOrder::getUserId, userId)
                .eq(SchoolCourseOrder::getCourseId, courseId)
                .set(passTime != null, SchoolCourseOrder::getPassTime, passTime)
                .set(gradTime != null, SchoolCourseOrder::getGradTime, gradTime));
        return true;
    }

    /**
     * 根据唯一码查询学员信息
     *
     * @param uniqueCode 唯一码
     * @return cn.iocoder.yudao.module.base.vo.DlDriveSchoolStaffVO
     */
    @Override
    public DlDriveSchoolStudentVO queryStudentByUniqueCode(String uniqueCode) {
        return BeanUtil.copyProperties(getOne(Wrappers.<DlDriveSchoolStudent>lambdaQuery().eq(DlDriveSchoolStudent::getUniqueCode, uniqueCode)),
                DlDriveSchoolStudentVO.class);
    }

    /**
     * 添加文件夹
     *
     * @param userId 用户id
     * @return 文件夹id
     */
    @Override
    public Long addFolder(Long userId) {
        DlDriveSchoolStudent student = this.getStudentByUserId(userId);
        if (ObjectUtil.isNotEmpty(student)) {
            Long folderId = inspectionFileService.addFolderForJx(student.getName(), InspectionConstants.DRIVE_SCHOOL_STUDENT_KEY);

            //查询员工子表是否存在数据
            DlDriveSchoolStudent staff = this.getOne(Wrappers.<DlDriveSchoolStudent>lambdaQuery().eq(DlDriveSchoolStudent::getUserId, userId));
            if (ObjectUtil.isNull(staff)) {
                staff = new DlDriveSchoolStudent();
                staff.setUserId(userId);
                staff.setFolderId(folderId);
                //新增
                this.save(staff);
            } else {
                //修改文件夹id
                this.update(Wrappers.<DlDriveSchoolStudent>lambdaUpdate().eq(DlDriveSchoolStudent::getUserId, userId).set(DlDriveSchoolStudent::getFolderId, folderId));
            }
            return folderId;
        } else {
            log.error("用户不存在");
            return null;
        }
    }

    /*@Override
    public Long addFolder(Long userId) {
        AdminUserDO user = userService.getUser(userId);
        if (ObjectUtil.isNotEmpty(user)) {
            Long folderId = inspectionFileService.addFolderForJx(user.getNickname(), InspectionConstants.DRIVE_SCHOOL_STUDENT_KEY);

            //查询员工子表是否存在数据
            DlDriveSchoolStudent staff = this.getOne(Wrappers.<DlDriveSchoolStudent>lambdaQuery().eq(DlDriveSchoolStudent::getUserId, userId));
            if (ObjectUtil.isNull(staff)) {
                staff = new DlDriveSchoolStudent();
                staff.setUserId(userId);
                staff.setFolderId(folderId);
                //新增
                this.save(staff);
            } else {
                //修改文件夹id
                this.update(Wrappers.<DlDriveSchoolStudent>lambdaUpdate().eq(DlDriveSchoolStudent::getUserId, userId).set(DlDriveSchoolStudent::getFolderId, folderId));
            }
            return folderId;
        } else {
            log.error("用户不存在");
            return null;
        }
    }*/

    public void addFile(List<FileDO> fileList, String nickname, Long fatherId, Long userId) {
        if (ObjectUtil.isEmpty(fatherId)) {
            //添加文件夹
            InspectionFile inspectionFile = new InspectionFile();
            inspectionFile.setFileName(nickname + InspectionConstants.INSPECTION_FOLDER_SUFFIX);
            inspectionFile.setType(InspectionConstants.INSPECTION_FOLDER);
            inspectionFile.setServicePackageId("jiaxiao");
            fatherId = inspectionFileService.insertInspectionFile(inspectionFile).getId();

            //更新员工子表中的文件夹id
            this.update(Wrappers.<DlDriveSchoolStudent>lambdaUpdate()
                    .eq(DlDriveSchoolStudent::getUserId, userId)
                    .set(DlDriveSchoolStudent::getFolderId, fatherId));
        } else {

            //删除文件下的所有文件
            inspectionFileService.remove(Wrappers.<InspectionFile>lambdaQuery()
                    .eq(InspectionFile::getFatherId, fatherId)
                    .eq(InspectionFile::getType, InspectionConstants.INSPECTION_FILE)
                    .eq(InspectionFile::getIsStaffFile, InspectionConstants.INSPECTION_IS_STAFF_FILE));
        }

        //添加文件
        List<InspectionFile> fileDOList = new ArrayList<>();
        for (FileDO fileDO : fileList) {
            InspectionFile file = new InspectionFile();
            file.setFileName(removeFileExtension(fileDO.getName()));
            file.setFilePath(fileDO.getUrl());
            file.setType(InspectionConstants.INSPECTION_FILE);
            file.setFatherId(fatherId);
            file.setIsStaffFile(InspectionConstants.INSPECTION_IS_STAFF_FILE);
            file.setServicePackageId("jiaxiao");
            fileDOList.add(file);
        }

        //批量插入文件
        inspectionFileService.insertBatchInspectionFile(fileDOList);
    }

    /**
     * 去除文件名中的后缀
     *
     * @param filename
     * @return
     */
    public String removeFileExtension(String filename) {
        if (filename == null) {
            return null; // 或者你可以选择返回一个空字符串，取决于你的业务需求
        }
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return filename; // 如果没有找到点，则返回原文件名
        }
        return filename.substring(0, lastDotIndex);
    }


    @Override
    public List<DriveSchoolStudentExportVo> getAll(DlDriveSchoolStudent query) {
        return baseMapper.getAll(query);
    }

}
