package com.ruoyi.web.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.UserRegStatus;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.dezhi.service.IBBusiDezhiVideoService;
import com.ruoyi.mingxue.domain.CustomerVideoWatches;
import com.ruoyi.mingxue.service.ICustomerVideoWatchesService;
import com.ruoyi.mxjb.domain.MxjbContants;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.syzy.domain.BBusiSyghVideo;
import com.ruoyi.syzy.domain.BWwwNewsVideo;
import com.ruoyi.syzy.service.IBBusiSyghVideoService;
import com.ruoyi.syzy.service.IBWwwNewsVideoService;
import com.ruoyi.util.PageUtil;
import com.ruoyi.web.service.CommService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

@Api(tags = "学习-视频课程")
@RestController
@RequestMapping("front/videoCourse/")
public class FrontVideoCourseController extends BaseController {
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IBWwwNewsVideoService newsVideoService;
    @Autowired
    private IBBusiDezhiVideoService videoService;
    @Autowired
    private ICustomerVideoWatchesService customerVideoWatchesService;
    @Autowired
    private IBBusiSyghVideoService busiSyghVideoService;
    @Autowired
    private CommService commService;
    @ApiOperation("01 视频大类")
    @GetMapping("subjects")
    public TableDataInfo subjects(@ApiParam("ie") @RequestParam(required = false) Integer type) {
        if (null != type && type.equals(1)) {
            JSONArray arr = new JSONArray();
            busiSyghVideoService.subjectNames().stream().forEach(t -> {
                JSONObject d = new JSONObject();
                d.put("code", t.getSubjectId());
                d.put("label", t.getSubjectName());
                arr.add(d);
            });
            return getDataTable(arr);
        }
        String json = configService.selectConfigByKey("video_subjects");
        JSONArray arr = JSON.parseArray(json);
        return getDataTable(arr);
    }

    @ApiOperation("01 大类知识点")
    @GetMapping("knowledges")
    public TableDataInfo knowledges(@ApiParam("大类") @RequestParam Integer subject) {
        JSONArray arr = new JSONArray();
        busiSyghVideoService.knowledgeNames(subject).stream().forEach(t -> {
            JSONObject d = new JSONObject();
            d.put("code", t.getKnowledgeId());
            d.put("label", t.getKnowledgeName());
            arr.add(d);
        });
        return getDataTable(arr);
    }

    @ApiOperation("06 视频列表")
    @GetMapping("video/list")
    public TableDataInfo videoList(@ApiParam("大类 ") @RequestParam Integer subject, @ApiParam("知识点") @RequestParam(required = false) Integer knowledge,
        @ApiParam("科目") @RequestParam(required = false) String course,
        @ApiParam("年级") @RequestParam(required = false) String grade, @ApiParam("版本") @RequestParam(required = false) String version,
        @ApiParam("视频包Id") @RequestParam(required = false) String pack, @ApiParam("标题") @RequestParam(required = false) String sectionName,
        @ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
        @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) {
        commService.requireVip();

        startPage();
        if(StringUtils.isBlank(pack)) {
            BBusiSyghVideo syghVideoCond = new BBusiSyghVideo();
            syghVideoCond.setSubjectId(subject);
            syghVideoCond.setKnowledgeId(knowledge);
            List<BBusiSyghVideo> videoList = busiSyghVideoService.selectBBusiSyghVideoList(syghVideoCond);
            List<JSONObject> arr = Lists.newArrayList();
            for (BBusiSyghVideo v : videoList) {
                JSONObject item = new JSONObject(true);
                item.put("aliId", v.getAliid());
                item.put("name", v.getName());
                item.put("img", v.getPictUrl());
                item.put("aliIdType", MxjbContants.Ali_Id_sygh);
                arr.add(item);
            }
            return getDataTable(PageUtil.getDtoListWithPageable(videoList, arr));
        }
        Map<String, Object> params = new HashMap<>(6);
        if (StringUtils.isNotBlank(pack)) {
            params.put("packId", pack);
        } else {
            params.put("course", course);
            params.put("grade", grade);
            params.put("version", version);
        }
        params.put("sectionName", sectionName);
        List<JSONObject> arr = videoService.selectVideoList(params);

        //是否收藏 TODO MF
        return getDataTable(arr);
    }


    /**
     * 没登陆时，取4条固定的（从配置)
     * 有登陆时，根据初中还是高中，随便取4条
     * @return
     * @throws Exception
     */
    @ApiOperation("08.1 首页视频列表（未登陆时）")
    @GetMapping("listForHomepageNoLogin")
    public TableDataInfo listForHomepageNoLogin() throws Exception {
        String configValue = configService.selectConfigByKey("video_for_homepage");
        if (StringUtils.isBlank(configValue)) {
            return new TableDataInfo();
        }
        JSONArray jsonArray = JSONArray.parseArray(configValue);
        return getDataTable(jsonArray);
    }

    @ApiOperation("08.2 首页视频列表（已登陆时）")
    @GetMapping("listForHomepageLogined")
    public TableDataInfo listForHomepageLogined(@ApiParam(value = "页数", example = "1") @RequestParam Integer pageNum,
            @ApiParam(value = "页大小", example = "15") @RequestParam Integer pageSize) throws Exception {
        if (!UserRegStatus.Student.equals(SecurityUtils.getLoginUser().getUser().getRegStatus())) {
            throw new CustomException("未授权", 401);
        }
        List<JSONObject> result= new ArrayList<>();

        Map<String, Object> params = new HashMap<>();
        //{"total":9,"rows":[{"code":1001,"label":"语文"},{"code":1002,"label":"数学"},{"code":1003,"label":"英语"},{"code":1004,"label":"物理"},{"code":1005,"label":"化学"},{"code":1006,"label":"生物"},{"code":1007,"label":"历史"},{"code":1008,"label":"地理"},{"code":1009,"label":"政治"}],"code":200,"msg":"查询成功"}
        //仅需显示语文、数学、物理、化学四条即可
        List<Integer> courses=Arrays.asList(1001,1002,1004,1005);
        for(int i= 0;i<courses.size();i++){
            params.put("course",courses.get(i));
            List<JSONObject> arr = videoService.selectVideoList2(params);
            if(!CollectionUtils.isEmpty(arr)){
                result.add(arr.get(new Random().nextInt(courses.size())));
            }
        }

        return getDataTable(result);
    }

    @ApiOperation("保存视频观看记录")
    @PostMapping("saveWatchRecord")
    public AjaxResult saveWatchRecord(@ApiParam("type 1 dezhi 2 sygh 3 mxapp 4 question 5 resource") @RequestParam(required = false) Integer type,
                                      @ApiParam("sectionAliId") @RequestParam("sectionId") String sectionAliId, Long duration, Double percent) {
        if(null == type) {
            //TODO 暂不处理，后面6天解决
//            return AjaxResult.error("aliIdType不能为空");
        }
        String customerCode = SecurityUtils.getLoginUser().getUser().getCode();
        CustomerVideoWatches watches = customerVideoWatchesService.selectTodayBySection(customerCode, type, sectionAliId);
        if (watches != null) {
            if (watches.getPercent().compareTo( new BigDecimal(String.valueOf(percent)))==-1) {
                watches.setDuration(duration);
                watches.setPercent(new BigDecimal(percent));
                watches.setTime(new Date());
                watches.setType(type);
                customerVideoWatchesService.updateCustomerVideoWatches(watches);
            }
        } else {
            watches = new CustomerVideoWatches();
            watches.setType(type);
            watches.setCustomerCode(customerCode);
            watches.setSectionId(sectionAliId);
            watches.setDuration(duration);
            watches.setPercent(new BigDecimal(percent));

            if (type.equals(MxjbContants.Ali_Id_voluntary_course)) { // 11
                BWwwNewsVideo video = newsVideoService.selectBWwwNewsVideoByAliId(sectionAliId);
                if (null != video) {
                    watches.setTitle(video.getTitle());
                }
            } else if (type.equals(MxjbContants.Ali_Id_sygh)) { // 2 sygh
                BBusiSyghVideo cond = new BBusiSyghVideo();
                cond.setAliid(sectionAliId);
                List<BBusiSyghVideo> list = busiSyghVideoService.selectBBusiSyghVideoList(cond);
                if (!CollectionUtils.isEmpty(list)) {
                    watches.setTitle(list.get(0).getName());
                }
            }
            customerVideoWatchesService.insertCustomerVideoWatches(watches);
        }
        return AjaxResult.success();
    }

    @ApiOperation("9 收藏视频")
    @PostMapping("video/collectVideoCourse")
    public AjaxResult collectVideoCourse(@ApiParam("视频ID") @RequestParam(required = true) Long id,@ApiParam("是否收藏 true收藏，false取消收藏") @RequestParam Boolean isCollect) {
        /*if(isCollect) {
            BBusiDezhiVideo video = videoService.selectBBusiDezhiVideoById(id);
            String aliId = video.getSectionAliid();
            LoginUser loginUser =SecurityUtils.getLoginUser();
            Long roleId = loginUser.getUser().getCurrentRoleId();
            if(RoleType.isHeadteacher(roleId)||RoleType.isTeacher(roleId)){
                //老师时才可收藏视频到个人资源库
                PersonResources personResources = new PersonResources();
                personResources.setAliIdType(MxjbContants.Ali_Id_resource_person);
                personResources.setSchoolId(loginUser.getSchoolId());
                personResources.setCreateId(loginUser.getUser().getUserId());
                personResources.setResourcesUrl(aliId);
                personResources.setVideoId(aliId);
                personResources.setResourcesName(video.getSectionName());
                personResources.setSourceId(String.valueOf(video.getId()));//微课视频的ID
                personResources.setType(1L);//资源类型 1 视频 2 图片 3 word 4 pdf
                personResources.setCategory("视频课程");
                //获取科目
                BBusiDezhiVideoPackage videoPackage = videoPackageService.selectBBusiDezhiVideoPackageByPackId(video.getPackId());
                if(null!=videoPackage){
                    //1001对应subjectId中的1
                    Long subjectId = Long.parseLong(videoPackage.getCourse())-1000;
                    personResources.setSubjectId(subjectId);
                }
                Date now = new Date();
                personResources.setCreateTime(now);
                personResources.setUpdateTime(now);
                personResourcesService.insertPersonResources(personResources);
            }else {
                return AjaxResult.error("仅有老师或班主任才能收藏视频");
            }
        }else {
            //取消收藏
            PersonResources personResources = new PersonResources();
            personResources.setCreateId(SecurityUtils.getLoginUser().getUser().getUserId());
            personResources.setSourceId(String.valueOf(id));
            List<PersonResources> personResourcesList = personResourcesService.selectPersonResourcesList(personResources);
            List<Long> personResourcesIds = personResourcesList.stream().map(PersonResources::getResourcesId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(personResourcesIds)){
                personResourcesService.deletePersonResourcesByIds(personResourcesIds.toArray(new Long[personResourcesIds.size()]));
            }
        }*/
        return AjaxResult.success();
    }

}
