package com.fs.course.controller;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.fs.common.constant.HttpStatus;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.R;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.ServletUtils;
import com.fs.course.domain.StatisticsTable;
import com.fs.course.param.FsCourseOverParam;
import com.fs.course.param.FsCourseWatchLogListParam;
import com.fs.course.param.FsCourseWatchLogParam;
import com.fs.course.param.FsCourseWatchLogStatisticsListParam;
import com.fs.course.service.IFsUserCoursePeriodDaysService;
import com.fs.course.service.IFsUserCoursePeriodService;
import com.fs.course.service.IStatisticsTableService;
import com.fs.course.vo.FsCoureseWatchLogVO;
import com.fs.course.vo.FsCourseOverVO;
import com.fs.course.vo.FsCourseWatchLogListVO;
import com.fs.course.vo.FsCourseWatchLogStatisticsListVO;
import com.fs.qw.param.QwWatchLogStatisticsListParam;
import com.fs.qw.service.IQwWatchLogService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.enums.BusinessType;
import com.fs.course.domain.FsCourseWatchLog;
import com.fs.course.domain.FsUserCourse;
import com.fs.course.domain.FsUserCourseVideo;
import com.fs.course.service.IFsCourseWatchLogService;
import com.fs.course.service.IFsUserCourseService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.common.core.page.TableDataInfo;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 短链课程看课记录Controller
 *
 * @author fs
 * @date 2024-10-24
 */
@RestController
@RequestMapping("/course/courseWatchLog")
public class FsCourseWatchLogController extends BaseController
{
    @Autowired
    private IFsCourseWatchLogService fsCourseWatchLogService;

    @Autowired
    private IQwWatchLogService qwWatchLogService;
    @Autowired
    private IStatisticsTableService iStatisticsTableService;
    @Autowired
    private IFsUserCourseService fsUserCourseService;
    @Autowired
    private IFsUserCourseVideoService fsUserCourseVideoService;
    /**
     * 查询短链课程看课记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:list')")
    @PostMapping("/list")
    public R list(@RequestBody FsCourseWatchLogListParam param)
    {
        startPage();
        if(CollectionUtil.isNotEmpty(param.getUserIds())){
            param.setUserIds(param.getUserIds().stream()
                    .filter(userId -> userId != null && userId.startsWith("user_"))
                    .map(userId -> userId.substring(5))
                    .collect(Collectors.toList())
            );
        }
        List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogListVO(param);
        return R.ok().put("data", new PageInfo<>(list));
    }

    /**
     * 查询短链课程看课记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:pageList')")
    @PostMapping("/pageList")
    public R pageList(@RequestBody FsCourseWatchLogListParam param)
    {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogListVO(param);
        return R.ok().put("data", new PageInfo<>(list));
    }

    @GetMapping("/qwWatchLogAllStatisticsList")
    public TableDataInfo qwWatchLogAllStatisticsList(QwWatchLogStatisticsListParam param)
    {
        logger.info("会员课程数据汇总 参数: {}",param);

        if(param.getCompanyId() == null && (param.getUserIds() == null || param.getUserIds().isEmpty())){
            throw new CustomException("必须选择公司！");
        }
        if (param.getSTime()==null||param.getETime()==null){
            return getDataTable(new ArrayList<>());
        }
        return qwWatchLogService.selectQwWatchLogAllStatisticsListVONew(param);
    }
    @GetMapping("/qwWatchLogStatisticsList")
    public TableDataInfo qwWatchLogStatisticsList(QwWatchLogStatisticsListParam param)
    {
        if(param.getPageNum() == null){
            param.setPageNum(1L);
        }
        if(param.getPageSize() == null){
            param.setPageSize(10L);
        }
        if (param.getSTime()==null||param.getETime()==null){
            return getDataTable(new ArrayList<>());
        }
        if(param.getCompanyId() == null){
            throw new CustomException("必须选择公司！");
        }
        return qwWatchLogService.selectQwWatchLogStatisticsListVONew(param);
    }
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:statisticsList')")
    @GetMapping("/statisticsList")
    public TableDataInfo statisticsList(FsCourseWatchLogStatisticsListParam param)
    {
        // 如果看指定用户就不用设置公司
        if(param.getCompanyId() == null){
            if(param.getUserId() == null) {
                throw new CustomException("查看公司或者用户必填！");
            }
        }
        if (param.getSTime()==null||param.getETime()==null){
            throw new CustomException("必须选择开始时间和结束时间！");
        }
        startPage();
        List<FsCourseWatchLogStatisticsListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogStatisticsListVONew(param);

        return getDataTable(list);
    }

    /**
     * 会员看课统计导出
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:statisticsExport')")
    @Log(title = "会员看课统计导出", businessType = BusinessType.EXPORT)
    @PostMapping("/statisticsExport")
    public AjaxResult statisticsExport(@RequestBody FsCourseWatchLogStatisticsListParam param)
    {

        // 如果看指定用户就不用设置公司
        if(param.getCompanyId() == null){
            if(param.getUserId() == null) {
                throw new CustomException("查看公司或者用户必填！");
            }
        }
        if (param.getSTime()==null||param.getETime()==null){
            throw new CustomException("必须选择开始时间和结束时间！");
        }

        List<FsCourseWatchLogStatisticsListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogStatisticsListVONew(param);

        ExcelUtil<FsCourseWatchLogStatisticsListVO> util = new ExcelUtil<FsCourseWatchLogStatisticsListVO>(FsCourseWatchLogStatisticsListVO.class);
        return util.exportExcel(list, "会员看课统计");
    }


    /**
     * 导出短链课程看课记录列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:export')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(@RequestBody FsCourseWatchLogListParam param)
    {
        List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogListVO(param);
        ExcelUtil<FsCourseWatchLogListVO> util = new ExcelUtil<FsCourseWatchLogListVO>(FsCourseWatchLogListVO.class);
        return util.exportExcel(list, "短链课程看课记录数据");
    }

    /**
     * 获取短链课程看课记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:query')")
    @GetMapping(value = "/{logId}")
    public AjaxResult getInfo(@PathVariable("logId") Long logId)
    {
        return AjaxResult.success(fsCourseWatchLogService.selectFsCourseWatchLogByLogId(logId));
    }

    /**
     * 新增短链课程看课记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:add')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsCourseWatchLog fsCourseWatchLog)
    {
        return toAjax(fsCourseWatchLogService.insertFsCourseWatchLog(fsCourseWatchLog));
    }

    /**
     * 修改短链课程看课记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:edit')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsCourseWatchLog fsCourseWatchLog)
    {
        return toAjax(fsCourseWatchLogService.updateFsCourseWatchLog(fsCourseWatchLog));
    }

    /**
     * 删除短链课程看课记录
     */
    @PreAuthorize("@ss.hasPermi('course:courseWatchLog:remove')")
    @Log(title = "短链课程看课记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{logIds}")
    public AjaxResult remove(@PathVariable Long[] logIds)
    {
        return toAjax(fsCourseWatchLogService.deleteFsCourseWatchLogByLogIds(logIds));
    }

    @GetMapping("/watchLogStatistics")
    public TableDataInfo watchLogStatistics(FsCourseOverParam param)
    {
        startPage();
        if (param.getSTime()==null||param.getETime()==null){
            return getDataTable(new ArrayList<>());
        }
        List<FsCourseOverVO> list = fsCourseWatchLogService.selectFsCourseWatchLogOverStatisticsListVO(param);
        return getDataTable(list);
    }

    /**
     * 每个公司对应小程序观看人数统计
     *
     * @param fsCourseWatchLog
     * @return
     */
    @GetMapping("/getAppIdList")
    public TableDataInfo getAppIdList( FsCourseWatchLogParam fsCourseWatchLog) {
        startPage();
        List<StatisticsTable> statisticsTables = iStatisticsTableService.selectAppIdList(fsCourseWatchLog);
        return getDataTable(statisticsTables);
    }

    /**
     * 导出每个公司对应小程序观看人数统计
     *
     * @param fsCourseWatchLog
     * @return
     */
    @Log(title = "小程序观看人数统计", businessType = BusinessType.EXPORT)
    @GetMapping("/exportAppIdList")
    public AjaxResult exportAppIdList(FsCourseWatchLogParam fsCourseWatchLog) {
        List<StatisticsTable> statisticsTables = iStatisticsTableService.selectAppIdList(fsCourseWatchLog);
        ExcelUtil<StatisticsTable> util = new ExcelUtil<StatisticsTable>(StatisticsTable.class);
        return util.exportExcel(statisticsTables, "小程序观看人数统计数据");
    }

    /**
     * 每个公司对应观看人数统计
     *
     * @param fsCourseWatchLog
     * @return
     */
    @GetMapping("/getUserIdList")
    public TableDataInfo getUserIdList( FsCourseWatchLogParam fsCourseWatchLog) {
    if (fsCourseWatchLog.getCreateTime() == null) {
        fsCourseWatchLog.setCreateTime(new Date());
    }
        startPage();
        List<FsCoureseWatchLogVO> list = fsCourseWatchLogService.selectUserIdList(fsCourseWatchLog);
        TableDataInfo dataTable = getDataTable(list);
        // 清除分页后再查全量合计，避免 PageHelper 影响汇总 SQL
        PageHelper.clearPage();
        FsCoureseWatchLogVO summary = fsCourseWatchLogService.selectUserIdListSummary(fsCourseWatchLog);
        dataTable.put("summary", summary);
        return dataTable;
    }

    /**
     * 导出每个公司对应观看人数统计
     *
     * @param fsCourseWatchLog
     * @return
     */
    @Log(title = "公司观看人数统计", businessType = BusinessType.EXPORT)
    @GetMapping("/exportUserIdList")
    public AjaxResult exportUserIdList(FsCourseWatchLogParam fsCourseWatchLog) {
        List<FsCoureseWatchLogVO> list = fsCourseWatchLogService.selectUserIdList(fsCourseWatchLog);
        ExcelUtil<FsCoureseWatchLogVO> util = new ExcelUtil<FsCoureseWatchLogVO>(FsCoureseWatchLogVO.class);
        return util.exportExcel(list, "公司观看人数统计数据");
    }

    /**
     * 按项目查询课程下拉（完播统计）
     */
    @GetMapping("/listCoursesByProject")
    public AjaxResult listCoursesByProject(@RequestParam("project") Long project) {
        if (project == null) {
            return AjaxResult.error("请先选择项目");
        }
        FsUserCourse query = new FsUserCourse();
        query.setProject(project);
        List<FsUserCourse> courses = fsUserCourseService.selectFsUserCourseList(query);
        List<FsUserCourse> result = new ArrayList<>();
        if (courses != null) {
            for (FsUserCourse course : courses) {
                if (course.getIsDel() == null || course.getIsDel() == 0) {
                    result.add(course);
                }
            }
            result.sort((a, b) -> {
                Long sa = a.getSort() == null ? Long.MAX_VALUE : a.getSort();
                Long sb = b.getSort() == null ? Long.MAX_VALUE : b.getSort();
                int cmp = sa.compareTo(sb);
                if (cmp != 0) {
                    return cmp;
                }
                Long ida = a.getCourseId() == null ? 0L : a.getCourseId();
                Long idb = b.getCourseId() == null ? 0L : b.getCourseId();
                return ida.compareTo(idb);
            });
        }
        return AjaxResult.success(result);
    }

    /**
     * 按课程查询小节下拉（完播统计小节区间）
     */
    @GetMapping("/listVideosByCourse")
    public AjaxResult listVideosByCourse(@RequestParam("courseId") Long courseId) {
        if (courseId == null) {
            return AjaxResult.error("请先选择课程");
        }
        FsUserCourseVideo query = new FsUserCourseVideo();
        query.setCourseId(courseId);
        query.setIsDel(0);
        List<FsUserCourseVideo> videos = fsUserCourseVideoService.selectFsUserCourseVideoList(query);
        if (videos == null) {
            videos = new ArrayList<>();
        } else {
            // 按 course_sort、video_id 排序，与统计解析顺序一致
            videos.sort((a, b) -> {
                Long sa = a.getCourseSort() == null ? Long.MAX_VALUE : a.getCourseSort();
                Long sb = b.getCourseSort() == null ? Long.MAX_VALUE : b.getCourseSort();
                int cmp = sa.compareTo(sb);
                if (cmp != 0) {
                    return cmp;
                }
                Long ida = a.getVideoId() == null ? 0L : a.getVideoId();
                Long idb = b.getVideoId() == null ? 0L : b.getVideoId();
                return ida.compareTo(idb);
            });
        }
        return AjaxResult.success(videos);
    }
}
