package com.yizhi.application.project.controller.util;


import com.yizhi.assignment.application.feign.AssignmentStudentClient;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.feign.CoursePcClient;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.exam.application.feign.ExamManageClient;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveActivityResultVO;
import com.yizhi.live.application.vo.LiveActivityVO;
import com.yizhi.research.application.feign.ResearchClient;
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.training.application.vo.api.TrainingProjectContentActivityVo;
import com.yizhi.training.application.vo.api.TrainingProjectContentPlanVo;
import com.yizhi.training.application.vo.api.TrainingProjectIntroductionVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ProjectWorkUtil {

    @Autowired
    LiveActivityClient liveActivityClient;
    @Autowired
    private ResearchClient researchClient;
    @Autowired
    private CourseClient courseClient;
    @Autowired
    private ExamManageClient examManageClient;
    @Autowired
    private AssignmentStudentClient assignmentStudentClient;

    @Autowired
    private FunctionDisplayConfigApiClients configApiClients;
    @Autowired
    private CoursePcClient coursePcClient;

    private final Integer COURSE = 0;

    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectWorkUtil.class);


    /**
     * 活动为直播时，组装其直播频道
     *
     * @param dataList
     * @return
     */
    public Map buildMap(List<TrainingProjectContentPlanVo> dataList, TrainingProjectIntroductionVo introductionVo, Boolean enabled) {
        if (!CollectionUtils.isEmpty(dataList)) {
            List<Long> courseIds = new ArrayList<>(dataList.size());
            List<Long> examIds = new ArrayList<>(dataList.size());
            List<Long> researchIds = new ArrayList<>(dataList.size());
            List<Long> assignmentIds = new ArrayList<>(dataList.size());


            for (TrainingProjectContentPlanVo voData : dataList) {
                List<TrainingProjectContentActivityVo> activities = voData.getActivities();
                if (!CollectionUtils.isEmpty(activities)) {
                    for (TrainingProjectContentActivityVo activityVo : activities) {
                        Integer activityType = activityVo.getType().intValue();
                        Long bizId = activityVo.getRelationId();
                        //获取需要计算积分的bizId
                        switch (activityType) {
                            case 0://课程
                                courseIds.add(bizId);
                                break;
                            case 1://考试
                                examIds.add(bizId);
                                break;
                            case 2://调研
                                researchIds.add(bizId);
                                break;
                            case 3://直播
                                LiveActivityResultVO liveVo = liveActivityClient.get(activityVo.getRelationId());
                                if (liveVo != null) {
                                    LiveActivityVO liveActivity = liveVo.getLiveActivity();
                                    if (liveActivity != null) {
                                        String channel = liveActivity.getChannel();
                                        activityVo.setUrl(channel);
                                    }
                                }
                                break;
                            case 5://作业
                                assignmentIds.add(bizId);
                                break;
                        }
                    }
                }
            }
            Map map = new HashMap<>(3);


            //目前没有用到
//            if (enabled) {
//                Integer totalPointMin = 0;
//                Integer totalPointMax = 0;
//                if (!CollectionUtils.isEmpty(researchIds)) {
//                    Integer researchPoint = researchClient.getPointByIds(researchIds);
//                    researchPoint = returnNumber(researchPoint);
//                    LOGGER.info("调研积分：" + researchPoint.toString());
//                    totalPointMin = getTotalPoint(researchPoint, totalPointMin);
//                    totalPointMax = getTotalPoint(researchPoint, totalPointMax);
//                }
//                if (!CollectionUtils.isEmpty(courseIds)) {
//                    Map<Long, Integer> coursePointMap = courseClient.getCourseScoreByIds(courseIds);
//                    if (coursePointMap != null) {
//                        LOGGER.info("课程积分：" + coursePointMap.toString());
//                        Collection<Integer> values = coursePointMap.values();
//                        for (Integer point : values) {
//                            totalPointMin = getTotalPoint(returnNumber(point), totalPointMin);
//                            totalPointMax = getTotalPoint(returnNumber(point), totalPointMax);
//                        }
//                    }
//                }
//                if (!CollectionUtils.isEmpty(examIds)) {
//                    Map<String, Integer> examPointMap = examManageClient.getMinAndMaxPointSum(examIds);
//                    if (examPointMap != null) {
//                        LOGGER.info("考试积分：" + examPointMap.toString());
//                        examPointMap = getPointMap(examPointMap, totalPointMin, totalPointMax);
//                        totalPointMax = examPointMap.get("maxPoint");
//                        totalPointMin = examPointMap.get("minPoint");
//                    }
//                }
//                if (!CollectionUtils.isEmpty(assignmentIds)) {
//                    Map<String, Integer> assignmentPointMap = assignmentStudentClient.getTrainingPoint(assignmentIds);
//                    if (assignmentPointMap != null) {
//                        LOGGER.info("作业积分：" + assignmentPointMap.toString());
//                        assignmentPointMap = getPointMap(assignmentPointMap, totalPointMin, totalPointMax);
//                        totalPointMax = assignmentPointMap.get("maxPoint");
//                        totalPointMin = assignmentPointMap.get("minPoint");
//                    }
//
//                }
//                Integer projectPoint = returnNumber(introductionVo.getPoint());
//                totalPointMin = getTotalPoint(projectPoint, totalPointMin);
//                totalPointMax = getTotalPoint(projectPoint, totalPointMax);
//                LOGGER.info("培训积分：" + projectPoint.toString());
//
//                map.put("minPoint", totalPointMin);
//                map.put("maxPoint", totalPointMax);
//            }

            //这里给项目添加 学时是否显示

            Map durationMap = getDurationMap(courseIds);
            if (durationMap != null) {
                //是否显示项目学时
                introductionVo.setTrainingDurationShow((Boolean) durationMap.get("trainingDurationShow"));
                introductionVo.setPeriod((Float) durationMap.get("trainingDuration"));
            }

            //给活动增加是否发放证书标识
            if (!CollectionUtils.isEmpty(courseIds)) {
                List<CourseEntityVo> courses = null;
                try {
                    courses = courseClient.getCourseByIds(courseIds);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (!CollectionUtils.isEmpty(courses)) {
                    Map<Long, Boolean> hasCertificateMap = new HashMap<>(courses.size());
                    courses.forEach(a -> {
                        if (!hasCertificateMap.containsKey(a.getId())) {
                            hasCertificateMap.put(a.getId(), a.getGrantCertificate());
                        }
                    });
                    for (TrainingProjectContentPlanVo voData : dataList) {
                        List<TrainingProjectContentActivityVo> activities = voData.getActivities();
                        if (!CollectionUtils.isEmpty(activities)) {
                            for (TrainingProjectContentActivityVo activityVo : activities) {
                                Integer activityType = activityVo.getType().intValue();
                                Long bizId = activityVo.getRelationId();
                                if (activityType.equals(COURSE)) {
                                    if (hasCertificateMap != null) {
                                        activityVo.setHasCertificate(hasCertificateMap.get(bizId));
                                    }
                                }

                            }
                        }
                    }
                }
            }

            map.put("dataList", dataList);
            return map;
        }
        return null;
    }

    public Map getDurationMap(List<Long> courseIds) {
        Map map = new HashMap<>(2);

        //这里给项目添加 学时是否显示

        List<FunctionDisplayConfigVo> dataFunction = configApiClients.getAllBySiteId();
        Boolean trainingDurationShow = false;
        if (!CollectionUtils.isEmpty(dataFunction)) {
            for (FunctionDisplayConfigVo a : dataFunction) {
                if (FunctionTypeCode.TRAINING.getCode().equals(a.getFunctionType())) {
                    trainingDurationShow = a.getShowDisplay();
                }
            }
        }
        map.put("trainingDurationShow", trainingDurationShow);

        Float allMaterialTime = 0.0f;
        if (!CollectionUtils.isEmpty(courseIds)) {
            Map<Long, Float> courseMap = coursePcClient.getStudyHourByCourseIds(courseIds);
            if (null != courseMap) {
                LOGGER.info("查询到的cousreMap为:" + courseMap.toString());
                for (Long courseId : courseIds) {
                    Float materialTime = courseMap.get(courseId);
                    LOGGER.info("查询到的materialTime为:" + materialTime);
                    materialTime = (materialTime == null ? 0.0f : materialTime);
                    allMaterialTime = materialTime + allMaterialTime;
                }
            }
        }
        map.put("trainingDuration", allMaterialTime);
        return map;
    }

    /**
     * |
     * 目的是null值默认为0
     *
     * @param object
     * @return
     */
    public Integer returnNumber(Object object) {
        object = (object == null ? 0 : object);
        return Integer.valueOf(object.toString());
    }

    /**
     * 返回积分之和
     *
     * @param newPoint
     * @param resultPoint
     * @return
     */
    private Integer getTotalPoint(Integer newPoint, Integer resultPoint) {

        return (newPoint + resultPoint);
    }

    /**
     * 组装最小积分   最大积分
     *
     * @param pointMap
     * @param totalPointMin
     * @param totalPointMax
     * @return
     */
    private Map<String, Integer> getPointMap(Map<String, Integer> pointMap, Integer totalPointMin, Integer totalPointMax) {
        if (pointMap != null) {
            Integer maxPoint = returnNumber(pointMap.get("maxPoint"));
            Integer minPoint = returnNumber(pointMap.get("minPoint"));
            if (maxPoint >= minPoint) {
                totalPointMin = getTotalPoint(minPoint, totalPointMin);
                totalPointMax = getTotalPoint(maxPoint, totalPointMax);
            } else {
                totalPointMin = getTotalPoint(maxPoint, totalPointMin);
                totalPointMax = getTotalPoint(minPoint, totalPointMax);
            }
            Map<String, Integer> map = new HashMap<>(2);
            map.put("minPoint", totalPointMin);
            map.put("maxPoint", totalPointMax);
            return map;
        }
        return null;
    }
}
