package com.yizhi.application.lecturer;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.lecturer.vo.LecturerParamVo;
import com.yizhi.application.tools.PageTools;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.OfflineCourseClient;
import com.yizhi.course.application.vo.LecturerCourseVO;
import com.yizhi.course.application.vo.LecturerCourseValidReqVO;
import com.yizhi.course.application.vo.OfflineCourseVo;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.lecturer.application.enums.DeleteFlag;
import com.yizhi.lecturer.application.feign.LecturerClient;
import com.yizhi.lecturer.application.vo.LecturerApiVo;
import com.yizhi.lecturer.application.vo.LecturerApiVoParam;
import com.yizhi.lecturer.application.vo.LecturerListVO;
import com.yizhi.lecturer.application.vo.RelationVOList;
import com.yizhi.site.application.enums.PortalEnum;
import com.yizhi.system.application.system.remote.AccountClient;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;


/**
 * <p>讲师库学员端</p>
 * @author lilingye
 * @date 2019-5-17
 * @since 1.0.0
 */
@Api(tags = "学员端-讲师库")
@RestController
@RequestMapping("/api/lecturer")
public class LecturerController {

    private static final Logger LOG = LoggerFactory.getLogger(LecturerController.class);

    @Autowired
    private LecturerClient lecturerClient;

    @Autowired
    AccountClient accountClient;

    @Autowired
    CourseClient courseClient;

    @Autowired
    TrainingProjectClient trainingProjectClient;

    @Autowired
    OfflineCourseClient offlineCourseClient;


    @ApiOperation(value = "讲师详情", notes = "讲师详情",response = LecturerListVO.class)
    @GetMapping(value = "/get")
    public Response<String> getLecturerDetail(@ApiParam(name = "id",value = "讲师id") @RequestParam(name = "id") Long id){

        return Response.ok(lecturerClient.queryLecturerByLecturerId(id));

    }


    @ApiOperation(value = "讲师关联课程或培训列表", response = RelationVOList.class)
    @GetMapping(value = "/relation/list")
    public Response queryLecturerRelationList(@RequestParam(name = "lecturerId",required = false) Long lecturerId,
                                 @RequestParam(name = "pageNo",defaultValue = "1") Integer pageNo,
                                 @RequestParam(name = "pageSize",defaultValue = "20") Integer pageSize){
        Page<RelationVOList> relationVOPage = null;
        Map<Integer, List<RelationVOList>> relationListMap = null;
        try {
            relationVOPage = lecturerClient.getRelationListByLecturerId(lecturerId, pageNo, pageSize);
            relationListMap = relationVOPage.getRecords().stream().collect(Collectors.groupingBy(RelationVOList::getType));
        } catch (Exception e) {
           LOG.info("返回异常：",e);
        }

        // 声明暂存返回的列表
        List<RelationVOList> relationVOList = new ArrayList<>();
        LOG.info("返回的列表lecturerRecords："+relationVOPage.getRecords());
        LOG.info("返回的列表relationListMap："+relationListMap);

        // 课程
        relationVOList = getCourseLecturerRelation(relationListMap, relationVOList, PortalEnum.ONE.toValue());
        LOG.info("relationVOList1:"+relationVOList);
        // 线下课程
        relationVOList = getCourseLecturerRelation(relationListMap,relationVOList,PortalEnum.TWO.toValue());
        LOG.info("relationVOList2:"+relationVOList);
        // 培训
        relationVOList = getTrainingRelationList(relationListMap,relationVOList,PortalEnum.THREE.toValue());
        LOG.info("relationVOList3:"+relationVOList);

        List<RelationVOList> lecturerRelationVOList = new ArrayList<>();

        for (RelationVOList r:relationVOPage.getRecords()){
            int temp=0;
            for (RelationVOList rv:relationVOList) {
                if (r.getRelationId().equals(rv.getRelationId())){
                    lecturerRelationVOList.add(rv);
                    temp =1;
                    break;
                }
            }
            LOG.info("当前a："+temp);
            if (temp!=1){
                RelationVOList relationVO = getRelation(r);
                lecturerRelationVOList.add(relationVO);
            }
        }
        relationVOPage.setRecords(lecturerRelationVOList);

        return Response.ok(PageTools.versaPage(relationVOPage));
    }

    /**
     * 获取关联关系
     * @param r
     * @return
     */
    private RelationVOList getRelation(RelationVOList r){

        r.setFlag(DeleteFlag.NO.ordinal());
        switch (r.getType()){
            case 1:
                try {
                    CourseEntityVo course = courseClient.view(r.getRelationId());
                    if (course!=null) {
                        r.setRelationName(course.getName());
                        r.setImage(course.getImage());
                    }
                } catch (Exception e) {
                    LOG.info("在线课程",e);
                }
                break;
            case 2:
                try {
                    OfflineCourseVo offlineCourse = offlineCourseClient.getCourseById(r.getRelationId());
                    if (offlineCourse!=null) {
                        r.setRelationName(offlineCourse.getName());
                        r.setImage(offlineCourse.getImage());
                        r.setDes(offlineCourse.getDescription());
                    }
                } catch (Exception e) {
                    LOG.info("线下课程",e);
                }
                break;
            case 3:
                try {
                    TrainingProjectVo project = trainingProjectClient.getOne(r.getRelationId());
                    if (project!=null) {
                        r.setRelationName(project.getName());
                        r.setImage(project.getLogoImg());
                        LOG.info("开始时间："+project.getStartTime()+";"+project.getEndTime());
                        r.setStartTime(project.getStartTime());
                        r.setEndTime(project.getEndTime());
                    }
                } catch (Exception e) {
                    LOG.info("培训",e);
                }
                break;
                default:
        }
        return r;
    }

    /**
     * 获取课程的关联
     * @param relationListMap
     * @param relationVOList
     * @param type
     * @return
     */
    private List<RelationVOList> getCourseLecturerRelation(Map<Integer, List<RelationVOList>> relationListMap,List<RelationVOList> relationVOList,Integer type){
        LOG.info("参数：relationListMap："+relationListMap);
        LOG.info("参数：type："+type);
        LOG.info("参数：relationVOList："+relationVOList);
        LOG.info("参数：relationListMap.get(type)："+relationListMap.get(type));
        if (CollectionUtils.isNotEmpty(relationListMap.get(type))){


        List<Long> courseIds = relationListMap.get(type).parallelStream().map(lr->{
            return lr.getRelationId();
        }).collect(toList());
        LOG.info("在线课courseIds："+courseIds);
        LecturerCourseValidReqVO lecturerCourseValidReqVO = new LecturerCourseValidReqVO();
        lecturerCourseValidReqVO.setCourseIds(courseIds);
        lecturerCourseValidReqVO.setCourseType(type);
        // 有权限的课程
        try {
            List<LecturerCourseVO> courseVOS = courseClient.filterValidCourse(lecturerCourseValidReqVO);
            LOG.info("返回："+courseVOS);
            if (CollectionUtils.isNotEmpty(courseVOS)){
                LOG.info("有权限的在线课程："+courseVOS.size());
                relationVOList.addAll(
                        courseVOS.parallelStream().map(courseVO->{
                            RelationVOList rv = new RelationVOList();
                            rv.setRelationId(courseVO.getCourseId());
                            rv.setRelationName(courseVO.getCourseName());
                            rv.setFlag(DeleteFlag.YES.ordinal());
                            rv.setType(type);
                            rv.setDes(courseVO.getDes());
                            rv.setImage(courseVO.getImage());
                            return rv;
                        }).collect(toList())
                );
            }
        } catch (Exception e) {
            LOG.info("课程异常",e);
        }
        LOG.info("relationVOLists:"+relationVOList.size());
        }
        return relationVOList;
    }

    /**
     * 获取培训的关联
     * @param relationListMap
     * @param type
     * @return
     */
    private List<RelationVOList>  getTrainingRelationList(Map<Integer, List<RelationVOList>> relationListMap,List<RelationVOList> relationVOList,Integer type){
        try {
            if (CollectionUtils.isNotEmpty(relationListMap.get(type))) {

                List<Long> trainingIds = relationListMap.get(type).parallelStream().map(lr->{
                    return lr.getRelationId();
                }).collect(toList());
                LOG.info("返回trainingIds："+trainingIds.size());
                List<TrainingProjectVo> trainingProjects  = trainingProjectClient.getByIds(trainingIds);
                LOG.info("有权限的培训："+trainingProjects);
                if (CollectionUtils.isNotEmpty(trainingProjects)){
                    LOG.info("有权限的培训："+trainingProjects.size());
                    relationVOList.addAll(
                            trainingProjects.parallelStream().map(t->{
                                RelationVOList rv = new RelationVOList();
                                rv.setRelationId(t.getId());
                                rv.setRelationName(t.getName());
                                rv.setFlag(DeleteFlag.YES.ordinal());
                                rv.setType(PortalEnum.THREE.ordinal());
                                rv.setStartTime(t.getStartTime());
                                rv.setEndTime(t.getEndTime());
                                rv.setImage(t.getLogoImg());
                                return rv;
                            }).collect(toList())
                    );
                }
            }
        } catch (Exception e) {
           LOG.info("培训异常",e);
        }
        LOG.info("relationVOLists:"+relationVOList.size());
        return relationVOList;
    }

    /**
     * 交银康联接口
     * @param classifyId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/find")
    public Response findLecturerList(
            @ApiParam(name = "classifyId", value = "分类id") @RequestParam(value = "classifyId", required = false) String classifyId,
            @ApiParam(name = "pageNo", value = "要跳转的页数") @RequestParam(value = "pageNo", defaultValue = "1", required = false) Integer pageNo,
            @ApiParam(name = "pageSize", value = "每页条数，默认：10") @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize
    ){
        LecturerApiVoParam lecturerApiVoParam = new LecturerApiVoParam();
        lecturerApiVoParam.setPageNo(pageNo);
        lecturerApiVoParam.setPageSize(pageSize);
        List<String> ids = null;
        if (StringUtils.isNotBlank(classifyId)) {
             ids = Arrays.asList(classifyId.split(","));
             lecturerApiVoParam.setIds(ids);
        }

        LOG.info("参数：{}", JSON.toJSON(lecturerApiVoParam));
        Page<LecturerApiVo> lecturerApiVoPage = lecturerClient.findLecturer(lecturerApiVoParam);
        List<LecturerApiVo> records = lecturerApiVoPage.getRecords();
        LecturerParamVo lecturerParamVo = new LecturerParamVo();
        lecturerParamVo.setContent(records);
        lecturerParamVo.setTotalElements(lecturerApiVoPage.getTotal());
        LOG.info("最总返回：{}",JSON.toJSON(lecturerParamVo));
        return Response.ok(lecturerParamVo);
    }
}
