package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.LiveRoomVideoDao;
import com.yonge.cooleshow.biz.dal.entity.LiveRoom;
import com.yonge.cooleshow.biz.dal.entity.LiveRoomVideo;
import com.yonge.cooleshow.biz.dal.entity.RecordNotify;
import com.yonge.cooleshow.biz.dal.service.LiveRoomService;
import com.yonge.cooleshow.biz.dal.service.LiveRoomVideoService;
import com.yonge.toolset.thirdparty.storage.StoragePluginContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 直播视频记录(LiveRoomVideo)表服务实现类
 *
 * @author hgw
 * @since 2022-03-18 15:41:17
 */
@Service("liveRoomVideoService")
public class LiveRoomVideoServiceImpl extends ServiceImpl<LiveRoomVideoDao, LiveRoomVideo> implements LiveRoomVideoService {

    private final static Logger log = LoggerFactory.getLogger(LiveRoomVideoServiceImpl.class);

    @Autowired
    private LiveRoomService liveRoomService;
    @Autowired
    private StoragePluginContext storagePluginContext;

    @Override
    public LiveRoomVideoDao getDao() {
        return this.baseMapper;
    }

    /**
     * 查询对应房间的录像
     *
     * @param roomUid 房间uid
     */
    @Override
    public List<LiveRoomVideo> queryVideo(String roomUid) {
        return this.list(Wrappers.<LiveRoomVideo>lambdaQuery()
                .eq(LiveRoomVideo::getRoomUid, roomUid)
                .eq(LiveRoomVideo::getType, 4)
        );
    }

    /**
     * 云端录制回调
     */
    @Override
    public void recordSync(RecordNotify recordNotify) {
        if (recordNotify.getCode().equals(200)) {
            if (Objects.nonNull(recordNotify.getType())) {
                //云端录制文件地址
                String fileUrl = storagePluginContext.getPublicUrl(recordNotify.getOutput().getFileUrl(),"live-rewind");
                //房间uid
                String roomUId = recordNotify.getRoomId();
                //融云唯一id标识
                String recordId = recordNotify.getRecordId();
                //回调事件类型
                Integer notifyType = recordNotify.getType();
                //查询直播间
                LiveRoom room = liveRoomService.getOne(new QueryWrapper<LiveRoom>().lambda()
                        .eq(LiveRoom::getRoomUid, roomUId));
                if(Objects.isNull(room)){
                    log.info("recordSync >>> roomUid is null");
                    return;
                }
                //开始录制
                if (notifyType == 1) {
                    insertVideo(fileUrl, recordId, notifyType, room);
                    return;
                }
                //录制完成
                if (notifyType == 4) {
                    //写入数据库
                    try {
                        //获取最后一次录制视频
                        LiveRoomVideo video = baseMapper.getLastRecord(roomUId, recordId);
                        if (Objects.isNull(video)) {
                            log.error("recordSync error ：roomUId : {} ,recordId:{}", roomUId, recordId);
                            return;
                        }
                        if (StringUtils.isNotEmpty(video.getUrl())) {
                            //保存切片
                            insertVideo(fileUrl, recordId, notifyType, room);
                        } else {
                            Date now = new Date();
                            video.setEndTime(now);
                            video.setType(notifyType);
                            video.setUrl(fileUrl);
                            video.setCreatedTime(now);
                            this.updateById(video);
                        }
                    } catch (Exception e) {
                        log.error("recordSync error : {}", e.getMessage());
                    }
                }
            }
        }
    }

    private void insertVideo(String fileUrl, String recordId, Integer notifyType, LiveRoom room) {
        Date now = new Date();
        LiveRoomVideo roomVideo = new LiveRoomVideo();
        roomVideo.setCourseGroupId(room.getCourseGroupId());
        roomVideo.setCourseId(room.getCourseId());
        roomVideo.setRoomUid(room.getRoomUid());
        roomVideo.setRecordId(recordId);
        roomVideo.setUrl(fileUrl);
        roomVideo.setStartTime(now);
        roomVideo.setType(notifyType);
        roomVideo.setCreatedTime(now);
        this.save(roomVideo);
    }

}

