package com.fs.app.controller;

import com.fs.app.annotation.Login;
import com.fs.app.config.ImageStorageConfig;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.common.utils.StringUtils;
import com.fs.course.domain.FsUserCoursePeriod;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.param.newfs.FsCourseSortLinkParam;
import com.fs.course.param.newfs.FsUserCourseListParam;
import com.fs.course.param.newfs.FsWatchCourseTimeParam;
import com.fs.course.param.newfs.UserCourseVideoPageParam;
import com.fs.course.service.IFsCourseLinkService;
import com.fs.course.service.IFsUserCoursePeriodService;
import com.fs.course.service.IFsUserCourseService;
import com.fs.course.service.IFsUserCourseVideoService;
import com.fs.course.vo.FsUserCourseParticipationRecordVO;
import com.fs.course.vo.newfs.FsUserCourseListVO;
import com.fs.course.vo.newfs.FsUserCourseVideoDetailsVO;
import com.fs.course.vo.newfs.FsUserCourseVideoPageListVO;
import com.fs.course.vo.newfs.FsUserVideoListVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Api("课程库相关接口")
@RestController
@RequestMapping("/app/fs/course")
@Slf4j
public class FsUserCourseVideoController extends AppBaseController {

    @Autowired
    private IFsUserCourseVideoService fsUserCourseVideoService;

    @Autowired
    private IFsUserCourseService fsUserCourseService;

    @Autowired
    private IFsCourseLinkService courseLinkService;

    @Autowired
    private ImageStorageConfig imageConfig;

    @Autowired
    private IFsUserCoursePeriodService fsUserCoursePeriodService;

    @Login
    @GetMapping("/pageList")
    @ApiOperation("课程分页列表")
    public ResponseResult<PageInfo<FsUserCourseVideoPageListVO>> list(UserCourseVideoPageParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(getCompanyId());
        param.setCompanyUserId(Long.parseLong(getUserId()));
        List<FsUserCourseVideoPageListVO> list = fsUserCourseVideoService.pageListCourseVideo(param);
        PageInfo<FsUserCourseVideoPageListVO> pageInfo = new PageInfo<>(list);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @ApiOperation("课程视频详情")
    @GetMapping(value = "/videoDetails")
    public ResponseResult<FsUserCourseVideoDetailsVO> getVideoDetails(Long videoId) {
        return fsUserCourseVideoService.getVideoDetails(videoId);
    }

    @Login
    @GetMapping("/courseList")
    @ApiOperation("获取课程下拉列表")
    public ResponseResult<PageInfo<FsUserCourseListVO>> getAllCourseList(FsUserCourseListParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(getCompanyId());
        List<FsUserCourseListVO> fsUserCourseList = fsUserCourseService.getFsUserCourseList(param);
        PageInfo<FsUserCourseListVO> pageInfo = new PageInfo<>(fsUserCourseList);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @GetMapping("/videoList")
    @ApiOperation("获取视频下拉列表")
    public ResponseResult<PageInfo<FsUserVideoListVO>> getAllVideoList(UserCourseVideoPageParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(getCompanyId());
        List<FsUserVideoListVO> listCourseVideo = fsUserCourseVideoService.getListCourseVideo(param);
        PageInfo<FsUserVideoListVO> result = new PageInfo<>(listCourseVideo);
        return ResponseResult.ok(result);
    }

    @Login
    @ApiOperation("参与记录")
    @GetMapping("/participationRecord")
    public ResponseResult<Object> participationRecord(@RequestParam Long videoId,
                                                      @RequestParam Integer type,
                                                      @RequestParam(required = false) String keyword,
                                                      @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                      @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.debug("参与记录 keyword: {}, pageNum: {}, pageSize: {}", keyword, pageNum, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("videoId", videoId);
        params.put("type", type);
        params.put("keyword", keyword);

        PageHelper.startPage(pageNum, pageSize);
        List<FsUserCourseParticipationRecordVO> record = fsUserCourseService.getParticipationRecordByMap(params);
        return ResponseResult.ok(new PageInfo<>(record));
    }

    @Login
    @PostMapping("/courseSortLink")
    @ApiOperation("生成课程分享短链")
    public R createCourseSortLink(@RequestBody FsCourseSortLinkParam param) {
        FsCourseLinkCreateParam fsCourseLinkCreateParam = new FsCourseLinkCreateParam();
        BeanUtils.copyProperties(param, fsCourseLinkCreateParam);

        R courseSortLink = fsUserCourseService.createCourseSortLink(fsCourseLinkCreateParam);
        String url = courseSortLink.get("url").toString();
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        return R.ok(map);
    }

    @Login
    @PostMapping("/courseImage")
    @ApiOperation("生成课程海报")
    public R createCourseImage(@RequestBody FsCourseSortLinkParam param) {
        // 获取生成链接
        FsCourseLinkCreateParam fsCourseLinkCreateParam = new FsCourseLinkCreateParam();
        BeanUtils.copyProperties(param, fsCourseLinkCreateParam);

        R courseSortLink = fsUserCourseService.createCourseSortLink(fsCourseLinkCreateParam);
        String link = courseSortLink.get("link").toString();
        R r = courseLinkService.getRealLink(link);
        String realLink = r.get("realLink").toString();
        try {
            String path = imageConfig.getServerPath();
            log.info("获取的logo图片路径，fileUrl：{}", path);
            InputStream inputStream = fsUserCourseService.handleImage("", path);

            // 获取营期的课程风格url
            String imgUrl;
            FsUserCoursePeriod fsUserCoursePeriod = fsUserCoursePeriodService.selectFsUserCoursePeriodById(param.getPeriodId());
            if (fsUserCoursePeriod != null) {
                imgUrl = fsUserCoursePeriod.getCourseStyle();
            } else {
                imgUrl = param.getImgUrl();
            }
            if(StringUtils.isEmpty(imgUrl)){
                return R.error(400, "营期风格图片或课程封面不能为空！");
            }

            String base64Image = fsUserCourseService.createCourseImageQR(realLink, imgUrl, inputStream, "png", param.getTitle(), param.getDuration());
            // 返回Base64编码的图片字符串
            Map<String, Object> map = new HashMap<>();
            map.put("url", base64Image);
            return R.ok().put("posterImage", map);
        } catch (Exception e) {
            log.error("生成海报失败，param：{}", param);
            return R.error("生成海报失败！");
        }
    }


//    @Login
//    @PostMapping("/sortLink/courseMember")
//    @ApiOperation("生成分享成为会员短链")
//    public R createCourseMemberSortLink(@RequestBody FsUserCourseBeMemberParam param) {
//        FsCourseLinkCreateParam fsCourseLinkCreateParam = new FsCourseLinkCreateParam();
//        BeanUtils.copyProperties(param, fsCourseLinkCreateParam);
//
//        R courseSortLink = fsUserCourseService.createCourseMemberSortLink(fsCourseLinkCreateParam);
//        String url = courseSortLink.get("url").toString();
//        Map<String, Object> map = new HashMap<>();
//        map.put("url", url);
//        return R.ok(map);
//    }

    @Login
    @GetMapping("/todayCourseList")
    @ApiOperation("今日课程")
    public ResponseResult<PageInfo<FsUserCourseVideoPageListVO>> todayCourseList(@RequestParam(defaultValue = "1") Integer pageNum,
                                                                                 @RequestParam(defaultValue = "10") Integer pageSize) {
        Long companyId = getCompanyId();
        if (Objects.isNull(companyId)) {
            ResponseResult.fail(400, "未获取到公司ID,请重新登录后再试");
        }

        Map<String, Object> params = new HashMap<>();
        params.put("companyId", companyId);
        params.put("dayDate", LocalDate.now());
        params.put("companyUserId", Long.parseLong(getUserId()));

        PageHelper.startPage(pageNum, pageSize);
        List<FsUserCourseVideoPageListVO> list = fsUserCourseVideoService.selectCourseVideoListByMap(params);
        PageInfo<FsUserCourseVideoPageListVO> pageInfo = new PageInfo<>(list);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @PostMapping("/setWatchTime")
    @ApiOperation("销售设置课程时间")
    public ResponseResult<Boolean> setWatchCourseTime(@RequestBody List<FsWatchCourseTimeParam> paramList) {
        List<FsWatchCourseTimeParam> collect = paramList.stream().peek(v -> {
            v.setCompanyUserId(Long.parseLong(getUserId()));
            v.setCompanyId(getCompanyId());
        }).collect(Collectors.toList());
        return fsUserCourseVideoService.setWatchCourseTime(collect);
    }


}
