package org.jeecg.modules.app.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.app.service.ICoachService;
import org.jeecg.modules.app.vo.coach.AppCoachDetailsRequestVO;
import org.jeecg.modules.app.vo.coach.AppCoachDetailsVO;
import org.jeecg.modules.app.vo.coach.AppCoachVO;
import org.jeecg.modules.app.vo.course.CourseRequestVo;
import org.jeecg.modules.app.vo.course.CourseResponseVo;
import org.jeecg.modules.system.app.entity.AppCategory;
import org.jeecg.modules.system.app.entity.AppCourses;
import org.jeecg.modules.system.app.entity.AppOrder;
import org.jeecg.modules.system.app.entity.AppOrderProInfo;
import org.jeecg.modules.system.app.mapper.*;
import org.jeecg.modules.system.util.PositionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Log4j2
public class CoachServiceImpl implements ICoachService {


    @Autowired
    AppInstructorMapper appInstructorMapper;
    @Autowired
    AppCategoryMapper appCategoryMapper;
    @Autowired
    AppCoursesMapper appCoursesMapper;
    @Autowired
    private AppOrderMapper appOrderMapper;

    @Autowired
    private AppOrderProInfoMapper appOrderProInfoMapper;
    @Autowired
    EvaluateMapper evaluateMapper;


    @Override
    public Result<List<AppCoachVO>> findCoachList() {
        List<AppCoachVO> appCoachVOList= appInstructorMapper.findCoachList();
        List<AppCategory> appCategories = appCategoryMapper.selectList(Wrappers.<AppCategory>lambdaQuery().eq(AppCategory::getDelFlag, 0));
        for (AppCoachVO appCoachVO : appCoachVOList) {
            String trainingProgramsName=getTrainingProgramsName(appCoachVO.getTrainingPrograms(),appCategories);
            appCoachVO.setTrainingProgramsName(trainingProgramsName);
        }
        return Result.ok(appCoachVOList);
    }

    @Override
    public Result<AppCoachDetailsVO> findByCoachId(AppCoachDetailsRequestVO appCoachDetailsRequestVO) {
        AppCoachDetailsVO appCoachDetailsVO = appInstructorMapper.findById(appCoachDetailsRequestVO.getId());
        if(appCoachDetailsVO==null){
            return Result.error("未查到教练信息");
        }
        List<AppCategory> appCategories = appCategoryMapper.selectList(Wrappers.<AppCategory>lambdaQuery().eq(AppCategory::getDelFlag, 0));

        String trainingProgramsName=getTrainingProgramsName(appCoachDetailsVO.getTrainingPrograms(),appCategories);
        appCoachDetailsVO.setTrainingProgramsName(trainingProgramsName);
        List<String> honorList = new ArrayList<>();
        if (StringUtils.isNotEmpty(appCoachDetailsVO.getHonor())&&appCoachDetailsVO.getHonor().indexOf(",")>0){
            honorList = Arrays.asList(appCoachDetailsVO.getHonor().split(","));
        }else {
            honorList.add(appCoachDetailsVO.getHonor());
        }
        appCoachDetailsVO.setHonorImgList(honorList);
        CourseRequestVo courseRequestVo = new CourseRequestVo();
        courseRequestVo.setInstructorId(appCoachDetailsRequestVO.getId());
        //写死默认一页50条 全部展示
        Page<CourseResponseVo> page = new Page<CourseResponseVo>(1,100);
        //查询课时列表
        Date date = new Date();
        IPage<CourseResponseVo> byCourseList = appCoursesMapper.findByCourseList(page, courseRequestVo,date);
        appCoachDetailsVO.setCourseInfoVOList(byCourseList.getRecords());
        if (appCoachDetailsVO.getCourseInfoVOList()!=null){
            for (CourseResponseVo courseResponseVo : appCoachDetailsVO.getCourseInfoVOList()) {
                int courseSales = getCourseSales(courseResponseVo.getId());
                courseResponseVo.setAnnualSalesNum(courseSales);
                int courseSalesCount = getCourseSalesCount(courseResponseVo.getId());
                courseResponseVo.setSaleNum(courseSalesCount);
//                int firstPurchase = isFirstPurchase(userId);
                int firstPurchase = 0;
                courseResponseVo.setIsOneBuy(firstPurchase);
                if (ObjectUtils.isNotEmpty(courseResponseVo.getLatitude())&&ObjectUtils.isNotEmpty(courseResponseVo.getLongitude())){
                    double km = PositionUtil.calculateDistance(appCoachDetailsRequestVO.getLatitude(), appCoachDetailsRequestVO.getLongitude(), courseResponseVo.getLatitude().doubleValue(), courseResponseVo.getLongitude().doubleValue());
                    courseResponseVo.setKm(km);
                }
                String positiveRating = evaluateMapper.findPositiveRating(courseResponseVo.getId());
                courseResponseVo.setGoodRate(positiveRating);
            }
        }
        appCoachDetailsVO.setClassesNumber((long) getInstructorTeachingNum(appCoachDetailsVO.getUserId()));
        appCoachDetailsVO.setOrderNumber((long) getInstructorOrderNum(appCoachDetailsVO.getUserId()));
        return Result.ok(appCoachDetailsVO);
    }

    /**
     * @description 根据教练ID获取教练订单数
     * params
     * @author SheepHy
     * @date 2025/9/10
     * return   {@link }
     **/
    private int getInstructorOrderNum(String id) {
        List<String> courseIds = appCoursesMapper.selectList(
                        Wrappers.<AppCourses>lambdaQuery()
                                .select(AppCourses::getId)
                                .eq(AppCourses::getUserId, id)
                ).stream()
                .map(AppCourses::getId)
                .collect(Collectors.toList());
        if(courseIds.isEmpty()) return 0;
        return Math.toIntExact(appOrderProInfoMapper.selectCount(
                Wrappers.<AppOrderProInfo>lambdaQuery()
                        .eq(AppOrderProInfo::getStatus,0)
                        .ne(AppOrderProInfo::getType,6)
                        .ne(AppOrderProInfo::getOrderStatus,0)
                        .ne(AppOrderProInfo::getOrderStatus,4)
                        .ne(AppOrderProInfo::getOrderStatus,5)
                        .ne(AppOrderProInfo::getOrderStatus,6)
                        .eq(AppOrderProInfo::getDelFlag,0)
                        .in(AppOrderProInfo::getProductId, courseIds)
        ));
    }

    /**
     * @description 根据教练ID获取授课人数(基于familyUserId去重统计)
     * @param id 教练ID
     * @author SheepHy
     * @date 2025/9/10
     * @return 去重后的授课人数
     **/
    private int getInstructorTeachingNum(String id) {
        List<String> courseIds = appCoursesMapper.selectList(
                        Wrappers.<AppCourses>lambdaQuery()
                                .select(AppCourses::getId)
                                .eq(AppCourses::getUserId, id)
                ).stream()
                .map(AppCourses::getId)
                .collect(Collectors.toList());
        if (courseIds.isEmpty()) return 0;
        // 查询不重复的familyUserId数量
        List<String> distinctFamilyUserIds = appOrderProInfoMapper.selectList(
                        Wrappers.<AppOrderProInfo>lambdaQuery()
                                .select(AppOrderProInfo::getFamilyUserId)
                                .in(AppOrderProInfo::getProductId, courseIds)
                                .ne(AppOrderProInfo::getType,6)
                                .ne(AppOrderProInfo::getOrderStatus,0)
                                .ne(AppOrderProInfo::getOrderStatus,4)
                                .ne(AppOrderProInfo::getOrderStatus,5)
                                .ne(AppOrderProInfo::getOrderStatus,6)
                                .eq(AppOrderProInfo::getStatus, 0)
                                .eq(AppOrderProInfo::getDelFlag, 0)
                                .isNotNull(AppOrderProInfo::getFamilyUserId)
                ).stream()
                .map(AppOrderProInfo::getFamilyUserId)
                .distinct()
                .collect(Collectors.toList());

        return distinctFamilyUserIds.size();
    }
    /**
     * @Author SheepHy
     * @Description 计算当前课程年销售数
     * @Date 15:47 2025/7/8
     * @Param id 课程id
     * @return int 课程年销售数
     **/
    private int getCourseSales(String id) {
        // 获取当前年份的时间范围（如：2025-01-01 00:00:00 到 2026-01-01 00:00:00）
        LocalDate now = LocalDate.now();
        LocalDateTime startOfYear = now.withDayOfYear(1).atStartOfDay(); // 当前年份第一天
        LocalDateTime endOfYear = startOfYear.plusYears(1); // 下一年第一天

        return Math.toIntExact(appOrderProInfoMapper.selectCount(
                Wrappers.<AppOrderProInfo>lambdaQuery()
                        .eq(AppOrderProInfo::getProductId, id)
                        .eq(AppOrderProInfo::getStatus,0)
                        .ne(AppOrderProInfo::getType,6)
                        .ne(AppOrderProInfo::getOrderStatus,0)
                        .ne(AppOrderProInfo::getOrderStatus,4)
                        .ne(AppOrderProInfo::getOrderStatus,5)
                        .ne(AppOrderProInfo::getOrderStatus,6)
                        .eq(AppOrderProInfo::getDelFlag,0)
                        .ge(AppOrderProInfo::getCreateTime, Date.from(startOfYear.atZone(ZoneId.systemDefault()).toInstant())) // >= 2025-01-01
                        .lt(AppOrderProInfo::getCreateTime, Date.from(endOfYear.atZone(ZoneId.systemDefault()).toInstant())) // < 2026-01-01
        ));
    }

    /**
     * @Author SheepHy
     * @Description 计算当前课程销售数
     * @Date 15:47 2025/7/8
     * @Param id 课程id
     * @return int 课程年销售数
     **/
    private int getCourseSalesCount(String id) {
        return Math.toIntExact(appOrderProInfoMapper.selectCount(
                Wrappers.<AppOrderProInfo>lambdaQuery()
                        .eq(AppOrderProInfo::getProductId, id)
                        .ne(AppOrderProInfo::getType,6)
                        .ne(AppOrderProInfo::getOrderStatus,0)
                        .ne(AppOrderProInfo::getOrderStatus,4)
                        .ne(AppOrderProInfo::getOrderStatus,5)
                        .ne(AppOrderProInfo::getOrderStatus,6)
        ));
    }

    /**
     * @Author SheepHy
     * @Description 查询用户是否为第一次购买
     * @Date 16:54 2025/7/8
     * @Param
     * @return
     **/
    private int isFirstPurchase(String userId) {
        AppOrder appOrder = appOrderMapper.selectOne(Wrappers.<AppOrder>lambdaQuery()
                .eq(AppOrder::getUpdateBy, userId).last("limit 1"));
        if(null == appOrder){
            return 1;
        }else {
            return 0;
        }
    }
    private String getTrainingProgramsName(String trainingPrograms,List<AppCategory> appCategories){
        String trainingProgramsName ="";
        if (StringUtils.isNotEmpty(trainingPrograms)&&trainingPrograms.indexOf(",")>0){
            String[] split = trainingPrograms.split(",");
            for (String s : split) {
                for (AppCategory appCategory : appCategories) {
                    if (appCategory.getId().equals(s)){
                        if (StringUtils.isNotEmpty(trainingProgramsName)){
                            trainingProgramsName=trainingProgramsName+"、"+appCategory.getName();
                        }else{
                            trainingProgramsName=appCategory.getName();
                        }
                        break;
                    }
                }
            }
        }else {
            for (AppCategory appCategory : appCategories) {
                if (appCategory.getId().equals(trainingPrograms)){
                    trainingProgramsName=appCategory.getName();
                }
            }

        }
        return trainingProgramsName;
    }
}