package com.yizhi.application.course.controller;


import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.Certificate.CertificateUtills.PushCertificateUtil;
import com.yizhi.application.course.utils.StuWorkUtil;
import com.yizhi.application.tools.PageTools;
import com.yizhi.application.util.HtmlTagUtil;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.feign.CommClient;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.CoursePcClient;
import com.yizhi.course.application.feign.MaterialClient;
import com.yizhi.course.application.vo.*;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.site.application.enums.FunctionTypeCode;
import com.yizhi.site.application.feign.api.FunctionDisplayConfigApiClients;
import com.yizhi.site.application.vo.domain.FunctionDisplayConfigVo;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.system.application.system.remote.SiteClient;
import com.yizhi.system.application.vo.SiteVO;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

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

@Api(tags = "学员端-课程相关接口")
@RestController
@RequestMapping("/api/course")
public class CourseApiController {

    @Autowired
    CourseClient courseClient;

    @Autowired
    CommClient commClient;

    @Autowired
    MaterialClient materialClient;

    @Autowired
    private AccountClient accountClient;

    @Autowired
    private FunctionDisplayConfigApiClients configApiClients;

    @Autowired
    private StuWorkUtil stuWorkUtil;

    @Autowired
    private CoursePcClient coursePcClient;

    @Autowired
    private PushCertificateUtil pushCertificateUtil;

    @Autowired
    private SiteClient siteClient;

    private static final Logger logger = LoggerFactory.getLogger(CourseApiController.class);

    @Value("${ACTIVE}")
    private String active;

    @ApiOperation(value = "获取我的课程统计信息", notes = "指定课程我的学习次数和学习时长", response = CourseStudyStatisticVO.class)
    @GetMapping("/study/statistic")
    public Response<CourseStudyStatisticVO> getCourseStudyStatistic(@RequestParam("courseId") Long courseId) {
        RequestContext requestContext = ContextHolder.get();
        return Response.ok(courseClient.getCourseStudyStatistic(courseId,requestContext.getAccountId()));
    }

    @ApiOperation(value = "获取我的课程学习记录列表", notes = "指定课程我的学习记录的开始时间，学习时长等数据", response = RecordeVO.class)
    @GetMapping("/study/recorde")
    public Response<RecordeVO> getCourseStudyRecorde(@RequestParam("courseId") Long courseId) {
        RequestContext requestContext = ContextHolder.get();
        return Response.ok(courseClient.getCourseStudyRecorde(courseId,requestContext.getAccountId()));
    }

        // 微信课程【首页--课程分类】--单个课程列表接口
    @GetMapping("/list")
    @ApiOperation(value = "课程分页查询", notes = "返回分页结果集", response = ApiListCourseVo.class)
    public Response list(
            @ApiParam(name = "name", value = "课程名称", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(name = "classifyId", value = "分类id", required = false) @RequestParam(name = "classifyId", required = false) Long classifyId,
            @ApiParam(name = "type", value = "1 为默认更新时间排序，2 按评分排序", required = true) @RequestParam(name = "type", required = true, defaultValue = "1") Integer type,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize
    ) {
        ApiSeachCourseVo apiSeachCourseVo = new ApiSeachCourseVo();
        apiSeachCourseVo.setName(name);
        apiSeachCourseVo.setClassifyId(classifyId);
        apiSeachCourseVo.setType(type);
        apiSeachCourseVo.setPageSize(pageSize);
        apiSeachCourseVo.setPageNo(pageNo);
        RequestContext requestContext = ContextHolder.get();
        apiSeachCourseVo.setIds(requestContext.getRelationIds());
        if (StringUtils.isEmpty(requestContext)) {
            apiSeachCourseVo.setAccountId(0L);
            apiSeachCourseVo.setCompanyId(0L);
            apiSeachCourseVo.setSiteId(0L);
        } else {
            apiSeachCourseVo.setAccountId(requestContext.getAccountId());
            apiSeachCourseVo.setCompanyId(requestContext.getCompanyId());
            apiSeachCourseVo.setSiteId(requestContext.getSiteId());
        }
        Page<ApiListCourseVo> apiListCourseVos = courseClient.searchPageSubClassify(apiSeachCourseVo);
        // 添加课程是否显示学时
        List<ApiListCourseVo> inData = apiListCourseVos.getRecords();
        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(inData)){
            List<FunctionDisplayConfigVo> dataFunction = configApiClients.getAllBySiteId();
            boolean courseDurationShow = false;
            if(org.apache.commons.collections.CollectionUtils.isNotEmpty(dataFunction)){
                for(FunctionDisplayConfigVo item : dataFunction){
                    if(FunctionTypeCode.COURSE.getCode()
                            .equals(item.getFunctionType())){
                        courseDurationShow = item.getShowDisplay();
                    }
                }
            }
            // 增加课程学习状态显示
            List<Long> courseIds = inData.stream().map(objItem->objItem.getId()).collect(Collectors.toList());
            //logger.info("课程id列表={}", JSON.toJSONString(courseIds));
            List<CourseStudentStatusVO> statusList = coursePcClient.getStatusByIds(courseIds);
            Map<Long,Integer> statusMap = new HashMap<>();
            if(CollectionUtils.isNotEmpty(statusList)){
                statusMap = statusList.stream().collect(Collectors.toMap(key->key.getCourseId(),val->val.getStudentStatus()));
            }

            for(ApiListCourseVo obj : inData){
                // 增加课程学习状态显示
                Long courseIdTmp = obj.getId();
                obj.setStudentStatus(-1);
                if(statusMap.containsKey(courseIdTmp)){
                    Integer statu = statusMap.get(courseIdTmp);
                    //logger.info("课程学习状态statu={}", JSON.toJSONString(statusMap));
                    if(Objects.nonNull(statu)){
                        obj.setStudentStatus(statu);
                    }
                }
                obj.setCourseDurationShow(courseDurationShow);
            }
        }
        // 微信查询不添加时长
        /*List<ApiListCourseVo> dataR = apiListCourseVos.getRecords();
        if(!CollectionUtils.isEmpty(dataR)){
            // 查询课程的总学习时长
            Map<Long, Long> courseDuration = coursePcClient.getMaterialTimeByCourseIds(dataR.stream().map(stuCourse->stuCourse.getId())
                    .collect(Collectors.toList()));
            for(ApiListCourseVo itemObj : dataR){
                Long currCourseId = itemObj.getId();
                Long durationTem = courseDuration.get(currCourseId);
                itemObj.setDuration(durationTem==null?0:Integer.valueOf(durationTem.toString()));
            }
        }*/
        return Response.ok(apiListCourseVos);
    }

    //2018.09.13添加扫码查看接口
    @GetMapping("/get/scan")
    @ApiOperation(value = "课程查看扫码查看", notes = "课程查看扫码查看", response = CourseDetailsVo.class)
    public Response getScan(
            @ApiParam(value = "课程主键id", required = true) @RequestParam("id") Long id) {
        RequestContext requestContext = ContextHolder.get();
        Long accountId = requestContext.getAccountId();
        List<Long> relationIds = requestContext.getRelationIds();
        Long siteId = requestContext.getSiteId();
        boolean isPass = false;
        CourseEntityVo course = courseClient.view(id);
        if (course.getScope() != null && course.getScope() == 1) {
            if (siteId != null && course.getSiteId() != null && siteId.equals(course.getSiteId())) {
                isPass = true;
            }
        } else if (course.getScope() != null && course.getScope() == 2) {
            List<Long> rangeIds = courseClient.getRange(id);
            if (rangeIds.contains(accountId)) {
                isPass = true;
            } else {
                for (Long relationId : relationIds) {
                    if (rangeIds.contains(relationId)) {
                        isPass = true;
                        break;
                    }
                }
            }
        }
        if (isPass) {
            return get(id);
        } else {
            return Response.fail("4001", "无权访问");
        }
    }

    @GetMapping("/chapters/get")
    @ApiOperation(value = "课程详情-章节列表信息（拆分）", notes = "课程详情-章节列表信息（拆分）", response = ChapterDetailsVo.class)
    public Response<ChapterDetailsVo> getChapter(
            @ApiParam(value = "课程主键id", required = true) @RequestParam("id") Long id) {
        List<ChapterDetailsVo> chapterDetailsVos = courseClient
                .getChapter(id, ContextHolder.get().getAccountId());
        if(chapterDetailsVos != null && chapterDetailsVos.size() == 1){
            ChapterDetailsVo vo = chapterDetailsVos.get(0);
            if(ChapterDetailsVo.NOT_EXACTLY_MSG.equals(vo.getName())){
                return Response.fail(Constants.COURSE_MSG_COURSE_DETAIL_NON_EXISTENT.getCode().toString(),
                        Constants.COURSE_MSG_COURSE_DETAIL_NON_EXISTENT.getName());
            }
        }
        return Response.ok(chapterDetailsVos);

    }

    @GetMapping("/get")
    @ApiOperation(value = "课程查看", notes = "课程查看", response = CourseDetailsVo.class)
    public Response get(
            @ApiParam(value = "课程主键id", required = true) @RequestParam("id") Long id) {
        RequestContext requestContext = ContextHolder.get();
        CourseDetailsVo courseDetailsVo = courseClient.get(id, requestContext.getAccountId());
        if (null == courseDetailsVo) {
            return Response.fail(Constants.COURSE_MSG_COURSE_DETAIL_QUERY_FAIL.getCode().toString(),
                    Constants.COURSE_MSG_COURSE_DETAIL_QUERY_FAIL.getName());
        }
        CourseVo vo = courseDetailsVo.getCourseVo();
        if(vo == null ){
            return Response.fail(Constants.COURSE_MSG_COURSE_DETAIL_NON_EXISTENT.getCode().toString(),
                    Constants.COURSE_MSG_COURSE_DETAIL_NON_EXISTENT.getName());
        }else if(!requestContext.getSiteId().equals(vo.getSiteId())){
            return Response.fail(Constants.COURSE_MSG_COURSE_ACCESS_SITE_DIFFERENT.getCode().toString(),
                    Constants.COURSE_MSG_COURSE_ACCESS_SITE_DIFFERENT.getName());
        }
        // 获取站点佩在信息
        SiteVO siteVO = siteClient.selectById(vo.getSiteId());
        if(siteVO != null){
            vo.setVideoRate(siteVO.getVideoRate());
        }
        Boolean vailExplanation = null != courseDetailsVo && null != courseDetailsVo.getMaterialVo() && null != courseDetailsVo.getMaterialVo().getExplanation();
        if (vailExplanation) {
            courseDetailsVo.getMaterialVo().setExplanation(HtmlTagUtil.deleteAllHTMLTag(courseDetailsVo.getMaterialVo().getExplanation()));
        }

        // 自动发放证书（异步调用）
        CourseVo courseVo = courseDetailsVo.getCourseVo();
        if(Boolean.TRUE.equals(courseVo.getGrantCertificate()) && courseDetailsVo.getStudentStatus().intValue()==1){
            // Arrays.asList() 数组转list
            String[] certificateStr = courseVo.getCertificateStr().split(",");
            List<Long> cIds = new ArrayList<>();
            for(String str:certificateStr){
                cIds.add(Long.valueOf(str));
            }
            pushCertificateUtil.pushCertificate(1,courseVo.getId(),courseVo.getName(),cIds);
        }
        return Response.ok(courseDetailsVo);

    }

    @GetMapping("/comment/list")
    @ApiOperation(value = "课程查看评论", notes = "课程查看评论", response = ApiCommnentVo.class)
    public Response commentList(
            @ApiParam(value = "课程主键id", required = true) @RequestParam("id") Long id,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认20条", required = true) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize
    ) {
        RequestContext requestContext = ContextHolder.get();
        Page<ApiCommnentVo> page = commClient.apiList(id, requestContext.getAccountId(), pageNo, pageSize);

        page = stuWorkUtil.fillData(page,requestContext);

        return Response.ok(page);
    }

    /**
     * 微信--》课程--》首页列表
     * @param name
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/homePage/list")
    @ApiOperation(value = "课程首页查看", notes = "课程首页查看", response = HomePageCoursePageVo.class)
    public Response homePageList(
            @ApiParam(name = "name", value = "课程名称", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认10条", required = true) @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        ApiSeachCourseVo apiSeachCourseVo = new ApiSeachCourseVo();
        apiSeachCourseVo.setName(name);
        apiSeachCourseVo.setPageSize(pageSize);
        apiSeachCourseVo.setPageNo(pageNo);
        RequestContext requestContext = ContextHolder.get();
        apiSeachCourseVo.setIds(requestContext.getRelationIds());
        apiSeachCourseVo.setCompanyId(requestContext.getCompanyId());
        apiSeachCourseVo.setSiteId(requestContext.getSiteId());
        //List<HomePageCourseVo> list = courseClient.getHomePageCourseList(apiSeachCourseVo);
        Page<HomePageCourseVo> pageData = courseClient.getHomePageCourseList(apiSeachCourseVo);

        // 微信端不展示课程时长
        /*List<HomePageCourseVo> countData = pageData.getRecords();
        if(!CollectionUtils.isEmpty(countData)){
            List<Long> courseIds = countData.stream().parallel().flatMap(arObj->arObj.getApiListCourseVos().
                    stream()).map(subObj->subObj.getId()).collect(Collectors.toList());
            Map<Long, Long> courseDuration = coursePcClient.getMaterialTimeByCourseIds(courseIds);
            for(HomePageCourseVo obj : countData){
                List<ApiListCourseVo> subList = obj.getApiListCourseVos();
                for(ApiListCourseVo subObjLookp : subList){
                    Long currCourseId = subObjLookp.getId();
                    Long durationTem = courseDuration.get(currCourseId);
                    subObjLookp.setDuration(durationTem==null?0:Integer.valueOf(durationTem.toString()));
                }
            }
        }*/
        // 或许改成返回分页信息
        //Pair<List<HomePageCourseVo>,Map<String,Integer>> retData = PageTools.split(pageData);
        return Response.ok(PageTools.split(pageData));
    }

    @GetMapping("/material/get")
    @ApiOperation(value = "素材库信息查询", notes = "返回素材库信息", response = MaterialVo.class)
    public Response<MaterialVo> getMaterialVo(
            @ApiParam(name = "id", value = "主键id", required = true) @RequestParam(name = "id") Long id
    ) {
        MaterialVo materialVo = materialClient.get(id);
        Boolean vailExplanation = null != materialVo && null != materialVo.getExplanation();
        if (vailExplanation) {
            materialVo.setExplanation(HtmlTagUtil.deleteAllHTMLTag(materialVo.getExplanation()));
        }

        return Response.ok(materialVo);
    }

    @GetMapping("/hot/list")
    @ApiOperation(value = "火热课程", notes = "火热课程", response = HomePageCoursePageVo.class)
    public Response hotList(
            @ApiParam(name = "name", value = "课程名称", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认10条", required = true) @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {
        ApiSeachCourseVo apiSeachCourseVo = new ApiSeachCourseVo();
        apiSeachCourseVo.setPageSize(pageSize);
        apiSeachCourseVo.setPageNo(pageNo);
        apiSeachCourseVo.setName(name);
        RequestContext requestContext = ContextHolder.get();
        apiSeachCourseVo.setIds(requestContext.getRelationIds());
        apiSeachCourseVo.setCompanyId(requestContext.getCompanyId());
        apiSeachCourseVo.setSiteId(requestContext.getSiteId());
        List<HomePageCoursePageVo> list = courseClient.hotList(apiSeachCourseVo);
        return Response.ok(list);
    }

    @ApiOperation(value = "课程心跳配置", notes = "课程心跳配置", response = HeartBeatVo.class)
    @GetMapping("/heartbeat")
    public Response get() {
        HeartBeatVo heartBeatVo = new HeartBeatVo();
        /*if ("dev".equals(active)) {
            heartBeatVo.setNginxAddress("http://192.168.0.162");
        } else if ("sit".equals(active)) {
            heartBeatVo.setNginxAddress("https://test.wechat.kmelearning.com/heart_check");
        } else if ("uat".equals(active)) {
            heartBeatVo.setNginxAddress("https://uat.wechat.kmelearning.com/heart_check");
        } else {
            heartBeatVo.setNginxAddress("https://kmelearning.com/heart_check");
        }*/
        heartBeatVo.setNginxAddress("/heart_check");
        return Response.ok(heartBeatVo);
    }

    @ApiOperation(value = "保存scorm进度", notes = "保存scorm进度")
    @PostMapping("/scorm/save")
    public Response saveScorm(@ApiParam("传 id、data、scormId、chapterId") @RequestBody ScormRecordVO record) {
        ScormRecordVO scormRecord = courseClient.saveScorm(record);
        if (scormRecord != null) {
            return Response.ok();
        }
        return Response.fail();
    }

    @ApiOperation(value = "获取scorm进度")
    @GetMapping("/scorm/get")
    public Response getScorm(
            @ApiParam("scormId") @RequestParam("scormId") Long scormId,
            @ApiParam("chapterId") @RequestParam("chapterId") Long chapterId) {
        ScormRecordVO record = courseClient.getScorm(scormId, chapterId);
        if(record == null){
            record = new ScormRecordVO();
        }
        record.setStartStudyTime(new Date());
        return Response.ok(record);
    }

    @ApiOperation(value = "获取离线下载列表", notes = "获取离线下载列表")
    @GetMapping("/offline/list")
    public Response<List<ApiListCourseVo>> getOfflineList(
            @ApiParam(name = "ids", value = "用，分割", required = true) @RequestParam(name = "ids") String ids,
            @ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = true) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数,默认10条", required = true) @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        List<ApiListCourseVo> apiListCourseVos = courseClient.getOfflineList(ids, pageNo, pageSize);
        return Response.ok(apiListCourseVos);
    }

}
