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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolCoachCourse;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolCourse;
import cn.iocoder.yudao.module.base.entity.DriveSchoolCourseDeduct;
import cn.iocoder.yudao.module.base.mapper.DlDriveSchoolCourseMapper;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCoachCourseService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseDeductService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseService;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachVO;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolCourseVO;
import cn.iocoder.yudao.module.jx.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 驾校教练 Service 实现类
 *
 * @author pqz
 */
@Service
@Validated
public class DlDriveSchoolCourseServiceImpl extends ServiceImpl<DlDriveSchoolCourseMapper, DlDriveSchoolCourse> implements DlDriveSchoolCourseService {

    @Resource
    private DlDriveSchoolCourseMapper courseMapper;
    @Resource
    private DlDriveSchoolCoachCourseService coachCourseService;
    @Resource
    private DlDriveSchoolCourseDeductService driveSchoolCourseDeductService;

    /**
     * 分页查询驾校课程
     *
     * @param pageReqVO {@link DlDriveSchoolCourseVO}
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.base.vo.DlDriveSchoolCourseVO>
     * @author PQZ
     * @date 22:04 2025/1/16
     **/
    @Override
    public IPage<DlDriveSchoolCourseVO> queryListPage(DlDriveSchoolCourseVO pageReqVO, Page<DlDriveSchoolCourseVO> page) {
        return courseMapper.queryListPage(pageReqVO, page);
    }

    /**
     * 不分页查询驾校课程
     *
     * @param courseVO {@link DlDriveSchoolCourseVO}
     * @return java.util.List<cn.iocoder.yudao.module.base.vo.DlDriveSchoolCourseVO>
     * @author PQZ
     * @date 22:07 2025/1/16
     **/
    @Override
    public List<DlDriveSchoolCourse> queryList(DlDriveSchoolCourseVO courseVO) {
        LambdaQueryWrapper<DlDriveSchoolCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BaseDO::getDeleted, 0).eq(DlDriveSchoolCourse::getIfDisplay,"0");
        if (StringUtils.isNotEmpty(courseVO.getName())) {
            lambdaQueryWrapper.like(DlDriveSchoolCourse::getName, courseVO.getName());
        }
        if (courseVO.getTenantId() != null) {
            lambdaQueryWrapper.eq(DlDriveSchoolCourse::getTenantId, courseVO.getTenantId());
        }

        return list(lambdaQueryWrapper);
    }

    /**
     * 保存课程信息
     *
     * @param courseVO {@link DlDriveSchoolCourseVO}
     * @author PQZ
     * @date 22:12 2025/1/16
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDriveSchoolCourse(DlDriveSchoolCourseVO courseVO) {
        DlDriveSchoolCourse course = BeanUtils.toBean(courseVO, DlDriveSchoolCourse.class);
        saveOrUpdate(course);
        coachCourseService.saveCoachCourse(course.getId(), courseVO.getName(), courseVO.getType(), courseVO.getCoachList());
        // 删除提成配置
        driveSchoolCourseDeductService.remove(Wrappers.<DriveSchoolCourseDeduct>lambdaQuery()
                .eq(DriveSchoolCourseDeduct::getCourseId, course.getId()));
        //设置提成信息课程id
        courseVO.getDeductList().forEach(deduct -> {
            deduct.setCourseId(course.getId());
            deduct.setId(null);
        });

        // 保存提成信息
        driveSchoolCourseDeductService.saveBatch(courseVO.getDeductList());
    }

    /**
     * 删除课程信息
     *
     * @param id 课程id
     * @author PQZ
     * @date 22:14 2025/1/16
     **/
    @Override
    public void deleteCourse(String id) {
        removeById(id);
    }

    /**
     * 通过id查询课程信息
     *
     * @param id 课程id
     * @return cn.iocoder.yudao.module.base.vo.DlDriveSchoolCourseVO
     * @author PQZ
     * @date 22:15 2025/1/16
     **/
    @Override
    public DlDriveSchoolCourseVO queryDetailById(String id) {
        DlDriveSchoolCourse course = getById(id);
        //查询课程信息
        DlDriveSchoolCourseVO result = BeanUtils.toBean(course, DlDriveSchoolCourseVO.class);
        //课程关联教练
        List<DlDriveSchoolCoachVO> coachList = transCoachList(coachCourseService.queryByCourseId(id));
        result.setCoachList(coachList);
        // 使用 Stream API 按 coachId 分组
        Map<String, List<String>> groupedCoachMap = coachList.stream()
                .collect(Collectors.groupingBy(
                        DlDriveSchoolCoachVO::getCoachName,
                        Collectors.mapping(coach -> "科目" + coach.getSubject(), Collectors.toList())
                ));
        // 将 groupedCoachMap 转换为字符串格式
        String resultString = groupedCoachMap.entrySet().stream()
                .map(entry -> entry.getKey() + "[" + String.join(" ", entry.getValue()) + "]")
                .collect(Collectors.joining(", "));
        result.setCoachListText(resultString);
        // 查询提成配置
        List<DriveSchoolCourseDeduct> deducts = driveSchoolCourseDeductService.list(Wrappers.<DriveSchoolCourseDeduct>lambdaQuery()
                .eq(DriveSchoolCourseDeduct::getCourseId, id));
        if (CollUtil.isEmpty(deducts)) {
            // 科目一到科目四都为0
            for (int i = 1; i <= 4; i++) {
                DriveSchoolCourseDeduct deduct = new DriveSchoolCourseDeduct();
                deduct.setCourseId(id);
                deduct.setCourseSubject(i + "");
                deduct.setDeduct(new BigDecimal("0"));
                deducts.add(deduct);
            }
        }
        result.setDeductList(deducts);
        return result;
    }


    /**
     * 数据类型转换
     *
     * @param coachList TODO
     * @return java.util.List<cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachVO>
     * @author PQZ
     * @date 14:25 2025/2/8
     **/
    private List<DlDriveSchoolCoachVO> transCoachList(List<DlDriveSchoolCoachCourse> coachList) {
        List<DlDriveSchoolCoachVO> transList = new ArrayList<>();
        if (!coachList.isEmpty()) {
            coachList.forEach(item -> {
                DlDriveSchoolCoachVO vo = new DlDriveSchoolCoachVO();
                vo.setCoachId(item.getCoachId());
                vo.setCoachName(item.getCoachName());
                vo.setSubject(item.getSubject());
                vo.setCoachPhone(item.getCoachPhone());
                transList.add(vo);
            });
        }
        return transList;
    }


}
