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.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.common.SchoolRoleEnum;
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.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolCoach;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolStudent;
import cn.iocoder.yudao.module.base.mapper.DlDriveSchoolCoachMapper;
import cn.iocoder.yudao.module.base.mapper.DlDriveSchoolStudentMapper;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCoachService;
import cn.iocoder.yudao.module.base.vo.*;
import cn.iocoder.yudao.module.constant.InspectionConstants;
import cn.iocoder.yudao.module.course.entity.SchoolCommission;
import cn.iocoder.yudao.module.course.mapper.SchoolCommissionMapper;
import cn.iocoder.yudao.module.exam.mapper.ExamBatchItemMapper;
import cn.iocoder.yudao.module.exam.vo.ExamBatchItemVO;
import cn.iocoder.yudao.module.infra.dal.dataobject.file.FileDO;
import cn.iocoder.yudao.module.inspection.entity.InspectionFile;
import cn.iocoder.yudao.module.inspection.entity.InspectionStaff;
import cn.iocoder.yudao.module.inspection.service.IInspectionFileService;
import cn.iocoder.yudao.module.inspection.vo.ImportStaffVo;
import cn.iocoder.yudao.module.inspection.vo.InspectionStaffSaveVo;
import cn.iocoder.yudao.module.inspection.vo.StaffImportExcelVO;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCar;
import cn.iocoder.yudao.module.jx.service.IDriveSchoolCarService;
import cn.iocoder.yudao.module.jx.utils.StringUtils;
import cn.iocoder.yudao.module.staff.entity.CompanyStaff;
import cn.iocoder.yudao.module.staff.service.CompanyStaffService;
import cn.iocoder.yudao.module.staff.service.UniqueCodeService;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
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.api.user.dto.UserRoleDTO;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.module.train.mapper.TrainMapper;
import cn.iocoder.yudao.module.train.vo.TrainVO;
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.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.text.DecimalFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.common.BaseConstants.PASSWORD_DEFAULT;
import static cn.iocoder.yudao.framework.common.config.CommonStr.USER_TYPE_STAFF;

/**
 * 驾校教练 Service 实现类
 *
 * @author pqz
 */
@Service
@Validated
public class DlDriveSchoolCoachServiceImpl extends ServiceImpl<DlDriveSchoolCoachMapper, DlDriveSchoolCoach> implements DlDriveSchoolCoachService {

    @Resource
    private DlDriveSchoolCoachMapper dlDriveSchoolCoachMapper;
    @Resource
    @Lazy
    private AdminUserApi adminUserApi;
    @Autowired
    private AdminUserService userService;
    @Resource
    @Lazy
    private CompanyStaffService companyStaffService;
    @Resource
    private PermissionApi permissionApi;
    @Resource
    private UniqueCodeService uniqueCodeService;
    @Autowired
    @Lazy
    private IDriveSchoolCarService schoolCarService;
    @Autowired
    private DlDriveSchoolStudentMapper studentMapper;
    @Autowired
    private ExamBatchItemMapper examBatchItemMapper;
    @Autowired
    private TrainMapper trainMapper;
    @Autowired
    private SchoolCommissionMapper commissionMapper;
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private IInspectionFileService inspectionFileService;

    @Autowired
    private RoleService roleService;


    /**
     * 驾校教练、普通员工列表
     *
     * @param pageReqVO {@link DlDriveSchoolCoachPageReqVO}
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachRespVO>
     * @author PQZ
     * @date 15:02 2025/1/16
     **/
    @Override
    public IPage<DlDriveSchoolCoachRespVO> queryListPage(DlDriveSchoolCoachPageReqVO pageReqVO, Page<DlDriveSchoolCoachRespVO> page) {
        return dlDriveSchoolCoachMapper.queryListPage(pageReqVO, page);
    }

    /**
     * 不分页查询教练信息
     *
     * @param pageReqVO {@link DlDriveSchoolCoachPageReqVO}
     * @return java.util.List<cn.iocoder.yudao.module.base.entity.DlDriveSchoolCoach>
     * @author PQZ
     * @date 14:26 2025/2/7
     **/
    @Override
    public List<DlDriveSchoolCoach> listSchoolCoach(DlDriveSchoolCoachPageReqVO pageReqVO) {
        LambdaQueryWrapper<DlDriveSchoolCoach> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDO::getDeleted, 0).eq(DlDriveSchoolCoach::getType, "jl");
        if (StringUtils.isNotEmpty(pageReqVO.getName())) {
            lambdaQueryWrapper.like(DlDriveSchoolCoach::getName, pageReqVO.getName());
        }
        return list(lambdaQueryWrapper);
    }

    @Override
    public List<DlDriveSchoolCoach> listSchoolCoachApp(DlDriveSchoolCoachPageReqVO pageReqVO) {
        LambdaQueryWrapper<DlDriveSchoolCoach> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDO::getDeleted, 0).eq(DlDriveSchoolCoach::getType, "jl")
                .eq(DlDriveSchoolCoach::getTenantId, pageReqVO.getTenantId());
        if (StringUtils.isNotEmpty(pageReqVO.getName())) {
            lambdaQueryWrapper.like(DlDriveSchoolCoach::getName, pageReqVO.getName());
        }
        if (StringUtils.isNotEmpty(pageReqVO.getPhone())) {
            lambdaQueryWrapper.eq(DlDriveSchoolCoach::getPhone, pageReqVO.getPhone());
        }
        return list(lambdaQueryWrapper);
    }
    /**
     * 不分页查询教练信息
     *
     * @param pageReqVO {@link DlDriveSchoolCoachPageReqVO}
     * @return java.util.List<cn.iocoder.yudao.module.base.entity.DlDriveSchoolCoach>
     * @author PQZ
     * @date 14:26 2025/2/7
     **/
    @Override
    public List<DlDriveSchoolCoach> listSchoolPeople(DlDriveSchoolCoachPageReqVO pageReqVO) {
        LambdaQueryWrapper<DlDriveSchoolCoach> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDO::getDeleted, 0);
        if (StringUtils.isNotEmpty(pageReqVO.getName())) {
            lambdaQueryWrapper.like(DlDriveSchoolCoach::getName, pageReqVO.getName());
        }
        return list(lambdaQueryWrapper);
    }


    /**
     * @param staffVO {@link DlDriveSchoolStaffVO}
     * @param page    分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.base.vo.DlDriveSchoolStaffVO>
     * @author PQZ
     * @date 13:51 2025/2/6
     **/
    @Override
    public IPage<DlDriveSchoolStaffVO> pageStaffCoach(DlDriveSchoolStaffVO staffVO, Page<DlDriveSchoolStaffVO> page) {
        return dlDriveSchoolCoachMapper.pageStaffCoach(staffVO, page);
    }

    /**
     * 保存驾校教练
     *
     * @param createReqVO {@link DlDriveSchoolCoachSaveReqVO}
     * @author PQZ
     * @date 21:07 2025/1/16
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSchoolCoach(DlDriveSchoolCoachSaveReqVO createReqVO) {
        /*1、基础数据准备*/
        //数据类型转换
        DlDriveSchoolCoach dlDriveSchoolCoach = BeanUtils.toBean(createReqVO, DlDriveSchoolCoach.class);
        //初始化
        CompanyStaff companyStaff = companyStaffService.queryByPhone(createReqVO.getPhone());
        //查询用户
        AdminUserRespDTO userDTO = new AdminUserRespDTO();
        if (null == createReqVO.getUserId()) {
            userDTO = adminUserApi.getUserByUsername(createReqVO.getPhone());
        }
        //定义用户id
        Long userId = null;
        if (StringUtils.isEmpty(createReqVO.getId())) {
            /*2、 情况一：新增教练或员工时，员工表中无数据*/
            //员工表中无数据
            if (null == companyStaff) {
                //用户表中无数据
                if (null == userDTO) {
                    UserDTO user = new UserDTO();
                    //如果不存在创建用户；
                    user.setUsername(createReqVO.getPhone());
                    user.setNickname(createReqVO.getName());
                    //默认密码
                    user.setPassword(PASSWORD_DEFAULT);
                    user.setMobile(createReqVO.getPhone());
                    //用户类型员工
                    user.setUserType(USER_TYPE_STAFF);
                    //用户表创建教练
                    userId = adminUserApi.createUser(user);
                    //创建用户后为客户绑定角色
                    Set<String> roleCodes = new HashSet<>();
                    if ("jl".equals(createReqVO.getType())) {
                        roleCodes.add(SchoolRoleEnum.COACH.getCode());
                    } else if ("yg".equals(createReqVO.getType())) {
                        roleCodes.add(SchoolRoleEnum.STAFF.getCode());
                    } else if ("ywjl".equals(createReqVO.getType())) {
                        roleCodes.add(SchoolRoleEnum.BUSINESS.getCode());
                    }
                    permissionApi.assignUserRole(userId, roleCodes);
                } else {
                    //用户表中有数据
                    userId = userDTO.getId();
                }
                CompanyStaff newStaff = new CompanyStaff();
                newStaff.setUserId(userId);
                newStaff.setName(createReqVO.getName());
                newStaff.setTel(createReqVO.getPhone());
                newStaff.setAddress(createReqVO.getAddress());
                newStaff.setSex(createReqVO.getSex());
                newStaff.setUniqueCode(uniqueCodeService.createUniqueCode());
                //保存到员工表
                companyStaffService.save(newStaff);
            } else {
                //员工表中有数据，则取用户id
                userId = companyStaff.getUserId();
            }
            dlDriveSchoolCoach.setUserId(userId);
        }
        /*3、保存教练信息*/
        saveOrUpdate(dlDriveSchoolCoach);
    }

    /**
     * 跟新教练员车辆信息
     *
     * @param id    id
     * @param carNo 车辆
     * @author PQZ
     * @date 15:51 2025/2/7
     **/
    @Override
    public void updateSchoolCoachCarId(String id, String carNo) {
        DlDriveSchoolCoach schoolCoach = getById(id);
        schoolCoach.setCarId(carNo);
        updateById(schoolCoach);
    }

    /**
     * 删除驾校教练
     *
     * @param id 教练id
     * @author PQZ
     * @date 21:39 2025/1/16
     **/
    @Override
    public void deleteDlDriveSchoolCoach(String id) {
        removeById(id);
    }


    /**
     * 通过id查询教练信息
     *
     * @param id 教练id
     * @return cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachRespVO
     * @author PQZ
     * @date 21:43 2025/1/16
     **/
    @Override
    public DlDriveSchoolCoachRespVO getDlDriveSchoolCoach(String id) {
        //通过id查询教练信息
        DlDriveSchoolCoach schoolCoach = getById(id);
        //数据类型转换
        DlDriveSchoolCoachRespVO result = BeanUtils.toBean(schoolCoach, DlDriveSchoolCoachRespVO.class);
        return result;
    }

    /**
     * 获得驾校教练---通过user_id查
     *
     * @param userId 用户表id
     * @return 驾校教练
     */
    @Override
    public DlDriveSchoolCoachRespVO getDlDriveSchoolCoachByUserId(Long userId) {
        LambdaQueryWrapper<DlDriveSchoolCoach> queryWrapper = new LambdaQueryWrapper<DlDriveSchoolCoach>()
                .eq(DlDriveSchoolCoach::getUserId, userId);
        List<DlDriveSchoolCoach> list = this.list(queryWrapper);
        DlDriveSchoolCoachRespVO schoolCoach = null;
        if (!list.isEmpty()) {
            schoolCoach = BeanUtils.toBean(list.get(0), DlDriveSchoolCoachRespVO.class);
        }
        return schoolCoach;
    }

    /**
     * 通过教练id查询教练信息（APP使用）
     *
     * @param id 教练id
     * @return cn.iocoder.yudao.module.base.vo.CoachInfoVO
     * @author PQZ
     * @date 13:49 2025/2/12
     **/
    @Override
    public CoachInfoVO getCoachById(String id) {
        DecimalFormat df = new DecimalFormat("#.00");
        CoachInfoVO result = new CoachInfoVO();
        /*1.教练信息*/
        DlDriveSchoolCoach coach = getById(id);
        result.setCoachInfo(coach);
        /*2.车辆信息*/
        /*DriveSchoolCar schoolCar = new DriveSchoolCar();
        if (ObjectUtil.isNotEmpty(schoolCar)) {
            if (null != coach.getUserId()) {
                schoolCar = schoolCarService.selectByCoachId(coach.getUserId());
                if (null != schoolCar.getCarRegisterDate()) {
                    Long carOld = DateUtil.betweenYear(schoolCar.getCarRegisterDate(), new Date(), true);
                    schoolCar.setCarOld(carOld);
                }
            }
        }*/
        DriveSchoolCar schoolCar = null;
        if (coach.getUserId() != null) {
            schoolCar = schoolCarService.selectByCoachId(coach.getUserId());
            if (schoolCar != null && schoolCar.getCarRegisterDate() != null) {
                Long carOld = DateUtil.betweenYear(schoolCar.getCarRegisterDate(), new Date(), true);
                schoolCar.setCarOld(carOld);
            }
        }
        result.setCar(schoolCar);
        /*3.统计教练的学生基本信息*/
        //毕业情况
        List<DlDriveSchoolStudentVO> studentVOList = studentMapper.selectStudentListCoach(coach.getUserId(),null,null);
        int overNum = (int) studentVOList.stream().filter(item -> null != item.getGradTime()).count();
        int noOverNum = studentVOList.size()-overNum;
        Map<String,Object> studentInfoMap = new HashMap<>();
        studentInfoMap.put("overNum",overNum);
        studentInfoMap.put("noOverNum",noOverNum);
        //考试情况
        List<ExamBatchItemVO> examBatchItemVOList = examBatchItemMapper.selectByCoachId(coach.getUserId(),null,null);
        Double subject2Num = 0.0;
        Double subject3Num = 0.0;
        Double subject2PassNum = 0.0;
        Double subject3PassNum = 0.0;
        for (ExamBatchItemVO exam:examBatchItemVOList){
            if(2==exam.getSubject()){
                subject2Num++;
                if(null!=exam.getIfPass() && exam.getIfPass()){
                    //考试通过
                    subject2PassNum++;
                }
            }else if(3==exam.getSubject()){
                subject3Num++;
                if(null!=exam.getIfPass() && exam.getIfPass()){
                    //考试通过
                    subject3PassNum++;
                }
            }
        }
        double subject2Rate=0;
        double subject3Rate=0;
        if(0!=subject2Num && 0!=subject2PassNum){
            subject2Rate = subject2PassNum / subject2Num;
        }
        if(0!=subject3Num && 0!=subject3PassNum){
            subject3Rate = subject3PassNum / subject3Num;
        }
        studentInfoMap.put("subject2All",subject2Num);
        studentInfoMap.put("subject2Pass",subject2PassNum);
        studentInfoMap.put("subject2Rate",0!=subject2Rate?(Double.parseDouble(df.format(subject2Rate))*100):0);
        studentInfoMap.put("subject3All",subject3Num);
        studentInfoMap.put("subject3Pass",subject3PassNum);
        studentInfoMap.put("subject3Rate",0!=subject3Rate?(Double.parseDouble(df.format(subject3Rate))*100):0);
        //招生情况
        List<DlDriveSchoolStudentVO> studentList = studentMapper.selectStudentList(coach.getUserId(), null, null);
        int coachNum=0;
        double coachAmount=0;
        for (DlDriveSchoolStudentVO item:studentList){
            if("02".equals(item.getSource())){
                //教练自招
                coachNum++;
                coachAmount = coachAmount+item.getPriceAmount();
            }
        }
        studentInfoMap.put("coachNum",coachNum);
        studentInfoMap.put("coachAmount",coachAmount);
        //训练情况
        List<TrainVO> trainList = trainMapper.selectTrainByCondition(coach.getUserId(),null,null);
        Set<Long> allUserSet = new HashSet<>();
        Double trainTime = 0.0;
        for (TrainVO item:trainList){
            allUserSet.add(item.getUserId());
            if(null!=item.getTrainTime()){
                trainTime =trainTime+item.getTrainTime();
            }
        }
        studentInfoMap.put("trainUserNum",allUserSet.size());
        studentInfoMap.put("trainTime",trainTime);
        result.setStudentInfoMap(studentInfoMap);
        /*4.财务情况*/
        List<SchoolCommission> commissionList = commissionMapper.selectByCoachId(coach.getUserId(),null,null);
        //科目2当月应付
        Double subject2MonthShowed = 0.0;
        //科目2累计已付
        Double subject2Payed = 0.0;
        //科目2累计应付
        Double subject2Showed = 0.0;
        //科目3当月应付
        Double subject3MonthShowed = 0.0;
        //科目3累计已付
        Double subject3Payed = 0.0;
        //科目3累计应付
        Double subject3Showed = 0.0;
        //当月时间范围
        // 获取当前月份的开始时间和结束时间
        DateTime startOfMonth = DateUtil.beginOfMonth(DateUtil.date());
        DateTime endOfMonth = DateUtil.endOfMonth(DateUtil.date());
        for (SchoolCommission item:commissionList){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String localDateTimeNowStr = item.getCreateTime().format(formatter);
            DateTime createTime = DateUtil.parse(localDateTimeNowStr);
            if("2".equals(item.getSubject())){
               //科目二
                subject2Showed=subject2Showed+item.getCommissionAmount().doubleValue();
                if(null!=item.getIfPay() && item.getIfPay()){
                    subject2Payed=subject2Payed+item.getCommissionAmount().doubleValue();
                }
                if(createTime.isAfterOrEquals(startOfMonth) && createTime.isBeforeOrEquals(endOfMonth)){
                    //在当月内
                    subject2MonthShowed = subject2MonthShowed+item.getCommissionAmount().doubleValue();
                }
            }else if("3".equals(item.getSubject())){
                //科目三
                subject3Showed=subject3Showed+item.getCommissionAmount().doubleValue();
                if(null!=item.getIfPay() && item.getIfPay()){
                    subject3Payed=subject3Payed+item.getCommissionAmount().doubleValue();
                }
                if(createTime.isAfterOrEquals(startOfMonth) && createTime.isBeforeOrEquals(endOfMonth)){
                    //在当月内
                    subject3MonthShowed = subject3MonthShowed+item.getCommissionAmount().doubleValue();
                }
            }
        }
        Map<String,Object> financeMap = new HashMap<>();
        financeMap.put("subject2MonthShowed",subject2MonthShowed);
        financeMap.put("subject2Showed",subject2Showed);
        financeMap.put("subject2Payed",subject2Payed);
        financeMap.put("subject3MonthShowed",subject3MonthShowed);
        financeMap.put("subject3Showed",subject3Showed);
        financeMap.put("subject3Payed",subject3Payed);
        result.setFinanceMap(financeMap);
        return result;
    }

    /**
     * 根据邀请码查询教练信息
     */
    @Override
    public DlDriveSchoolCoach getCoachByUniqueCode(String uniqueCode) {
        return dlDriveSchoolCoachMapper.getCoachByUniqueCode(uniqueCode);
    }

    @Override
    public CoachStaffSaveVo getOnInternal(Long id) {
        CoachStaffSaveVo coachStaffSaveVo = baseMapper.getOnInternal(id);
        // 查询用户角色集合
        List<UserRoleDTO> userRoleDTOS = permissionService.userRoleDTOList(Collections.singletonList(id));
        coachStaffSaveVo.setRoleIds(userRoleDTOS.stream()
                .filter(role -> "jiaxiao".equals(role.getServicePackageId()))
                .map(UserRoleDTO::getRoleId)
                .collect(Collectors.toList()));

        //将驾驶证类型转为数组
        /*if (ObjectUtil.isNotEmpty(coachStaffSaveVo.getDriverLicenseType())) {
            coachStaffSaveVo.setDriverLicenseTypeArr(Arrays.asList(inspectionStaffSaveVo.getDriverLicenseType().split(",")));
        }*/
        //查询文件表文件夹id是否存在
        if (ObjectUtil.isNotEmpty(coachStaffSaveVo.getFolderId())) {
            InspectionFile folder = inspectionFileService.getOne(Wrappers.<InspectionFile>lambdaQuery().eq(InspectionFile::getId, coachStaffSaveVo.getFolderId()));
            if (ObjectUtil.isNull(folder)) {
                coachStaffSaveVo.setFolderId(null);
            }
        }
        return coachStaffSaveVo;
    }


    /**
     * 编辑检测员工
     *
     * @param coachStaffSaveVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(CoachStaffSaveVo coachStaffSaveVo) {
        //更新system_users主表
        UserSaveReqVO userDTO = BeanUtil.copyProperties(coachStaffSaveVo, UserSaveReqVO.class);
        userDTO.setId(coachStaffSaveVo.getUserId());
        userService.updateUser(userDTO);


        //查询员工子表是否存在数据
        DlDriveSchoolCoach staff = this.getOne(Wrappers.<DlDriveSchoolCoach>lambdaQuery().eq(DlDriveSchoolCoach::getUserId, coachStaffSaveVo.getUserId()));
        if (ObjectUtil.isNull(staff)) {
            staff = new DlDriveSchoolCoach();
            BeanUtil.copyProperties(coachStaffSaveVo, staff);
            //新增
            this.save(staff);
        } else {
            //更新检测员工子表
            String id = staff.getId();
            System.out.println("复制前 staff ID: " + staff.getId());
            BeanUtil.copyProperties(coachStaffSaveVo, staff);
            System.out.println("复制后 staff ID: " + staff.getId());
            staff.setId(id);
            this.updateById(staff);
        }

        //查询文件夹
        DlDriveSchoolCoach staff1 = this.getOne(Wrappers.<DlDriveSchoolCoach>lambdaQuery().eq(DlDriveSchoolCoach::getUserId, coachStaffSaveVo.getUserId()));
        if (CollUtil.isNotEmpty(coachStaffSaveVo.getFileList())) {
            addFile(coachStaffSaveVo.getFileList(), coachStaffSaveVo.getNickname(), staff1.getFolderId(), staff1.getUserId());
        }

        return true;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveCoachStaff(CoachStaffSaveVo coachStaffSaveVo) {
        //新增system_users主表
        UserSaveReqVO userDTO = BeanUtil.copyProperties(coachStaffSaveVo, UserSaveReqVO.class);
        userDTO.setId(coachStaffSaveVo.getUserId());
        //获取当前人的租户id
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        userDTO.setTenantId(loginUser.getTenantId());
        Long userId = userService.createUser(userDTO);

//        //查询检测基础员工角色
//        List<RoleDO> role = roleService.getRoleListByCodesTenant(Collections.singletonList(InspectionConstants.INSPECTION_BASE_STAFF_ROLE));
//
//        if (ObjectUtil.isNull(role)) {
//            throw new RuntimeException("检测基础员工角色不存在");
//        }
//
//        Set<Long> roleIds = role.stream().map(RoleDO::getId).collect(Collectors.toSet());
//        //设置角色为检测基础员工
//        permissionService.assignUserRole(userId, roleIds);

//        DlDriveSchoolCoach dlDriveSchoolCoach = BeanUtil.copyProperties(coachStaffSaveVo, DlDriveSchoolCoach.class);
        DlDriveSchoolCoach dlDriveSchoolCoach = new DlDriveSchoolCoach();
        dlDriveSchoolCoach.setUserId(userId);
        dlDriveSchoolCoach.setName(coachStaffSaveVo.getNickname());
        dlDriveSchoolCoach.setCarId(coachStaffSaveVo.getCarId());
        dlDriveSchoolCoach.setPhone(coachStaffSaveVo.getMobile());
        dlDriveSchoolCoach.setIdNumber(coachStaffSaveVo.getIdNumber());
        dlDriveSchoolCoach.setRegAddress(coachStaffSaveVo.getRegAddress());
        dlDriveSchoolCoach.setAddress(coachStaffSaveVo.getAddress());
        dlDriveSchoolCoach.setSeniority(coachStaffSaveVo.getSeniority());
        dlDriveSchoolCoach.setInstructorDesc(coachStaffSaveVo.getInstructorDesc());
        dlDriveSchoolCoach.setAge(coachStaffSaveVo.getAge());
        dlDriveSchoolCoach.setSex(coachStaffSaveVo.getSex());
        dlDriveSchoolCoach.setType(coachStaffSaveVo.getType());
        //新增检测员工子表
        this.save(dlDriveSchoolCoach);
        if (ObjectUtil.isNotEmpty(coachStaffSaveVo.getFileList())) {
            addFile(coachStaffSaveVo.getFileList(), coachStaffSaveVo.getNickname(), null, coachStaffSaveVo.getUserId());
        }
        return dlDriveSchoolCoach.getUserId();
    }


    /**
     * 添加文件夹
     *
     * @param userId 用户id
     * @return 文件夹id
     */
    @Override
    public Long addFolder(Long userId) {
        AdminUserDO user = userService.getUser(userId);
        if (ObjectUtil.isNotEmpty(user)) {
            Long folderId = inspectionFileService.addFolderForJx(user.getNickname(), InspectionConstants.DRIVE_SCHOOL_STAFF_KEY);

            //查询员工子表是否存在数据
            DlDriveSchoolCoach staff = this.getOne(Wrappers.<DlDriveSchoolCoach>lambdaQuery().eq(DlDriveSchoolCoach::getUserId, userId));
            if (ObjectUtil.isNull(staff)) {
                staff = new DlDriveSchoolCoach();
                staff.setUserId(userId);
                staff.setFolderId(folderId);
                //新增
                this.save(staff);
            } else {
                //修改文件夹id
                this.update(Wrappers.<DlDriveSchoolCoach>lambdaUpdate().eq(DlDriveSchoolCoach::getUserId, userId).set(DlDriveSchoolCoach::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.<DlDriveSchoolCoach>lambdaUpdate()
                    .eq(DlDriveSchoolCoach::getUserId, userId)
                    .set(DlDriveSchoolCoach::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);
    }

    /**
     * 导入检测员工
     *
     * @param list 检测员工
     * @return
     */
    @Override
    public Map<String, Object> importStaff(List<SchoolStaffImportExcelVO> list) {
        if (CollUtil.isEmpty(list)) {
            throw new RuntimeException("导入数据为空");
        }
        Map<String, Object> resultMap = new HashMap<>();

        //校验信息
        ImportSchoolStaffVo importStaffVo = validImportStaff(list);

        //保存用户信息
        int saveNum = saveImportStaff(importStaffVo.getSuccessList());
        resultMap.put("saveNum", saveNum);
        resultMap.put("failList", importStaffVo.getFailList());
        resultMap.put("successList", importStaffVo.getSuccessList());
        return resultMap;
    }

    /**
     * 保存检测员工
     *
     * @param successList
     * @return
     */
    private int saveImportStaff(List<SchoolStaffImportExcelVO> successList) {
        //将员工插入主表
        Map<String, Long> users = new HashMap<>();
        Map<Long, Long> folderMap = new HashMap<>();
        for (SchoolStaffImportExcelVO schoolStaffImportExcelVO : successList) {
            UserSaveReqVO createReqVO = new UserSaveReqVO();
            createReqVO.setUsername(schoolStaffImportExcelVO.getMobile());
            createReqVO.setMobile(schoolStaffImportExcelVO.getMobile());
            createReqVO.setNickname(schoolStaffImportExcelVO.getNickname());
            createReqVO.setPassword("123456");

            Long userId = userService.createUser(createReqVO);
            users.put(schoolStaffImportExcelVO.getMobile(), userId);
            //创建员工文件夹
            Long folderId = addFolder(userId);
            folderMap.put(userId, folderId);
            //修改文件夹id
            this.update(Wrappers.<DlDriveSchoolCoach>lambdaUpdate().eq(DlDriveSchoolCoach::getUserId, userId).set(DlDriveSchoolCoach::getFolderId, folderId));
        }


        //插入检测员工子表
        List<DlDriveSchoolCoach> dlDriveSchoolCoachList = new ArrayList<>();
        for (SchoolStaffImportExcelVO schoolStaffImportExcelVO : successList) {
            Long userId = users.get(schoolStaffImportExcelVO.getMobile());
            DlDriveSchoolCoach dlDriveSchoolCoach = BeanUtil.copyProperties(schoolStaffImportExcelVO, DlDriveSchoolCoach.class);
            dlDriveSchoolCoach.setName(schoolStaffImportExcelVO.getNickname());
            dlDriveSchoolCoach.setPhone(schoolStaffImportExcelVO.getMobile());
            dlDriveSchoolCoach.setUserId(userId);
            dlDriveSchoolCoach.setFolderId(folderMap.get(userId));
            dlDriveSchoolCoachList.add(dlDriveSchoolCoach);

            permissionService.assignUserRole(userId, Collections.singleton(schoolStaffImportExcelVO.getRoleId()));
            this.update(dlDriveSchoolCoach, Wrappers.<DlDriveSchoolCoach>lambdaUpdate().eq(DlDriveSchoolCoach::getUserId, userId));
        }
//        this.saveBatch(dlDriveSchoolCoachList);
        return successList.size();
    }

    /**
     * 验证导入员工数据
     *
     * @param list
     * @return
     */
    private ImportSchoolStaffVo validImportStaff(List<SchoolStaffImportExcelVO> list) {
        List<SchoolStaffImportExcelVO> successList = new ArrayList<>();
        List<SchoolStaffImportExcelVO> failList = new ArrayList<>();

        //查询检测角色
        RoleDO roleDO = new RoleDO();
        roleDO.setServicePackageId("jiaxiao");
        List<RoleDO> roleDOS = roleService.pageByQuery(roleDO);
        Map<String, Long> roleMap = roleDOS.stream().collect(Collectors.toMap(RoleDO::getName, RoleDO::getId));

        //根据手机号查询员工
        List<AdminUserDO> list1 = userService.list(Wrappers.<AdminUserDO>lambdaQuery().in(AdminUserDO::getMobile, list.stream().map(SchoolStaffImportExcelVO::getMobile).collect(Collectors.toList())));
        Map<String, Long> mobileMap = list1.stream().collect(Collectors.toMap(AdminUserDO::getMobile, AdminUserDO::getId));

        //判断第一条数据是否是测试数据
        if (ObjectUtil.isNotEmpty(list)) {
            if ("测试员工".equals(list.get(0).getNickname())) {
                list.remove(0);
            }
        }
        for (SchoolStaffImportExcelVO staffImportExcelVO : list) {
            if (ObjectUtil.isNull(staffImportExcelVO)) {
                continue;
            }
            //判断员工姓名是否为空
            if (ObjectUtil.isEmpty(staffImportExcelVO.getNickname())) {
                staffImportExcelVO.setReason("员工姓名不能为空");
                failList.add(staffImportExcelVO);
                continue;
            }
            // 判断手机号是否为空
            if (ObjectUtil.isEmpty(staffImportExcelVO.getMobile())) {
                staffImportExcelVO.setReason("员工" + staffImportExcelVO.getNickname() + "手机号不能为空");
                failList.add(staffImportExcelVO);
                continue;
            }
            //判断手机号是否存在
            if (ObjectUtil.isNotEmpty(mobileMap.get(staffImportExcelVO.getMobile()))) {
                staffImportExcelVO.setReason("员工" + staffImportExcelVO.getNickname() + "的手机号已存在");
                failList.add(staffImportExcelVO);
                continue;
            }
            //如果身份证存在验证身份证是否正确
            if (ObjectUtil.isNotEmpty(staffImportExcelVO.getIdNumber())) {
                if (!IdcardUtil.isValidCard(staffImportExcelVO.getIdNumber())) {
                    staffImportExcelVO.setReason("员工" + staffImportExcelVO.getNickname() + "身份证格式不正确");
                    failList.add(staffImportExcelVO);
                    continue;
                }
            }
            //判断员工角色是否为空
            if (ObjectUtil.isEmpty(staffImportExcelVO.getRoleName())) {
                staffImportExcelVO.setReason("员工" + staffImportExcelVO.getNickname() + "员工角色不能为空");
                failList.add(staffImportExcelVO);
                continue;
            }
            String sex = staffImportExcelVO.getSex();
            if (ObjectUtil.isNotEmpty(sex)) {
                sex = sex.trim();
                if ("男".equals(sex)) {
                    staffImportExcelVO.setSex("0");
                } else if ("女".equals(sex)) {
                    staffImportExcelVO.setSex("1");
                } else {
                    staffImportExcelVO.setSex(null);
                }
            }
            String roleName = staffImportExcelVO.getRoleName();
            if(ObjectUtil.isNotEmpty(roleName)){
                roleName = roleName.trim();
                if("教练".equals(roleName)){
                    staffImportExcelVO.setType("jl");
                } else if ("业务经理".equals(roleName)) {
                    staffImportExcelVO.setType("ywjl");
                }else {
                    staffImportExcelVO.setType("yg");
                }
            }
            //查询员工角色对应id
            Long roleId = roleMap.get(staffImportExcelVO.getRoleName());
            staffImportExcelVO.setRoleId(roleId);

            successList.add(staffImportExcelVO);
        }
        ImportSchoolStaffVo importStaffVo = new ImportSchoolStaffVo();
        importStaffVo.setSuccessList(successList);
        importStaffVo.setFailList(failList);
        return importStaffVo;
    }

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