package com.platform.modules.live.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.Query;
import com.platform.common.utils.RedisContants;
import com.platform.common.utils.RedisUtils;
import com.platform.modules.live.constants.LiveConstants;
import com.platform.modules.live.constants.SceneConstants;
import com.platform.modules.live.dao.LiveStreamStatusDao;
import com.platform.modules.live.entity.*;
import com.platform.modules.live.service.*;
import com.platform.plugs.live.LiveClient;
import com.platform.plugs.live.enums.PushStreamStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@Service("liveStreamStatusService")
@Transactional
@Slf4j
public class LiveStreamStatusServiceImpl extends ServiceImpl<LiveStreamStatusDao, LiveStreamStatusEntity> implements LiveStreamStatusService {

    @Autowired
    private LiveSceneLiveInfoService liveSceneLiveInfoService;

    @Autowired
    private LiveSceneService liveSceneService;

    @Autowired
    private LiveCasterService liveCasterService;

    @Autowired
    private LiveSceneRecordService liveSceneRecordService;

    @Autowired
    private LiveSceneLiveInfoExtService liveSceneLiveInfoExtService;

    @Autowired
    private LiveClient liveClient;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    @Transactional(readOnly = true)
    public PageUtils queryPage(Map<String, Object> params) {
        Page<LiveStreamStatusEntity> page = this.selectPage(
                new Query<LiveStreamStatusEntity>(params).getPage(),
                new EntityWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public void process(LiveStreamStatusEntity liveStreamStatusEntity) {
        //保存状态
        this.insert(liveStreamStatusEntity);
        Date now = new Date(Long.parseLong(liveStreamStatusEntity.getTime() + "000"));
        //导播台流和推流均会调用此回调，只处理推流
        LiveSceneEntity scene = null;
        Date startDate = null;
        StringBuilder recordName = new StringBuilder("快速回看_");
        String streamName = "";
        String flvUrl = null;
        if (SceneConstants.CASTER_APP_NAME.equals(liveStreamStatusEntity.getAppName())) {
            if (PushStreamStatus.publish_done.toString().equals(liveStreamStatusEntity.getAction())) {
                LiveCasterEntity liveCasterEntity = liveCasterService.selectByAppNameAndStreamName(liveStreamStatusEntity.getAppName(), liveStreamStatusEntity.getStreamName());
                if (liveCasterEntity != null) {
                    scene = liveSceneService.selectById(liveCasterEntity.getSceneId());
                    startDate = liveCasterEntity.getStartTime();
                    recordName.append("导播台");
                    streamName = liveCasterEntity.getStreamName();
//                    String[] streamsOriginals = liveClient.liveStream().generateLiveUrl(liveStreamStatusEntity.getAppName(), streamName, now);
//                    flvUrl = streamsOriginals[0];
                    //20200305 weiyan 获取直播时移的有效地址
                    flvUrl = liveClient.liveStream().generateTimeShiftUrl(startDate, liveStreamStatusEntity.getAppName(), streamName);
                }
            }
        } else {
            LiveSceneLiveInfoEntity liveSceneLiveInfoEntity = liveSceneLiveInfoService.findLiveInfoByPushDomainAppAndStream(liveStreamStatusEntity.getApp(), liveStreamStatusEntity.getAppName(), liveStreamStatusEntity.getStreamName());

            if (liveSceneLiveInfoEntity != null) {//直播间流修改状态及时间
                liveSceneLiveInfoService.updateLiveState(liveSceneLiveInfoEntity, liveStreamStatusEntity.getAction(), liveStreamStatusEntity.getTime());
                // 若为记者流，则修改记者状态为推流状态
                String key = RedisContants.REPORTER_PUSH_STATE + liveSceneLiveInfoEntity.getUserId();
                if (null != liveSceneLiveInfoEntity.getUserId() && PushStreamStatus.publish.toString().equals(liveStreamStatusEntity.getAction())){
                    redisUtils.set(key, 1, -1);
                }
                if (PushStreamStatus.publish_done.toString().equals(liveStreamStatusEntity.getAction())) {
                    // 若为记者流，则修改记者在线状态
                    if (null != liveSceneLiveInfoEntity.getUserId()){
                    	redisUtils.delete(key);
                    }
                    scene = liveSceneService.selectById(liveSceneLiveInfoEntity.getSceneId());
                    LiveSceneLiveInfoExtEntity liveSceneLiveInfoExtEntity = liveSceneLiveInfoExtService.selectByInfoId(liveSceneLiveInfoEntity.getId());
                    startDate = liveSceneLiveInfoEntity.getPushStart();
                    recordName.append(liveSceneLiveInfoEntity.getInfoName());
                    if (liveSceneLiveInfoExtEntity != null) {
//                        flvUrl = liveSceneLiveInfoExtEntity.getPlayUrlHls();
                    	//20200305 weiyan 获取直播时移的有效地址
                    	flvUrl = liveClient.liveStream().generateTimeShiftUrl(startDate, liveSceneLiveInfoEntity.getAppName(), liveSceneLiveInfoEntity.getStreamName());
                    }
                }
            }
        }
        if (PushStreamStatus.publish.toString().equals(liveStreamStatusEntity.getAction())) {
            return;
        }
        // 推流结束生成直播时移回看
        if (scene == null) {
            log.error("未找到对应现场 ： appName = {} streamName = {}", liveStreamStatusEntity.getAppName(), liveStreamStatusEntity.getStreamName());
            return;
        }

        LiveSceneRecordEntity liveSceneRecordEntity = new LiveSceneRecordEntity();
        liveSceneRecordEntity.setCreateDate(now);
        liveSceneRecordEntity.setLastUpdateDate(now);
        liveSceneRecordEntity.setSceneId(scene.getId());
        liveSceneRecordEntity.setTenantId(scene.getTenantId());
        if (StringUtils.isNotBlank(recordName)) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
            if (startDate != null)
                recordName.append("_").append(df.format(startDate));
            recordName.append("_").append(df.format(now));
        } else {
            recordName.append(scene.getSceneSign()).append("_").append(streamName);
        }

        liveSceneRecordEntity.setRecordName(recordName.toString());
        liveSceneRecordEntity.setTitleImage(scene.getTitleImage());

        // 生成duration
        if (startDate != null) {
            liveSceneRecordEntity.setDuration((double) (now.getTime() - startDate.getTime()) / 1000);
            liveSceneRecordEntity.setStartTime((int) (startDate.getTime() / 1000));
            // 生成url
            if (StringUtils.isNotBlank(flvUrl)) {
                DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
//                flvUrl += String.format("&aliyunols=on&lhs_start_human_s_8=%s&lhs_end_human_s_8=%s", df.format(startDate), df.format(now));
                //todo weiyan 20200224 用于兼容直播时移
                flvUrl += String.format("&aliyunols=on&lhs_start_human_s_8=%s&lhs_vodend_human_s_8=%s", df.format(startDate), df.format(now));
                liveSceneRecordEntity.setUri(flvUrl);
            }
        }

        liveSceneRecordEntity.setStopTime((int) (now.getTime() / 1000));
        liveSceneRecordEntity.setRecordStatus(SceneConstants.RECORD_TO_SHOW);
        liveSceneRecordEntity.setIsDelete(SceneConstants.NOT_DELETE);

        liveSceneRecordEntity.setTitleImage(scene.getTitleImage());
        // 设置回顾类型
        liveSceneRecordEntity.setRecordType(LiveConstants.RecordType.FAST_RECORD);
        liveSceneRecordService.insert(liveSceneRecordEntity);
    }
}
