package com.cirle.scientific.service.impl;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.cirle.scientific.constants.StatusConsts;
import com.cirle.scientific.controller.live.resp.LiveUserinfoResp;
import com.cirle.scientific.dao.*;
import com.cirle.scientific.po.*;
import com.cirle.scientific.server.WebSocketOneToMany;
import com.cirle.scientific.utils.*;
import com.cirle.scientific.utils.redis.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.cirle.scientific.dto.QkjLiveCommentsDTO;
import com.cirle.scientific.dto.QkjLiveDetailDTO;
import com.cirle.scientific.dto.QkjRecommendDTO;
import com.cirle.scientific.pojo.BizCodeEnum;
import com.cirle.scientific.pojo.Result;
import com.cirle.scientific.service.CommonService;
import com.cirle.scientific.service.LiveService;
import com.cirle.scientific.service.MemberService;
import com.cirle.scientific.service.OrderService;
import com.cirle.scientific.service.RecommendService;
import com.cirle.scientific.utils.page.PageBean;
import com.cirle.scientific.utils.page.Param;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Transactional
@Slf4j
public class LiveServiceImpl implements LiveService {

    public static Map<String, Long> totalmap = new HashMap();

    @Autowired
    private MemberService memberService;

    @Autowired
    private QkjLiveCommentsDao qkjLiveCommentsDao;

    @Autowired
    private QkjLiveDao qkjLiveDao;

    @Autowired
    private QkjLiveRemindDao qkjLiveRemindDao;

    @Autowired
    private RecommendService recommendService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private QkjLiveSeriesDao liveSeriesDao;

    @Autowired
    private QkjQuestionAnswerDao questionAnswerDao;

    @Autowired
    private QkjQuestionDetailDao questionDetailDao;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private WebSocketOneToMany webSocketOneToMany;

    @Autowired
    private CollectionDao collectionDao;

    @Autowired
    private QkjExaminationDetailDao qkjExaminationDetailDao;

    @Autowired
    private QkjAuditingDao qkjAuditingDao;


    @Override
    public List<QkjLiveDetailDTO> getLiveList(String memCard, Integer catalogsId, Integer page, Integer size) {
        List<QkjLive> list = qkjLiveDao.findList((page - 1) * size, size, new Integer[2]);
        List<QkjLiveDetailDTO> dtos = new ArrayList<QkjLiveDetailDTO>();
        for (QkjLive live : list) {
            dtos.add(makeLiveDetailDTO(live, memCard, false, false,
                    false, false, false, false));
        }
        return dtos;
    }

    @Override
    public Map<String, Object> pageLiveList(String memCard, Integer catalogsId, Integer page, Integer size, boolean isPC) {
        Integer[] mOrPc = new Integer[2];//电脑
        if (isPC) { //手机
            mOrPc[0] = 0;
            mOrPc[1] = 2;
        } else {
            mOrPc[0] = 1;
            mOrPc[1] = 2;
        }
        List<QkjLive> list = qkjLiveDao.findList((page - 1) * size, size, mOrPc);
        List<QkjLiveDetailDTO> dtos = new ArrayList<QkjLiveDetailDTO>();
        for (QkjLive live : list) {
            dtos.add(makeLiveDetailDTO(live, memCard, false, false,
                    false, false, false, false));
        }
        Map<String, Object> results = new HashMap<>();
        results.put("total", qkjLiveDao.selectAllCounts(mOrPc));
        results.put("results", dtos);
        return results;
    }

    @Override
    public Result getLiveDetail(Long liveId, String memCard) {
        QkjLive live = qkjLiveDao.findById(liveId).get();
        QkjLiveDetailDTO liveDetailDTO = (QkjLiveDetailDTO) redisUtil.get("LiveInfo" + liveId);
        liveDetailDTO = null;
        if (liveDetailDTO == null) {
            liveDetailDTO = makeLiveDetail(live, memCard, true, true,
                    true, true, true, true);
            redisUtil.set("LiveInfo" + liveId, liveDetailDTO);
        }
        return Result.success(liveDetailDTO);
    }

    @Override
    public Result getLiveComments(String memCard, Long liveId, Integer cId) {
        PageBean<QkjLiveComments> pagebean = new PageBean<QkjLiveComments>();

        LinkedHashMap<String, String> sortMap = new LinkedHashMap<String, String>();
        sortMap.put("id", "desc");

        PageRequest page = pagebean.buildPageRequest(1, 10, sortMap);

        Vector<Param> params = new Vector<Param>();
        params.add(new Param("liveId", liveId, "="));

        if (cId != null && cId != -1) {
            params.add(new Param("id", cId, "<"));
        }

        Specification<QkjLiveComments> spec = pagebean.buildSpecification(params, null);

        Page<QkjLiveComments> comments = qkjLiveCommentsDao.findAll(spec, page);

        List<QkjLiveCommentsDTO> mevosLiveCommentsDTOs = new LinkedList<QkjLiveCommentsDTO>();
        for (QkjLiveComments comment : comments.getContent()) {
            QkjLiveCommentsDTO dto = makeLivesConmmentDTO(memCard, comment);
            if (dto != null) {
                mevosLiveCommentsDTOs.add(dto);
            }
        }
        if (mevosLiveCommentsDTOs.size() > 0) {
            return Result.success(mevosLiveCommentsDTOs);
        } else {
            return Result.failed(BizCodeEnum.DATA_EMPTY);
        }
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public boolean addLiveComment(Long liveId, String memCard, String content) {
        QkjLiveComments comment = new QkjLiveComments();
        comment.setMemCard(memCard);
        comment.setLiveId(liveId);
        comment.setContent(content);
        comment.setOprTime(Calendar.getInstance());
        qkjLiveCommentsDao.save(comment);
        return true;
    }

    @Override
    public Result infoByMember(Long liveId, String memCard) {
        QkjLive live = qkjLiveDao.findById(liveId).get();
        Map<String, Object> map = new HashMap<String, Object>();
        if (memCard != null && !"mevosnullmemcard".equals(memCard) && judgeLiveReminded(liveId.toString(), memCard)) {
            map.put("isRemind", 1);
        } else {
            map.put("isRemind", 0);
        }
        if (memCard != null && !"mevosnullmemcard".equals(memCard) && judgeLivePurchased(liveId + "", memCard)) {
            map.put("isPurchased", 1);
        } else {
            map.put("isPurchased", 0);
        }

        //提醒人数
        map.put("remindMemberNum", live.getRemindMembers());//实际预约人数
        map.put("vremindMemberNum", live.getVremindMembers());//虚拟预约人数
        map.put("joinMembers", live.getJoinMembers());

        //学习人次
        map.put("liveManTime", live.getJoinMembers() + live.getPurchasedMembers());
        //是否填写问卷
        if (live.getQuestionFlag() == 1) {
            List<QkjQuestionAnswer> qa = questionAnswerDao.findByMemCardAndObjTypeAndObjId(memCard, 1, live.getId().intValue());
            if(CollectionUtils.isEmpty(qa)){
                //有可能是直播关联了试题，试题关联了问卷
                Integer exId = qkjExaminationDetailDao.findExIdByObjTypeAndObjId(1, live.getId().intValue());
                // 问卷问题
                qa = questionAnswerDao.findByMemCardAndObjTypeAndObjId(memCard, 3, exId);
            }
            if (qa.size() > 0) {
                map.put("isQuestionAnswer", 1);
            }
        }
        return Result.success(map);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Result<Map<String, Object>> reserveOrBets(String memCard, String liveId) {
        Map<String, Object> result = new HashMap<String, Object>();
        log.info("预约获取到的参数为：\nmemCard:" + memCard + "\nliveId:" + liveId);

        QkjLive live = qkjLiveDao.findByLiveId(liveId);
        if (live == null) {
            live = qkjLiveDao.findById(Long.parseLong(liveId)).get();
        }
        if (live == null) {
            log.info("直播不存在或者已经结束，无法预约");
            result.put("code", -1);
            result.put("errMsg", "直播不存在或者已经结束");
        }

        //预约
        QkjLiveRemind remind = qkjLiveRemindDao.findByLiveIdAndMemCard(liveId, memCard);
        if (remind != null) {
            result.put("code", -2);
            result.put("remindMemberNum", live.getRemindMembers());
            result.put("errMsg", "您已经预约");
        } else {
            QkjMember member = memberService.findByMemCard(memCard);
            if (member != null) {
                remind = new QkjLiveRemind();
                remind.setLiveId(liveId);
                remind.setMemCard(memCard);
                remind.setOprTime(Calendar.getInstance());
                remind.setRemindType(1);
                qkjLiveRemindDao.save(remind);
            }
            live.setRemindMembers(live.getRemindMembers() + 1);
            live.setVremindMembers(live.getVremindMembers() + 5);
            qkjLiveDao.save(live);

            result.put("code", 0);
            result.put("remindMemberNum", live.getRemindMembers());//实际预约人数
            result.put("vremindMemberNum", live.getVremindMembers());//虚拟预约人数
            result.put("errMsg", "预约成功");
        }
        return Result.success(result);
    }

    @Override
    public Result indexData(String memCard) {
        return indexData(memCard, null);
    }

    @Override
    public Result indexData(String memCard, Integer status) {
        JSONObject data = new JSONObject();
        //获取分类
//        List<QkjCatalogs> catalogsList = commonService.getCatalogsByFuId(1);
//        data.put("catalogsList",catalogsList);

        //获取顶部轮播图
        List<QkjRecommendDTO> recmdTop = recommendService.findByPosIdLimit(4L, status, 1, 10);
        data.put("recmdTop", recmdTop);

        return Result.success(data);
    }

    @Override
    public QkjLive getLiveInfo(Long liveId) {
        return qkjLiveDao.findById(liveId).get();
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public Result saveQuestionAnswer(String memCard, String questions, Integer liveId) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            List<QkjQuestionAnswer> list = mapper.readValue(questions, new TypeReference<List<QkjQuestionAnswer>>() {
            });
            if (list != null && list.size() > 0) {
                //questionAnswerDao.deleteByMemberAndObjTypeAndOjbId(memCard, list.get(0).getObjType(), list.get(0).getObjId());
                questionAnswerDao.deleteByMemberAndObjTypeAndOjbId(memCard, 1, liveId);
                for (QkjQuestionAnswer qa : list) {
                    qa.setMemCard(memCard);
                    qa.setObjId(liveId);
                    qa.setObjType(1);
                    questionAnswerDao.save(qa);
                }
                //同时增加审核表的数据
                qkjAuditingDao.deleteByMemberAndObjTypeAndOjbId(memCard, 1, liveId);
                QkjAuditing build = QkjAuditing.builder()
                        .memCard(memCard)
                        .auditingStatus(StatusConsts.auditingStatus_no_auditing)
                        .objType(1)
                        .objId(liveId)
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .build();
                QkjAuditing save = qkjAuditingDao.save(build);
                log.info("saveQuestionAnswer save:{}", save);
            }

            return Result.success("保存成功");
        } catch (Exception e) {
            e.getStackTrace();
            return Result.failed("数据解析错误");
        }
    }


    private final ConcurrentHashMap<String, Timer> liveStreams = new ConcurrentHashMap<>();

    @Override
    public void pushStreamCallback(HttpServletRequest request) {

        String action = request.getParameter("action");
        String id = request.getParameter("id");
        log.info("111111111阿里云推流回调参数 action=" + action);
        log.info("111111111阿里云推流回调参数 id=" + id);
        if ("publish".equals(action)) {
            if (liveStreams.containsKey(id)) { //如果定时器存在则取消
                Timer timer = liveStreams.get(id);
                timer.cancel();
                liveStreams.remove(id);
            }
//            log.info("推流开始，更改直播为开始状态");
//            String liveId = id.replace("QKJ-LIVE-", "");
//            QkjLive live = qkjLiveDao.findById(Long.parseLong(liveId)).get();
//            live.setLiveStatus(1);
//            qkjLiveDao.save(live);
//            //清楚缓存
//            redisUtil.del("LiveInfo" + liveId);
//            //websocket直播状态推送
//            webSocketOneToMany.sendStartOrStopLive(live.getId(), 1);

        } else if ("publish_done".equals(action)) {
            String liveId = id.replace("QKJ-LIVE-", "");
            QkjLive live = qkjLiveDao.findById(Long.parseLong(liveId)).get();
            if (liveStreams.containsKey(id)) { //如果定时器存在则取消
                Timer timer = liveStreams.get(id);
                timer.cancel();
                liveStreams.remove(id);
            }
            if (live.getLiveStatus() != 1 && live.getLiveType() != 3) { //只有在进行中才会继续/第三方直播不进行此操作
                return;
            }
            log.info("停止推流，30分钟后更改直播为已结束状态");
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                public void run() {
                    log.info("停止推流，更改直播为已结束状态");
                    live.setLiveStatus(2);
                    live.setLiveEndTime(Calendar.getInstance());
                    qkjLiveDao.save(live);
                    //清楚缓存
                    redisUtil.del("LiveInfo" + liveId);
                    //websocket直播状态推送
                    webSocketOneToMany.sendStartOrStopLive(live.getId(), 2);
                    liveStreams.remove(id);

                }
            }, 1000 * 60 * 30);
            liveStreams.put(id, timer);
        }
    }
    @Override
    public Result autoIncNum(String params) {
        try {

            int i1 = 0;
            while (true) {
                Long sleep = 30000L;
                JSONArray jsonArray = JSONArray.parseArray(params);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String timesString = jsonObject.getString("times");
                    String[] times = timesString.split("_");
                    String livesString = jsonObject.getString("lives");
                    String[] lives = livesString.split("_");
                    String aSwitch = jsonObject.getString("switch");
                    redisUtil.set("switch", aSwitch, 60 * 60 * 24);
                    //执行间隔参数
                    Long sleepJson = jsonObject.getLong("sleep");
                    if (Objects.nonNull(sleepJson) && !Objects.equals(0, sleep)) {
                        sleep = sleepJson;
                    }
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                    String now = format.format(new Date());
                    realincr(now, times, lives, sleep);
                }

                Thread.sleep(sleep);
                i1++;
                System.out.println("=====" + i1);

                log.info("i====={}", i1);
                Object aSwitch1 = redisUtil.get("switch");
                if (!"on".equals(aSwitch1)) {
                    log.info("跳出while");
                    break;
                }
            }
            log.info("结束了啊");
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    public Result getUserInfoByLiveId(String memCard, Integer liveId) {
        LiveUserinfoResp.LiveUserinfoRespBuilder builder = LiveUserinfoResp.builder();
        //查询直播
        QkjLive qkjLive = qkjLiveDao.findById(String.valueOf(liveId));
        if(Objects.nonNull(qkjLive)){
            builder.liveTitle(qkjLive.getLiveTitle());
            LocalDateTime time = LocalDateTimeUtil.getByCalendar(qkjLive.getLiveBeginTime());
            builder.liveBeginTime(LocalDateTimeUtil.getDateTimeAsString(time));
            builder.liveCoverImg(qkjLive.getLiveCoverImg());
        }
        QkjMember member = memberService.findByMemCard(memCard);
        if(Objects.nonNull(member)){
            builder.wxName(member.getMemNickname());
            builder.wxHeadImg(member.getMemHeadimg());
        }
        return Result.success(builder.build());
    }
    private void add(String now, String params, long sleep) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(params);

        String timesString = jsonObject.getString("times");
        String[] times = timesString.split("_");
        String livesString = jsonObject.getString("lives");
        String[] lives = livesString.split("_");
        realincr(now, times, lives, sleep);
    }

    public void realincr(String now, String[] times, String[] lives, long sleep) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        LocalDateTime nowLocal = LocalDateTime.now();
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String dataNow = nowLocal.toLocalDate().format(pattern);
        for (String live : lives) {
            String liveid = live.split(":")[0];//那个直播间
            Integer count = Integer.parseInt(live.split(":")[1]);//增加到多少人

            for (String time : times) {
                String start = time.split(",")[0].split("-")[0];
                String end = time.split(",")[0].split("-")[1];
                if (now.compareTo(start) < 0 || now.compareTo(end) >= 0) {
                    continue;//未开始或者已结束
                }
                //得到开始时间到结束时间之间 的间隔的秒数
                long last = (format.parse(dataNow + " " + end + ":00").getTime() - format.parse(dataNow + " " + start + ":00").getTime()) / 1000;

                //判断是否达到总人数上限达到停止程序
                String percent = time.split(",")[1];//时间段对应的百分比
                int currenttotal = count * Integer.parseInt(percent) / 100;//当前时间段需要增加多少人
                Long total = totalmap.get(liveid);
                redisUtil.set("realincr_total", total, 60 * 60 * 24);
                if(Objects.nonNull(total) && total == currenttotal){
                    continue;
                }

                long incr = currenttotal * sleep/1000 / last;//当前循环需要增加多少人数的固定部分
                long num = getnum(now, start, end, incr);//真实人数=固定人数+随机人数
                log.info("自动增加直播人数 liveId:{} num:{} incr:{} currenttotal:{} count:{}", liveid, num, incr, currenttotal, count);
                totalmap.merge(liveid, num, Long::sum);
                qkjLiveDao.updatePurchasedMembers(num, Long.parseLong(liveid));
            }
        }
    }

    private long getnum(String now, String start, String end, long incr) {

        if (now.compareTo(start) >= 0 && now.compareTo(end) < 0) {

        } else {
            int random2 = (int) ((Math.random() * 10));
            incr = random2;
        }
        int random = (int) ((Math.random() * 10 + 1) + incr);
        if (random < 0) {
            random = 0;
        }
        int MAX = 10000;
        if (random > MAX) {
            random = random % 10;
        }
        return random;

    }

    //判断直播是否已经购买
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    protected boolean judgeLivePurchased(String liveId, String memCard) {
        QkjLive live = qkjLiveDao.findById(Long.parseLong(liveId)).get();
        QkjPurchasedRecords records = orderService.findPurchasedRecords(memCard, 2, live.getId().intValue(), 1);
        Boolean isPurchased = false;
        if (records != null) {
            isPurchased = true;
        } else if (live.getLiveType() == 1) {
            List<QkjLiveSeries> liveSeries = liveSeriesDao.findByLiveId(live.getId().intValue());
            for (QkjLiveSeries series : liveSeries) {
                records = orderService.findPurchasedRecords(memCard, 2, series.getSeriesId().intValue(), 1);
                if (records != null) {
                    isPurchased = true;
                    break;
                }
            }
        }
        return isPurchased;
    }

    /**
     * 判断直播是否已经被提醒
     *
     * @param liveId
     * @param memCard
     * @return
     */
    private boolean judgeLiveReminded(String liveId, String memCard) {

        QkjLiveRemind mptq = qkjLiveRemindDao.findByLiveIdAndMemCard(liveId, memCard);
        if (mptq != null && !mptq.getMemCard().equals("")) {
            return true;
        }
        return false;
    }

    private String buildHcymLiveUrl(String memCard, QkjLive live) {
        if (live == null) {
            return "";
        }
        String livePlayUrl = live.getLivePlayUrl();

        QkjMember member = memberService.findByMemCard(memCard);
        String memberName = member.getMemNickname();

        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("DeviceId", "123456");
        headMap.put("Sign", "f21e3defc601761493f781ea98ae09ac");
        String liveKJsonStr = HttpClientUtil.sendGetSSL("https://api.njdyjy.com/video-key", headMap);
        Gson g = new Gson();
        JsonObject liveKJson = g.fromJson(liveKJsonStr, JsonObject.class);
        String liveK = liveKJson.get("k").getAsString();

        String liveUrl = livePlayUrl + "&name=" + memberName + "&k=" + liveK;


        return liveUrl;
    }

    public String buildShareUrl(String objType, Long objId, String memCard) {
//        String appDomain = getConstantByCode("APP_DOMAIN");
        String appDomain = "";
        String shareUrl = "";
        if ("1".equals(objType)) {
            shareUrl = appDomain + "/web/v2/tq/detailV3?objType=" + objType + "&tqcourseId=" + objId;
        } else if ("2".equals(objType)) {
            shareUrl = appDomain + "/web/v2/tq/detailV3?objType=" + objType + "&courseId=" + objId;
        } else if ("3".equals(objType)) {
            shareUrl = appDomain + "/web/v2/column/cDetail?columnId=" + objId;
        } else if ("4".equals(objType)) {
            shareUrl = appDomain + "/web/v2/column/artDetail?columnDetailId=" + objId;
        } else if ("5".equals(objType)) {
            shareUrl = appDomain + "/web/v3/live/lDetail?liveId=" + objId;
        }
        log.info("shareUrl=================================" + shareUrl);
        if (memCard == null || "".equals(memCard)) {
            return shareUrl;
        }
        // 客服人员信息
        QkjMember member = memberService.findByMemCard(memCard);
        if (member == null || "".equals(member)) {
            return shareUrl;
        }
        return shareUrl;
    }

    private String buildPlayUrlWithAuthKey(String liveDomain, String liveUri, int expminute) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, expminute);
        long timestamp = cal.getTimeInMillis() / 1000;
        String encryStr = liveUri + "-" + timestamp + "-0-0-8abFiaLMJPUmPKdk";
        String jqurl = Md5Util.encode(encryStr);
        String authUri = liveDomain + liveUri + "?auth_key=" + timestamp + "-0-0-" + jqurl;
        return authUri;
    }

    private QkjLiveCommentsDTO makeLivesConmmentDTO(String memCard, QkjLiveComments comment) {
        QkjMember member = memberService.findByMemCard(comment.getMemCard());
        if (member == null) {
            return null;
        }
        QkjLiveCommentsDTO mevosLiveCommentsDTO = new QkjLiveCommentsDTO();
        mevosLiveCommentsDTO.setCId(comment.getId());
        mevosLiveCommentsDTO.setContent(comment.getContent());
        mevosLiveCommentsDTO.setOprTime(DateUtil.generateTimeStr(comment.getOprTime()));
        mevosLiveCommentsDTO.setMemCard(member.getMemCard());
        mevosLiveCommentsDTO.setMemNickname(member.getMemNickname());
        mevosLiveCommentsDTO.setMemHeadimg(member.getMemHeadimg());
        if (StringUtils.isNotBlank(memCard) && memCard.equals(member.getMemCard())) {
            mevosLiveCommentsDTO.setIsMySend(1);
        }
        return mevosLiveCommentsDTO;
    }

    private QkjLiveDetailDTO makeLiveDetailDTO(QkjLive live, String memCard, Boolean searchAuthor,
                                               Boolean searcheRcmd, Boolean searchLiveSon, Boolean searchRemind, Boolean searchPurchased, Boolean searchQuestion) {
        QkjLiveDetailDTO mevosLiveDetailDTO = new QkjLiveDetailDTO();
        mevosLiveDetailDTO.setLiveId(live.getLiveId());
        mevosLiveDetailDTO.setLvId(live.getId());
        mevosLiveDetailDTO.setLiveTitle(live.getLiveTitle());
        mevosLiveDetailDTO.setLiveType(live.getLiveType());
        mevosLiveDetailDTO.setLiveStatus(live.getLiveStatus());
        mevosLiveDetailDTO.setJoinMembers(live.getJoinMembers());
        mevosLiveDetailDTO.setLiveContent(live.getLiveContent());
        mevosLiveDetailDTO.setLiveCoverImg(commonService.buildImgUrl(live.getLiveCoverImg()));
        mevosLiveDetailDTO.setShareTitle(live.getShareTitle() == null ? "" : live.getShareTitle());
        mevosLiveDetailDTO.setShareDesc(live.getShareDesc() == null ? "" : live.getShareDesc());
        mevosLiveDetailDTO.setSharePic(live.getSharePic() == null ? "" : commonService.buildImgUrl(live.getSharePic()));
        mevosLiveDetailDTO.setShareUrl(buildShareUrl("5", live.getId(), memCard));
        mevosLiveDetailDTO.setPrice(live.getPrice());
        mevosLiveDetailDTO.setPointFlag(live.getPointFlag());
        mevosLiveDetailDTO.setPoint(live.getPoint());
        mevosLiveDetailDTO.setLiveSonCount(live.getLiveSonCount());
        mevosLiveDetailDTO.setRemindMemberNum(live.getRemindMembers());
        mevosLiveDetailDTO.setPurchasedMembers(live.getPurchasedMembers());
        mevosLiveDetailDTO.setLiveBeginTime(DateFormater.formatDate(live.getLiveBeginTime(), "MM月dd日 HH:mm"));
        mevosLiveDetailDTO.setSmrzFlag(live.getSmrzFlag());
        mevosLiveDetailDTO.setYsrzFlag(live.getYsrzFlag());
        mevosLiveDetailDTO.setQuestionFlag(live.getQuestionFlag());
        mevosLiveDetailDTO.setIsSell(live.getIsSell());
        mevosLiveDetailDTO.setShowHall(live.getShowHall());
        mevosLiveDetailDTO.setColorSwatches(live.getColorSwatches());
        mevosLiveDetailDTO.setLiveTab(live.getLiveTab());
        mevosLiveDetailDTO.setIsController(1);
        mevosLiveDetailDTO.setQuestionTooltip(live.getQuestionTooltip());
        mevosLiveDetailDTO.setLiveManTime(live.getJoinMembers()+live.getPurchasedMembers());
        List<SalesCollectionMain> salesCollectionMainList = collectionDao.getCollectionInfo(memCard, live.getId() + "", 2);
        if (salesCollectionMainList != null & salesCollectionMainList.size() > 0) {
            mevosLiveDetailDTO.setIsController(0);
        }
        if (live.getLiveStatus() == 0) {
            long trailerTime = (live.getLiveBeginTime().getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) / 1000;
            mevosLiveDetailDTO.setLiveBeginSySecond(trailerTime);
            mevosLiveDetailDTO.setLiveBeginStr(DateUtil.generateTimeStrDjs(live.getLiveBeginTime()));
        }
        if (live.getLiveStatus() == 0 || live.getLiveStatus() == 1) {
            if (live.getLiveType() == 1) {
                //m3u8
                mevosLiveDetailDTO.setLivePlayUrl(buildPlayUrlWithAuthKey(live.getLiveDomain(), "/qkj/QKJ-LIVE-" + live.getId() + ".m3u8", 24 * 60));
                //flv
                mevosLiveDetailDTO.setLivePlayUrlFlv(buildPlayUrlWithAuthKey(live.getLiveDomain(), "/qkj/QKJ-LIVE-" + live.getId() + ".flv", 24 * 60));
            } else if (live.getLiveType() == 3) {
                mevosLiveDetailDTO.setLivePlayUrl(live.getPushStreamM3u8());
                mevosLiveDetailDTO.setLivePlayUrlFlv(live.getPushStreamFlv());
            }
        } else {
            mevosLiveDetailDTO.setBackviewUrl(live.getBackviewUrl());
        }

        if (searchAuthor) {
            // 获取作者
            mevosLiveDetailDTO.setAuthorList(memberService.getColumnistByObjTypeAndobjId(2, live.getId().intValue()));
        }
        if (searcheRcmd) {
            // 直播详情页顶部广告位
            mevosLiveDetailDTO.setSysRecommendDTOs(recommendService.findByPostTypeAndObjId(2, live.getId().intValue(), 1, 100));
        }
        if (live.getLiveType() == 2) {
            //统计系列直播学习人数
            List<QkjLive> sonLives = qkjLiveDao.findSonList(live.getId().intValue(), 0, 100);
            int joinMembers = 0;
            for(QkjLive nom : sonLives){
                joinMembers = joinMembers + nom.getJoinMembers() + nom.getPurchasedMembers();
            }
            mevosLiveDetailDTO.setLiveSonCount(sonLives.size());
//            mevosLiveDetailDTO.setPurchasedMembers(joinMembers);
            mevosLiveDetailDTO.setLiveManTime(joinMembers);
            // 获取子直播
            if (searchLiveSon) {
                List<QkjLiveDetailDTO> sons = new ArrayList<QkjLiveDetailDTO>();
                for (QkjLive son : sonLives) {
                    sons.add(makeLiveDetailDTO(son, memCard, false, false, false,
                            true, true, false));
                }
                if (sons.size() > 0) {
                    Integer isAllBuy = 1;
                    for (QkjLiveDetailDTO son : sons) {
                        if (son.getIsPurchased() == 0) {
                            isAllBuy = 0;
                            break;
                        }
                    }
                    mevosLiveDetailDTO.setIsPurchased(isAllBuy);
                }

                mevosLiveDetailDTO.setSons(sons);
            }
        }
        if (searchRemind && memCard != null) {
            // 是否预约
            QkjLiveRemind remind = qkjLiveRemindDao.findByLiveIdAndMemCard(live.getId().toString(), memCard);
            if (remind != null) {
                mevosLiveDetailDTO.setIsRemind(1);
            }
        }
        if (searchPurchased && memCard != null && judgeLivePurchased(live.getId().toString(), memCard)) {
            // 是否购买
            mevosLiveDetailDTO.setIsPurchased(1);
        }
        if (searchQuestion && live.getQuestionFlag() == 1) {
            // 问卷问题
            List<QkjQuestionDetail> questions = questionDetailDao.findByObjTypeAndObjId(1, live.getId().intValue());
            List<QkjQuestionAnswer> list = questions.stream().map(item -> {
                QkjQuestionAnswer dto = new QkjQuestionAnswer();
                dto.setObjType(item.getObjType());
                dto.setObjId(item.getObjId());
                dto.setQuId(item.getId().intValue());
                dto.setQuTitle(item.getQuTitle());
                dto.setQuType(item.getQuType());
                return dto;
            }).collect(Collectors.toList());
            mevosLiveDetailDTO.setQuestions(list);
        }
        return mevosLiveDetailDTO;
    }

    private QkjLiveDetailDTO makeLiveDetail(QkjLive live, String memCard, Boolean searchAuthor,
                                            Boolean searcheRcmd, Boolean searchLiveSon, Boolean searchRemind, Boolean searchPurchased, Boolean searchQuestion) {
        QkjLiveDetailDTO mevosLiveDetailDTO = new QkjLiveDetailDTO();
        mevosLiveDetailDTO.setLiveId(live.getLiveId());
        mevosLiveDetailDTO.setLvId(live.getId());
        mevosLiveDetailDTO.setLiveTitle(live.getLiveTitle());
        mevosLiveDetailDTO.setLiveType(live.getLiveType());
        mevosLiveDetailDTO.setLiveStatus(live.getLiveStatus());
        mevosLiveDetailDTO.setJoinMembers(live.getJoinMembers());
        mevosLiveDetailDTO.setLiveContent(live.getLiveContent());
        mevosLiveDetailDTO.setLiveCoverImg(commonService.buildImgUrl(live.getLiveCoverImg()));
        mevosLiveDetailDTO.setShareTitle(live.getShareTitle() == null ? "" : live.getShareTitle());
        mevosLiveDetailDTO.setShareDesc(live.getShareDesc() == null ? "" : live.getShareDesc());
        mevosLiveDetailDTO.setSharePic(live.getSharePic() == null ? "" : commonService.buildImgUrl(live.getSharePic()));
        mevosLiveDetailDTO.setShareUrl(buildShareUrl("5", live.getId(), memCard));
        mevosLiveDetailDTO.setPrice(live.getPrice());
        mevosLiveDetailDTO.setPointFlag(live.getPointFlag());
        mevosLiveDetailDTO.setPoint(live.getPoint());
        mevosLiveDetailDTO.setLiveSonCount(live.getLiveSonCount());
        mevosLiveDetailDTO.setRemindMemberNum(live.getRemindMembers());
        mevosLiveDetailDTO.setPurchasedMembers(live.getPurchasedMembers());
        mevosLiveDetailDTO.setLiveBeginTime(DateFormater.formatDate(live.getLiveBeginTime(), "MM月dd日 HH:mm"));
        mevosLiveDetailDTO.setSmrzFlag(live.getSmrzFlag());
        mevosLiveDetailDTO.setYsrzFlag(live.getYsrzFlag());
        mevosLiveDetailDTO.setQuestionFlag(live.getQuestionFlag());
        mevosLiveDetailDTO.setIsSell(live.getIsSell());
        mevosLiveDetailDTO.setShowHall(live.getShowHall());
        mevosLiveDetailDTO.setColorSwatches(live.getColorSwatches());
        mevosLiveDetailDTO.setLiveTab(live.getLiveTab());
        mevosLiveDetailDTO.setIsController(1);
        mevosLiveDetailDTO.setIsVisiable(live.getIsVisiable());
        mevosLiveDetailDTO.setLiveManTime(live.getJoinMembers()+live.getPurchasedMembers());
        mevosLiveDetailDTO.setInteractMonthlyImg(commonService.buildImgUrl(live.getInteractMonthlyImg()));
        mevosLiveDetailDTO.setScrollText(live.getScrollText());
        mevosLiveDetailDTO.setColorTextSwatches(live.getColorTextSwatches());
        mevosLiveDetailDTO.setAgoQuestionnaire(live.getAgoQuestionnaire());
        mevosLiveDetailDTO.setQuestionTooltip(live.getQuestionTooltip());
        mevosLiveDetailDTO.setCookQuestionnaire(live.getCookQuestionnaire());
        List<SalesCollectionMain> salesCollectionMainList = collectionDao.getCollectionInfo(memCard, live.getId() + "", 2);
        if (salesCollectionMainList != null & salesCollectionMainList.size() > 0) {
            mevosLiveDetailDTO.setIsController(0);
        }
        if (live.getLiveStatus() == 0) {
            long trailerTime = (live.getLiveBeginTime().getTimeInMillis() - Calendar.getInstance().getTimeInMillis()) / 1000;
            mevosLiveDetailDTO.setLiveBeginSySecond(trailerTime);
            mevosLiveDetailDTO.setLiveBeginStr(DateUtil.generateTimeStrDjs(live.getLiveBeginTime()));
        }
        if (live.getLiveStatus() == 0 || live.getLiveStatus() == 1) {
            if (live.getLiveType() == 1) {
                //m3u8
                mevosLiveDetailDTO.setLivePlayUrl(buildPlayUrlWithAuthKey(live.getLiveDomain(), "/qkj/QKJ-LIVE-" + live.getId() + ".m3u8", 24 * 60));
                //flv
                mevosLiveDetailDTO.setLivePlayUrlFlv(buildPlayUrlWithAuthKey(live.getLiveDomain(), "/qkj/QKJ-LIVE-" + live.getId() + ".flv", 24 * 60));
            } else if (live.getLiveType() == 3) {
                mevosLiveDetailDTO.setLivePlayUrl(live.getPushStreamM3u8());
                mevosLiveDetailDTO.setLivePlayUrlFlv(live.getPushStreamFlv());
            }
        } else {
            mevosLiveDetailDTO.setBackviewUrl(live.getBackviewUrl());
        }

        if (searchAuthor) {
            // 获取作者
            mevosLiveDetailDTO.setAuthorList(memberService.getColumnistByObjTypeAndobjId(2, live.getId().intValue()));
        }
        if (searcheRcmd) {
            // 直播详情页顶部广告位
            mevosLiveDetailDTO.setSysRecommendDTOs(recommendService.findByPostTypeAndObjId(2, live.getId().intValue(), 1, 100));
        }
        if (live.getLiveType() == 2) {
            List<Integer> integers = qkjLiveDao.selectLiveIdBySqn(live.getId().intValue());
            //统计系列直播学习人数
            List<QkjLive> sonLives = new ArrayList<>();
            integers.forEach(a->{
                QkjLive qkjLive = qkjLiveDao.selectSonList(a, 0, 100);
                if(Objects.nonNull(qkjLive)){
                    sonLives.add(qkjLive);
                }
            });
            int joinMembers = 0;
            for (QkjLive son : sonLives) {
                if (Objects.nonNull(son)) {
                    joinMembers += son.getPurchasedMembers() + son.getJoinMembers();
                }
            }
//            mevosLiveDetailDTO.setPurchasedMembers(joinMembers);
            mevosLiveDetailDTO.setLiveManTime(joinMembers);
            // 获取子直播
            if (searchLiveSon) {
                List<QkjLiveDetailDTO> sons = new ArrayList<QkjLiveDetailDTO>();
                for (QkjLive son : sonLives) {
                    if (Objects.nonNull(son)) {
                        sons.add(makeLiveDetailDTO(son, memCard, false, false, false,
                                true, true, false));
                    }
                }
                if (sons.size() > 0) {
                    Integer isAllBuy = 1;
                    for (QkjLiveDetailDTO son : sons) {
                        if (son.getIsPurchased() == 0) {
                            isAllBuy = 0;
                            break;
                        }
                    }
                    mevosLiveDetailDTO.setIsPurchased(isAllBuy);
                }

                mevosLiveDetailDTO.setSons(sons);
            }
        }
        if (searchRemind && memCard != null) {
            // 是否预约
            QkjLiveRemind remind = qkjLiveRemindDao.findByLiveIdAndMemCard(live.getId().toString(), memCard);
            if (remind != null) {
                mevosLiveDetailDTO.setIsRemind(1);
            }
        }
        if (searchPurchased && memCard != null && judgeLivePurchased(live.getId().toString(), memCard)) {
            // 是否购买
            mevosLiveDetailDTO.setIsPurchased(1);
        }
        if (searchQuestion && live.getQuestionFlag() == 1) {
            //先取答案表的数据  没有再去取问题表
            List<QkjQuestionAnswer> answers = questionAnswerDao.findByMemCardAndObjTypeAndObjId(memCard, 1, live.getId().intValue());
            if (CollectionUtils.isEmpty(answers)) {
                Integer exId = qkjExaminationDetailDao.findExIdByObjTypeAndObjId(1, live.getId().intValue());
                // 问卷问题
                List<QkjQuestionDetail> questions = questionDetailDao.SelectByObjTypeAndObjId(3, exId);
                answers = questions.stream().map(item -> {
                    QkjQuestionAnswer dto = new QkjQuestionAnswer();
                    dto.setObjType(item.getObjType());
                    dto.setObjId(item.getObjId());
                    dto.setQuId(item.getId().intValue());
                    dto.setQuTitle(item.getQuTitle());
                    dto.setQuType(item.getQuType());
                    return dto;
                }).collect(Collectors.toList());
            }
            mevosLiveDetailDTO.setQuestions(answers);
        }
        return mevosLiveDetailDTO;
    }
}
