package com.fs.app.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fs.app.annotation.Login;
import com.fs.app.config.ImageStorageConfig;
import com.fs.common.annotation.Log;
import com.fs.common.core.domain.R;
import com.fs.common.core.domain.ResponseResult;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyMiniapp;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyMiniappService;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.course.config.CourseConfig;
import com.fs.config.cloud.CloudHostProper;
import com.fs.course.domain.FsUserCoursePeriod;
import com.fs.course.dto.BatchSendCourseDTO;
import com.fs.course.dto.BatchUrgeCourseDTO;
import com.fs.course.param.FsCourseLinkCreateParam;
import com.fs.course.param.FsCourseWatchLogListParam;
import com.fs.course.param.FsWatchCourseTimeParam;
import com.fs.course.param.newfs.FsCourseSortLinkParam;
import com.fs.course.param.newfs.FsCourseWatchAppParam;
import com.fs.course.param.newfs.FsUserCourseListParam;
import com.fs.course.param.newfs.UserCourseVideoPageParam;
import com.fs.course.service.*;
import com.fs.course.vo.FsCourseWatchLogListVO;
import com.fs.course.vo.FsUserCourseParticipationRecordVO;
import com.fs.course.vo.FsUserCourseTrainingCampVO;
import com.fs.course.vo.newfs.*;
import com.fs.im.domain.FsImMsgSendLog;
import com.fs.im.dto.OpenImResponseDTO;
import com.fs.im.service.IFsImMsgSendDetailService;
import com.fs.im.service.IFsImMsgSendLogService;
import com.fs.im.service.OpenIMService;
import com.fs.im.vo.FsImMsgSendLogVO;
import com.fs.system.service.ISysConfigService;
import com.fs.live.service.ILiveService;
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 me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import javax.validation.Valid;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;


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

    @Autowired
    private IFsUserCourseVideoService fsUserCourseVideoService;

    @Autowired
    private ICompanyService iCompanyService;

    @Autowired
    private IFsUserCourseService fsUserCourseService;

    @Autowired
    private IFsUserCourseTrainingCampService fsUserCourseTrainingCampService;

    @Autowired
    private IFsCourseLinkService courseLinkService;

    @Autowired
    private ImageStorageConfig imageConfig;

    @Autowired
    private IFsUserCoursePeriodService fsUserCoursePeriodService;
    @Autowired
    private ICompanyUserService companyUserService;

    @Autowired
    private IFsCourseWatchLogService fsCourseWatchLogService;

    @Autowired
    private OpenIMService openIMService;

    @Autowired
    private IFsImMsgSendLogService imMsgSendLogService;
    @Autowired
    private ILiveService liveService;

    @Autowired
    private ICompanyMiniappService companyMiniappService;

    @Autowired
    private CloudHostProper cloudHostProper;

    @Autowired
    private ISysConfigService configService;

    private final String FANG_HUA_APP_ID = "wx503cf8ab31f83dd4";

    @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("/getLoginMiniAppId/{appId}")
//    public R getLoginMiniAppId(@PathVariable String appId) {
//        CompanyMiniapp params =  new CompanyMiniapp();
//        params.setCompanyId(getCompanyId());
//        List<CompanyMiniapp> miniApps = companyMiniappService.selectCompanyMiniappList(params);
//        if (miniApps != null) {
//            appId = miniApps.stream().min(Comparator.comparing(CompanyMiniapp::getSortNum)).map(CompanyMiniapp::getAppId).orElse(appId);
//        }
//
//        return R.ok().put("data", appId);
//    }
    @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
    @PostMapping("/list")
    @ApiOperation("获取营期下拉列表")
    public ResponseResult<PageInfo<FsUserCourseListVO>> getAllList(@Valid @RequestBody FsUserCourseListParam param) {
        log.info("查询营期列表 - 参数: trainingCampId={}, companyId={}, keyword={}, pageNum={}, pageSize={}",
                param.getTrainingCampId(), getCompanyId(), param.getKeyword(), param.getPageNum(), param.getPageSize());

        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        param.setCompanyId(getCompanyId());
        List<FsUserCourseListVO> fsUserCourseList = fsUserCourseService.getFsUserList(param);
        log.info("查询营期列表 - 结果数量: {}", fsUserCourseList.size());

        PageInfo<FsUserCourseListVO> pageInfo = new PageInfo<>(fsUserCourseList);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @GetMapping("/trainingCampList")
    @ApiOperation("获取训练营下拉列表")
    public ResponseResult<PageInfo<FsUserCourseTrainingCampVO>> getTrainingCampList(
            @RequestParam(required = false) String keyword) {
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", getCompanyId());
        if (StringUtils.isNotEmpty(keyword)) {
            params.put("trainingCampName", keyword);
        }
        List<FsUserCourseTrainingCampVO> list = fsUserCourseTrainingCampService.selectTrainingCampListForApp(params);
        return ResponseResult.ok(new PageInfo<>(list));
    }

    @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) Long periodId,
                                                      @RequestParam(required = false) String keyword,
                                                      @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                      @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        log.debug("参与记录 videoId:{}, type:{}, keyword: {}, pageNum: {}, pageSize: {}", videoId, type, keyword, pageNum, pageSize);
        Map<String, Object> params = new HashMap<>();
        params.put("videoId", videoId);
        params.put("periodId", periodId);
        params.put("type", type);
        params.put("keyword", keyword);

        // type 0 答题领奖记录----答题正确并且领取红包的
        // type 1 完播----这堂课看完的人
        // type 2 未完播---看课中断
        // 管理员看整个公司 否则看自己的
        CompanyUser companyUser = companyUserService.selectCompanyUserByUserId(Long.parseLong(getUserId()));
        if (companyUser.isAdmin()) {
            params.put("companyId", companyUser.getCompanyId());
        } else {
            params.put("companyUserId", companyUser.getUserId());
        }
        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();
        String linkId=courseSortLink.get("linkId").toString();
        Map<String, Object> map = new HashMap<>();
        map.put("url", url);
        map.put("linkId", linkId);
        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, String keyword) {
        Long companyId = getCompanyId();
        log.info("销售小程序-今日课程，获取公司id：{}", companyId);
        if (Objects.isNull(companyId)) {
            log.error("未获取到公司id，进入提示逻辑。。。。。。。。");
            return 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()));
        params.put("keyword", keyword);

        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);
    }

    @GetMapping("/getProjectCode")
    public R getProjectCode() {
        return courseLinkService.getProjectCode();
    }


    /**
     * 获取跳转微信小程序的链接地址
     */
    @Login
    @GetMapping("/getGotoWxAppLink")
    @ApiOperation("获取跳转微信小程序的链接地址")
    public ResponseResult<String> getGotoWxAppLink(String linkStr,String appid) throws IOException, WxErrorException {

        if ("河山医院".equals(cloudHostProper.getCompanyName())){
            return ResponseResult.ok(courseLinkService.generateShortLinkFull(appid,linkStr,false));
        }

        return ResponseResult.ok(courseLinkService.getGotoWxAppLink(linkStr,appid));
    }

    @GetMapping("/getGotoAppLink")
    @ApiOperation("获取跳转微信小程序的链接地址")
    public ResponseResult<String> getGotoWxAppLink(String linkStr, Long companyId) {
        Company company = iCompanyService.selectCompanyById(companyId);
        String appid = null;
        if (CollectionUtils.isNotEmpty(company.getMiniAppMaster())){
            appid = company.getMiniAppMaster().get(0);
        }else if (CollectionUtils.isNotEmpty(company.getMiniAppServer())){
            appid = company.getMiniAppServer().get(0);
        }else {
            return ResponseResult.fail(500,"请在后台配置主备小程序！");
        }
        return ResponseResult.ok(courseLinkService.getGotoWxAppLink(linkStr,appid));
    }
    /**
     * 获取跳转微信小程序的链接地址
     */
    @Login
    @GetMapping("/getGotoWxAppLiveLink")
    @ApiOperation("获取跳转微信小程序直播的链接地址")
    public ResponseResult<String> getGotoWxAppLiveLink(String linkStr,String appid) {
        return ResponseResult.ok(liveService.getGotoWxAppLiveLink(linkStr,appid));
    }

    @ApiOperation("会员批量发送课程消息")
    @PostMapping("/batchSendCourse")
    public OpenImResponseDTO batchSendCourse(@RequestBody BatchSendCourseDTO batchSendCourseDTO) throws JsonProcessingException {
        // 生成看课短链
        FsCourseLinkCreateParam fsCourseLinkCreateParam = new FsCourseLinkCreateParam();
        BeanUtils.copyProperties(batchSendCourseDTO, fsCourseLinkCreateParam);
        R courseSortLink = fsUserCourseService.createAppCourseSortLink(fsCourseLinkCreateParam);
        String url = courseSortLink.get("url").toString();
        batchSendCourseDTO.setUrl(url);
        batchSendCourseDTO.setIsUrgeCourse(false);
        return openIMService.batchSendCourse(batchSendCourseDTO);
    }

    @ApiOperation("会员一键催课")
    @PostMapping("/batchUrgeCourse")
    public OpenImResponseDTO batchUrgeCourse(@RequestBody BatchUrgeCourseDTO batchUrgeCourseDTO) throws JsonProcessingException {
        // 查询生成短链需要的内容
        Map<String, Object> params = new HashMap<>();
        params.put("logDetailIds", batchUrgeCourseDTO.getImMsgSendDetailId());
        List<FsImMsgSendLog> fsImMsgSendLogs = imMsgSendLogService.selectSendLogListByDetailId(params);
        OpenImResponseDTO openImResponseDTO = null;
        for (FsImMsgSendLog fsImMsgSendLog : fsImMsgSendLogs) {
            FsCourseLinkCreateParam fsCourseLinkCreateParam = new FsCourseLinkCreateParam();
            BeanUtils.copyProperties(fsImMsgSendLog, fsCourseLinkCreateParam);
            fsCourseLinkCreateParam.setId(fsImMsgSendLog.getPeriodDaysId());
            R courseSortLink = fsUserCourseService.createAppCourseSortLink(fsCourseLinkCreateParam);
            String url = courseSortLink.get("url").toString();
            openImResponseDTO = openIMService.batchUrgeCourse(batchUrgeCourseDTO, fsImMsgSendLog, url);
        }
        return openImResponseDTO;
    }

    @Login
    @ApiOperation("app-看课记录（包含今日完课、今日催课）")
    @GetMapping("/courseWatchLog")
    public ResponseResult<PageInfo<FsCourseWatchLogListVO>> getCourseWatchLog(FsCourseWatchAppParam fsCourseWatchAppParam)
    {
        FsCourseWatchLogListParam param = new FsCourseWatchLogListParam();
        BeanUtils.copyProperties(fsCourseWatchAppParam, param);
        param.setCompanyUserId(Long.parseLong(getUserId()));
        param.setCompanyId(getCompanyId());
        param.setSTime(DateUtil.formatDate(DateUtil.beginOfDay(new Date())));
        param.setETime(DateUtil.formatDate(DateUtil.endOfDay(new Date())));
//        startPage();
        PageHelper.startPage(fsCourseWatchAppParam.getPageNum (), fsCourseWatchAppParam.getPageSize());
        List<FsCourseWatchLogListVO> list = fsCourseWatchLogService.selectFsCourseWatchLogListVO(param);
        PageInfo<FsCourseWatchLogListVO> pageInfo = new PageInfo<>(list);
        return ResponseResult.ok(pageInfo);
    }

    @Login
    @ApiOperation("任务列表")
    @GetMapping("/im/sendLog")
    public ResponseResult<PageInfo<FsImSendLogVO>> imSendLog(@RequestParam(defaultValue = "1") Integer pageNum,
                                                             @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> params = new HashMap<>();
        params.put("companyId", getCompanyId());
        params.put("companyUserId", Long.parseLong(getUserId()));

        PageHelper.startPage(pageNum, pageSize);
        List<FsImSendLogVO> list = imMsgSendLogService.selectFsImSendLogList(params);
        PageInfo<FsImSendLogVO> pageInfo = new PageInfo<>(list);
        return ResponseResult.ok(pageInfo);
    }

    @ApiOperation("任务详情")
    @GetMapping("/im/sendLog/detail")
    public ResponseResult<FsImMsgSendLogVO> imSendLogDetail(@RequestParam Long logId) {
        FsImMsgSendLogVO fsImMsgSendLogVO = imMsgSendLogService.selectFsImMsgSendLogDetail(logId);
        return ResponseResult.ok(fsImMsgSendLogVO);
    }

    @Login
    @ApiOperation("删除任务")
    @DeleteMapping("/im/sendLog")
    @Log(title = "任务-删除任务", businessType = BusinessType.DELETE)
    public ResponseResult<Boolean> deleteImSendLog(@RequestParam Long logId) {
        return imMsgSendLogService.deleteFsImMsgSendLogAndDetail(logId);
    }



    @ApiOperation("获取登录小程id值")
    @GetMapping("/getLoginMiniAppId/{appId}")
    public ResponseResult getLoginMiniAppId(@PathVariable String appId){
        String json = configService.selectConfigByKey("course.config");
        if(null == json || com.hc.openapi.tool.util.StringUtils.isBlank(json)){
            ResponseResult.fail(500,"请先配置课程系统参数");
        }
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        //判断配置的appid是否为芳华惠选appid 如果配置了直接返回芳华惠选的appid
        if(null != config && StringUtils.isNotBlank(config.getLoginMiniAppId())){
            String loginMiniAppId = config.getLoginMiniAppId();
            if(FANG_HUA_APP_ID.equals(loginMiniAppId)){
                return ResponseResult.ok(FANG_HUA_APP_ID);
            }
        }

        return ResponseResult.ok(appId);
    }
}
