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

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat; 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetImageInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetImageInfoResponse.ImageInfo;
import com.aliyuncs.vod.model.v20170321.GetMezzanineInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetMezzanineInfoResponse.Mezzanine;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse;
import com.aliyuncs.vod.model.v20170321.GetVideoInfoResponse.Video;
import com.aliyuncs.vod.model.v20170321.SubmitTranscodeJobsResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.platform.autoconfigure.live.LiveProperties;
import com.platform.common.utils.ConverterUtils;
import com.platform.common.utils.DateUtils;
import com.platform.common.utils.PageUtils;
import com.platform.modules.live.constants.LiveConstants;
import com.platform.modules.live.constants.SceneConstants;
import com.platform.modules.live.dao.LiveMultimediaDao;
import com.platform.modules.live.dto.TranscodeCompleteDto;
import com.platform.modules.live.entity.LiveCasterEntity;
import com.platform.modules.live.entity.LiveMultimediaEntity;
import com.platform.modules.live.entity.LiveSceneEntity;
import com.platform.modules.live.entity.LiveSceneLiveInfoEntity;
import com.platform.modules.live.entity.LiveSceneRecordEntity;
import com.platform.modules.live.entity.LiveStreamRecordTaskEntity;
import com.platform.modules.live.entity.LiveTranscodeInfoEntity;
import com.platform.modules.live.entity.LiveTranscodeJobEntity;
import com.platform.modules.live.service.LiveCasterService;
import com.platform.modules.live.service.LiveMultimediaService;
import com.platform.modules.live.service.LiveSceneLiveInfoService;
import com.platform.modules.live.service.LiveSceneRecordService;
import com.platform.modules.live.service.LiveSceneService;
import com.platform.modules.live.service.LiveStreamRecordTaskService;
import com.platform.modules.live.service.LiveTranscodeInfoService;
import com.platform.modules.live.service.LiveTranscodeJobService;
import com.platform.modules.live.utils.ForeignProperties;
import com.platform.modules.live.utils.ReportTypeEnum;
import com.platform.modules.plm.util.FileCalculateUtils;
import com.platform.modules.plm.util.FileSizeUnitEnum;
import com.platform.modules.plm.util.MaterialUtils;
import com.platform.plugs.common.rpc.ResponseResult;
import com.platform.plugs.common.rpc.RpcResponse;
import com.platform.plugs.live.LiveClient;
import com.platform.plugs.live.responseEntity.TranscodeInfo;
import com.platform.plugs.live.responseEntity.TranscodeJob;
import com.platform.plugs.live.responseEntity.TranscodeTask;
import com.platform.plugs.live.utils.UTCDateFormat;

@Service("liveMultimediaService")
@Transactional
public class LiveMultimediaServiceImpl extends ServiceImpl<LiveMultimediaDao, LiveMultimediaEntity> implements LiveMultimediaService {
    private final Log log = LogFactory.getLog(LiveMultimediaServiceImpl.class);
    @Autowired
    private LiveClient liveClient;
    @Autowired
    private LiveProperties properties;
    @Autowired
    private ForeignProperties foreignProperties;

    @Autowired
    private LiveTranscodeInfoService liveTranscodeInfoService;
    @Autowired
    private LiveTranscodeJobService liveTranscodeJobService;

    @Autowired
    private LiveStreamRecordTaskService liveStreamRecordTaskService;

    @Autowired
    private LiveSceneService liveSceneService;

    @Autowired
    private LiveSceneLiveInfoService liveSceneLiveInfoService;

    @Autowired
    private LiveCasterService liveCasterService;

    @Autowired
    private LiveSceneRecordService liveSceneRecordService;

    UTCDateFormat df = new UTCDateFormat();

    @Override
    @Transactional(readOnly = true)
    public PageUtils queryPageByParams(Map<String, Object> params) {
        //检索记录
        int current = ConverterUtils.parseInt(params.get("page"));
        int limit = ConverterUtils.parseInt(params.get("limit"));
        String tenantId = (String) params.get("tenantId");
        Page<Map<String, Object>> page = new Page<>(current, limit);
        List<LiveMultimediaEntity> pageList = this.baseMapper.queryPageMap(page, params);
        List<Map<String, Object>> list = new ArrayList<>();
        if (pageList != null && pageList.size() > 0) {
            for (int i = 0; i < pageList.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                LiveMultimediaEntity bean = pageList.get(i);
                if (StringUtils.isNotBlank(tenantId) && !Long.valueOf(tenantId).equals(bean.getTenantId())) {
                    continue;
                }
                if (bean == null) {
                    continue;
                }
                map.put("id", bean.getId());
                map.put("title", bean.getTitle());
                map.put("mediaType", bean.getMediaType());
                map.put("mediaTypeShow", ReportTypeEnum.getName(bean.getMediaType()));
                map.put("mediaUrl", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
                map.put("mediaSize", bean.getMediaSize() < (1024 * 1024) ? FileCalculateUtils.calculateFileSizeString(bean.getMediaSize().longValue(), FileSizeUnitEnum.KB) : FileCalculateUtils.calculateFileSizeString(bean.getMediaSize().longValue(), FileSizeUnitEnum.MB));
                map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getCoverUrl(), foreignProperties.getMediaurl()));
                map.put("mediaDuration", FileCalculateUtils.calculateFileDurationString(bean.getMediaDuration().longValue()));
                map.put("duration", bean.getMediaDuration().longValue());
                map.put("fileUrl", bean.getMediaUrl());
                map.put("createDate", bean.getCreateDate());
                map.put("mediaWidth", bean.getMediaWidth());
                map.put("mediaHeight", bean.getMediaHeight());
                map.put("createDate", DateUtils.format(bean.getCreateDate(), "yyyy年MM月dd日"));
                map.put("creatorName", bean.getCreatorName());
                map.put("mediaId", bean.getMediaId());
                map.put("state", bean.getState());
                list.add(map);
            }
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    @Transactional(readOnly = true)
    public PageUtils queryAppPageByParams(Map<String, Object> params) {
        //检索记录
        int current = ConverterUtils.parseInt(params.get("page"));
        int limit = ConverterUtils.parseInt(params.get("limit"));
        Page<Map<String, Object>> page = new Page<>(current, limit);
        List<LiveMultimediaEntity> pageList = this.baseMapper.queryPageMap(page, params);
        List<Map<String, Object>> list = new ArrayList<>();
        if (pageList != null && pageList.size() > 0) {
            for (int i = 0; i < pageList.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                LiveMultimediaEntity bean = pageList.get(i);
                if (bean == null) {
                    continue;
                }
                map.put("id", bean.getId());
                map.put("title", bean.getTitle());
                map.put("mediaType", bean.getMediaType());
                map.put("mediaTypeShow", ReportTypeEnum.getName(bean.getMediaType()));
                map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getCoverUrl(), foreignProperties.getMediaurl()));
                map.put("coverFileUrl", bean.getCoverUrl());
                // map.put("mediaUrl", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
                map.put("fileUrl", bean.getMediaUrl());
                map.put("createDate", DateUtils.format(bean.getCreateDate(), "yyyy年MM月dd日"));
                map.put("creatorName", bean.getCreatorName());
                map.put("mediaId", bean.getMediaId());
                // 20200303_Mxy 图片类型进行压缩处理
                if (bean.getMediaType()!=null && 3 == bean.getMediaType()){
                    map.put("mediaUrl", MaterialUtils.getMaterialUrl(compressImage(bean), foreignProperties.getMediaurl()));
                }else {
                    map.put("mediaUrl", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
                }
                list.add(map);
            }
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    @Transactional(readOnly = true)
    public PageUtils queryCommonPageByParams(Map<String, Object> params) {
        //检索记录
        int current = ConverterUtils.parseInt(params.get("page"));
        int limit = ConverterUtils.parseInt(params.get("limit"));
        Page<Map<String, Object>> page = new Page<>(current, limit);
        List<LiveMultimediaEntity> pageList = this.baseMapper.queryPageMap(page, params);
        List<Map<String, Object>> list = new ArrayList<>();
        if (pageList != null && pageList.size() > 0) {
            for (int i = 0; i < pageList.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                LiveMultimediaEntity bean = pageList.get(i);
                if (bean == null) {
                    continue;
                }
                map.put("id", bean.getId());
                map.put("title", bean.getTitle());
                map.put("mediaId", bean.getMediaId());
                map.put("mediaType", bean.getMediaType());
                map.put("mediaTypeShow", ReportTypeEnum.getName(bean.getMediaType()));
                map.put("coverUrl", MaterialUtils.getMaterialUrl(bean.getCoverUrl(), foreignProperties.getMediaurl()));
                map.put("coverFileUrl", bean.getCoverUrl());
                map.put("mediaUrl", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
                map.put("fileUrl", bean.getMediaUrl());
                list.add(map);
            }
        }
        page.setRecords(list);
        return new PageUtils(page);
    }

    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> info(Integer id) {
        if (null == id) {
            return null;
        }
        LiveMultimediaEntity bean = this.baseMapper.queryInfoById(id);
        if (null == bean) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", bean.getId());
        map.put("title", bean.getTitle());
        map.put("mediaType", bean.getMediaType());
        map.put("mediaTypeShow", ReportTypeEnum.getName(bean.getMediaType()));
        // map.put("mediaUrlShow", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
        map.put("mediaUrl", bean.getMediaUrl());
        map.put("mediaSize", bean.getMediaSize() < (1024 * 1024) ? FileCalculateUtils.calculateFileSizeString(bean.getMediaSize(), FileSizeUnitEnum.KB) : FileCalculateUtils.calculateFileSizeString(bean.getMediaSize().longValue(), FileSizeUnitEnum.MB));
        map.put("coverUrlShow", MaterialUtils.getMaterialUrl(bean.getCoverUrl(), foreignProperties.getMediaurl()));
        map.put("coverUrl", bean.getCoverUrl());
        map.put("mediaDuration", FileCalculateUtils.calculateFileDurationString(bean.getMediaDuration().longValue()));
        map.put("mediaWidth", bean.getMediaWidth());
        map.put("mediaHeight", bean.getMediaHeight());
        map.put("createDate", DateUtils.format(bean.getCreateDate(), "yyyy年MM月dd日"));
        map.put("creatorName", bean.getCreatorName());
        map.put("description", bean.getDescription());
        map.put("state", bean.getState());
        // 20200303_Mxy 图片类型进行压缩处理
        if (bean.getMediaType()!=null && 3 == bean.getMediaType()){
            map.put("mediaUrlShow", MaterialUtils.getMaterialUrl(compressImage(bean), foreignProperties.getMediaurl()));
        }else {
            map.put("mediaUrlShow", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
        }
        return map;
    }

    @Override
    @Transactional(readOnly = true)
    public Map<String, Object> getInfoByMediaId(String mediaId) {
        if (StringUtils.isBlank(mediaId)) {
            return null;
        }
        LiveMultimediaEntity bean = new LiveMultimediaEntity();
        bean.setMediaId(mediaId);
        bean = this.baseMapper.selectOne(bean);
        if (null == bean) {
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id", bean.getId());
        map.put("title", bean.getTitle());
        map.put("mediaType", bean.getMediaType());
        map.put("mediaTypeShow", ReportTypeEnum.getName(bean.getMediaType()));
        map.put("mediaUrlShow", MaterialUtils.getMaterialUrl(bean.getMediaUrl(), foreignProperties.getMediaurl()));
        map.put("mediaUrl", bean.getMediaUrl());
        map.put("mediaSize", bean.getMediaSize() < (1024 * 1024) ? FileCalculateUtils.calculateFileSizeString(bean.getMediaSize().longValue(), FileSizeUnitEnum.KB) : FileCalculateUtils.calculateFileSizeString(bean.getMediaSize().longValue(), FileSizeUnitEnum.MB));
        map.put("coverUrlShow", MaterialUtils.getMaterialUrl(bean.getCoverUrl(), foreignProperties.getMediaurl()));
        map.put("coverUrl", bean.getCoverUrl());
        map.put("mediaDuration", FileCalculateUtils.calculateFileDurationString(bean.getMediaDuration().longValue()));
        map.put("mediaWidth", bean.getMediaWidth());
        map.put("mediaHeight", bean.getMediaHeight());
        map.put("createDate", DateUtils.format(bean.getCreateDate(), "yyyy年MM月dd日"));
        map.put("creatorName", bean.getCreatorName());
        return map;
    }

    @Override
    public Map<String, Object> save(LiveMultimediaEntity liveMultimedia, MultipartFile mediaFile, Long userId) {
        Map<String, Object> map = new HashMap<>(7);
        liveMultimedia.setState(SceneConstants.MediaState.UploadFail.value());
        try {
            if (mediaFile != null && liveMultimedia.getMediaType() != null && (liveMultimedia.getMediaType() == 3 || liveMultimedia.getMediaType().equals(3))) {
                liveMultimedia.setOriFileName(mediaFile.getOriginalFilename());
                UploadImageResponse response = liveClient.liveUploadToVoD().uploadImageStream(liveMultimedia.getTitle(), mediaFile.getOriginalFilename(), mediaFile.getInputStream(), "default", mediaFile.getOriginalFilename().substring(mediaFile.getOriginalFilename().lastIndexOf(".") + 1), liveMultimedia.getTags(), false, null);
                if (response.isSuccess()) {
                    liveMultimedia.setMediaId(response.getImageId());
                    liveMultimedia.setRequestId(response.getRequestId());
                    liveMultimedia.setMediaUrl(extractString(response.getImageURL(), "/", 3));
                    try {
                        getImageInfo(response.getImageId(), liveMultimedia);
                        liveMultimedia.setState(SceneConstants.MediaState.Normal.value());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else if (mediaFile != null && liveMultimedia.getMediaType() != null && (liveMultimedia.getMediaType() == 1 || liveMultimedia.getMediaType().equals(1) || liveMultimedia.getMediaType() == 2 || liveMultimedia.getMediaType().equals(2))) {
                liveMultimedia.setOriFileName(mediaFile.getOriginalFilename());
                UploadStreamResponse response = liveClient.liveUploadToVoD().uploadStream(liveMultimedia.getTitle(), mediaFile.getOriginalFilename(), mediaFile.getInputStream(), false,
                        null, liveMultimedia.getTags(), liveMultimedia.getDescription(), null, properties.getDomains().getMedia().getTemplateGroupId(), false, null);
                if (response.isSuccess()) {
                    liveMultimedia.setState(SceneConstants.MediaState.Transcoding.value());
                    liveMultimedia.setMediaId(response.getVideoId());
                    liveMultimedia.setRequestId(response.getRequestId());
                    try {
                        getVideoMezzanineInfo(response.getVideoId(), liveMultimedia);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            liveMultimedia.setMediaSource(SceneConstants.MediaSource.UPLOAD);
            liveMultimedia.setCreatorId(userId);
            liveMultimedia.setCreateDate(new Date());
            liveMultimedia.setIsDelete(0);
            this.baseMapper.insert(liveMultimedia);

            // 处理转码任务
//            if (mediaFile != null && liveMultimedia.getMediaType() != null && (liveMultimedia.getMediaType() == 1 || liveMultimedia.getMediaType().equals(1) || liveMultimedia.getMediaType() == 2 || liveMultimedia.getMediaType().equals(2))) {
//                this.createTranscode(liveMultimedia.getId(), LiveConstants.ServiceType.UPLOAD, liveMultimedia.getMediaId(), LiveConstants.TranscodeStatus.UPLOADING);
//            }

            map.put("id", liveMultimedia.getId());
            map.put("title", liveMultimedia.getTitle());
            map.put("mediaId", liveMultimedia.getMediaId());
            map.put("fileUrl", liveMultimedia.getMediaUrl());
            map.put("duration", liveMultimedia.getMediaDuration());
            map.put("mediaDuration", liveMultimedia.getMediaDuration() == null ? 0 : FileCalculateUtils.calculateFileDurationString(liveMultimedia.getMediaDuration().longValue()));
            map.put("mediaUrl", MaterialUtils.getMaterialUrl(liveMultimedia.getMediaUrl(), foreignProperties.getMediaurl()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public Map<String, Object> save(LiveMultimediaEntity liveMultimedia, Long userId) {
        Map<String, Object> map = new HashMap<>(7);
        // 上传中
        liveMultimedia.setState(SceneConstants.MediaState.Uploading.value());
        liveMultimedia.setMediaSource(SceneConstants.MediaSource.UPLOAD);
        liveMultimedia.setCreatorId(userId);
        liveMultimedia.setCreateDate(new Date());
        liveMultimedia.setIsDelete(0);
        try {
            this.baseMapper.insert(liveMultimedia);
//            // 处理转码任务
//            this.createTranscode(liveMultimedia.getId(), LiveConstants.ServiceType.UPLOAD, liveMultimedia.getMediaId(), LiveConstants.TranscodeStatus.UPLOADING);
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("id", liveMultimedia.getId());
        map.put("title", liveMultimedia.getTitle());
        map.put("mediaId", liveMultimedia.getMediaId());
        map.put("fileUrl", liveMultimedia.getMediaUrl());
        map.put("duration", liveMultimedia.getMediaDuration());
        map.put("mediaDuration", liveMultimedia.getMediaDuration() == null ? 0 : FileCalculateUtils.calculateFileDurationString(liveMultimedia.getMediaDuration().longValue()));
        map.put("mediaUrl", MaterialUtils.getMaterialUrl(liveMultimedia.getMediaUrl(), foreignProperties.getMediaurl()));
        return map;
    }

    @Override
    public void getVideoMezzanineInfo(String vedioId, LiveMultimediaEntity entity) throws Exception {
        GetMezzanineInfoResponse mezzanineInfoResponse = liveClient.liveUploadToVoD().getMezzanineInfo(vedioId);
        Mezzanine mezzanine = mezzanineInfoResponse.getMezzanine();
        if (mezzanine != null) {
            entity.setMediaUrl(extractString(mezzanine.getFileURL(), "/", 3));
//            entity.setOriMediaUrl(extractString(mezzanine.getFileURL(), "/", 3));
            entity.setMediaWidth(mezzanine.getWidth() == null ? 0 : mezzanine.getWidth().intValue());
            entity.setMediaHeight(mezzanine.getHeight() == null ? 0 : mezzanine.getHeight().intValue());
            entity.setMediaDuration(mezzanine.getDuration() == null ? 0 : Float.parseFloat(mezzanine.getDuration()));
            entity.setMediaBitrate(mezzanine.getBitrate());
            entity.setMediaFps(mezzanine.getFps());
//			entity.setMediaSize(mezzanine.getSize()==null ? 0 : mezzanine.getSize().intValue());
        }
    }

    @Override
    public void getImageInfo(String imageId, LiveMultimediaEntity entity) throws Exception {
        GetImageInfoResponse imageInfoResponse = liveClient.liveUploadToVoD().getImageInfo(imageId);
        ImageInfo imageInfo = imageInfoResponse.getImageInfo();
        if (imageInfo != null) {
            entity.setMediaWidth(imageInfo.getMezzanine().getWidth());
            entity.setMediaHeight(imageInfo.getMezzanine().getHeight());
            entity.setMediaSize(imageInfo.getMezzanine().getFileSize() == null ? 0 : Long.parseLong(imageInfo.getMezzanine().getFileSize()));
            entity.setTags(imageInfo.getTags());
        }
    }

    @Override
    public void update(LiveMultimediaEntity liveMultimedia, Long userId) {
        LiveMultimediaEntity entity = this.baseMapper.selectById(liveMultimedia.getId());
        if (entity != null && entity.getId() != null) {
            try {
                if (entity.getMediaType() != null && (entity.getMediaType() == 3 || entity.getMediaType().equals(3)) && StringUtils.isNotBlank(entity.getMediaId())) {
                    liveClient.liveUploadToVoD().updateContent(entity.getMediaId(), liveMultimedia.getTitle(), liveMultimedia.getDescription(), liveMultimedia.getCateId() != null ? Long.valueOf(liveMultimedia.getCateId()) : null, liveMultimedia.getTags());
                } else if (entity.getMediaType() != null && (entity.getMediaType() == 1 || entity.getMediaType().equals(1) || entity.getMediaType() == 2 || entity.getMediaType().equals(2)) && StringUtils.isNotBlank(entity.getMediaId())) {
                    liveClient.liveUploadToVoD().updateVideoInfo(entity.getMediaId(), liveMultimedia.getTitle(), liveMultimedia.getDescription(), liveMultimedia.getCateId() != null ? Long.valueOf(liveMultimedia.getCateId()) : null, liveMultimedia.getTags());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            liveMultimedia.setLastUpdateUser(userId);
            liveMultimedia.setLastUpdateDate(new Date());
            this.baseMapper.updateById(liveMultimedia);
        }
    }

    @Override
    public void delete(Integer id, Long userId) {
        if (id == null) {
            return;
        }
        LiveMultimediaEntity entity = new LiveMultimediaEntity();
        entity.setIsDelete(1);
        entity.setId(id);
        entity.setLastUpdateDate(new Date());
        entity.setLastUpdateUser(userId);
        this.baseMapper.updateById(entity);
    }

    @Override
    public void deleteBatch(Integer[] ids, Long userId) {
        if (ids == null || ids.length == 0) {
            return;
        }
        LiveMultimediaEntity entity = new LiveMultimediaEntity();
        entity.setIsDelete(1);
        entity.setLastUpdateDate(new Date());
        entity.setLastUpdateUser(userId);
        EntityWrapper<LiveMultimediaEntity> wrapper = new EntityWrapper<>(new LiveMultimediaEntity());
        wrapper.in("id", ids);
        this.baseMapper.update(entity, wrapper);
    }

    @Override
    public void fileUploadComplete(String videoId, String fileUrl) {
        if (StringUtils.isBlank(videoId) || StringUtils.isBlank(fileUrl)) {
            return;
        }
        LiveMultimediaEntity entity = new LiveMultimediaEntity();
        entity.setMediaId(videoId);
        entity = this.baseMapper.selectOne(entity);
        if (entity != null && entity.getId() != null) {
            try {
                fileUrl = extractString(fileUrl, "/", 3);
                entity.setMediaUrl(fileUrl);
            } catch (Exception e) {
                entity.setState(SceneConstants.MediaState.UploadFail.value());
                e.printStackTrace();
            }
            this.baseMapper.updateById(entity);
        }
    }

    @Override
    public void getVideoInfo(String videoId) {
        if (StringUtils.isBlank(videoId)) {
            return;
        }
        LiveMultimediaEntity entity = new LiveMultimediaEntity();
        entity.setMediaId(videoId);
        entity = this.baseMapper.selectOne(entity);
        if (entity != null && entity.getId() != null) {
            try {
            	if(StringUtils.isBlank(entity.getMediaUrl())){
               	 GetMezzanineInfoResponse mezzanineInfoResponse = liveClient.liveUploadToVoD().getMezzanineInfo(videoId);
                    Mezzanine mezzanine = mezzanineInfoResponse.getMezzanine();
                    if (mezzanine != null) {
                        entity.setMediaUrl(extractString(mezzanine.getFileURL(), "/", 3));
                    }
               }
                GetVideoInfoResponse videoInfoResponse = liveClient.liveUploadToVoD().getVideoInfo(videoId);
                Video video = videoInfoResponse.getVideo();
//                entity.setMediaDuration(video.getDuration() == null ? 0 : video.getDuration());
//                entity.setMediaSize(video.getSize() == null ? 0 : video.getSize());
                List<String> snapshots = new ArrayList<>();
                if (video.getSnapshots() != null && video.getSnapshots().size() > 0) {
                    for (String str : video.getSnapshots()) {
                        if (StringUtils.isNotBlank(str)) {
                            snapshots.add(extractString(str, "/", 3));
                        }
                    }
                }
                entity.setMediaSnapshots(StringUtils.join(snapshots, ","));
                entity.setTags(video.getTags());
                entity.setCoverUrl(extractString(video.getCoverURL(), "/", 3));
                if(StringUtils.isNoneBlank(entity.getMediaUrl()) && !entity.getMediaUrl().endsWith(".m3u8")){
                	entity.setState(SceneConstants.MediaState.Normal.value());
                }
                this.baseMapper.updateById(entity);
            } catch (Exception e) {
                entity.setState(SceneConstants.MediaState.UploadFail.value());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void getImageInfo(String imageId){
        if (StringUtils.isBlank(imageId)) {
            return;
        }
        LiveMultimediaEntity entity = new LiveMultimediaEntity();
        entity.setMediaId(imageId);
        entity = this.baseMapper.selectOne(entity);
        if (entity != null && entity.getId() != null) {
            try {
            	getImageInfo(imageId, entity);
            	entity.setLastUpdateDate(new Date());
                this.baseMapper.updateById(entity);
            } catch (Exception e) {
                entity.setState(2);
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void videoAnalysisComplete(String videoId, Integer mediaWidth, Integer mediaHeight, Float mediaDuration, String mediaBitrate, String mediaFps, Long mediaSize) {
    	if (StringUtils.isBlank(videoId)) {
            return;
        }
        LiveMultimediaEntity entity = new LiveMultimediaEntity();
        entity.setMediaId(videoId);
        entity = this.baseMapper.selectOne(entity);
        if (entity != null && entity.getId() != null) {
            try {
                entity.setMediaWidth(mediaWidth);
                entity.setMediaHeight(mediaHeight);
                entity.setMediaDuration(mediaDuration);
                entity.setMediaBitrate(mediaBitrate);
                entity.setMediaFps(mediaFps);
                entity.setMediaSize(mediaSize);
                if(StringUtils.isBlank(entity.getMediaUrl())){
                	 GetMezzanineInfoResponse mezzanineInfoResponse = liveClient.liveUploadToVoD().getMezzanineInfo(videoId);
                     Mezzanine mezzanine = mezzanineInfoResponse.getMezzanine();
                     if (mezzanine != null) {
                         entity.setMediaUrl(extractString(mezzanine.getFileURL(), "/", 3));
                         if(entity.getMediaType()==null && StringUtils.isNotBlank(mezzanine.getFileURL())){
                        	 entity.setMediaType(mezzanine.getFileURL().endsWith(".mp3") ?  SceneConstants.MediaType.AUDIO.getValue() : SceneConstants.MediaType.VIDEO.getValue());
                         }
                     }
                }
                // 添加m3u8处理
                LiveStreamRecordTaskEntity task = this.liveStreamRecordTaskService.selectByVideoId(videoId);
                LiveSceneRecordEntity liveSceneRecordEntity = null;
                if (task != null) {
                    //查询现场
                    String appName = task.getAppName();
                    String streamName = task.getStreamName();
                    String recordName = "";
                    LiveSceneEntity scene;
                    if (SceneConstants.CASTER_APP_NAME.equals(appName)) {
                        LiveCasterEntity liveCasterEntity = liveCasterService.selectByAppNameAndStreamName(appName, streamName);
                        scene = liveSceneService.selectById(liveCasterEntity.getSceneId());
                        recordName = "导播台";
                    } else {
                        scene = liveSceneService.selectBySign(appName);
                        LiveSceneLiveInfoEntity infoEntity = liveSceneLiveInfoService.findLiveInfoByLiveDomainAppAndStream(task.getDomainName(), appName, streamName);
                        if (infoEntity != null) {
                            recordName = infoEntity.getInfoName();
                        }
                    }
                    if (scene == null) {
                        log.error("videoAnalysisComplete m3u8 error, can not find LiveSceneEntity");
                        return;
                    }

                    // 查询视频信息
                    GetMezzanineInfoResponse mezzanineInfo = liveClient.liveUploadToVoD().getMezzanineInfo(videoId);
                    if (mezzanineInfo != null && mezzanineInfo.getMezzanine() != null) {
                        // 添加记录formSessionId
                        final Mezzanine mezzanine = mezzanineInfo.getMezzanine();
                        Date now = new Date();
                        liveSceneRecordEntity = new LiveSceneRecordEntity();
                        liveSceneRecordEntity.setCreateDate(now);
                        liveSceneRecordEntity.setLastUpdateDate(now);
                        liveSceneRecordEntity.setSceneId(scene.getId());
                        liveSceneRecordEntity.setTenantId(scene.getTenantId());
                        if (StringUtils.isNotBlank(recordName)) {
                            recordName += "_m3u8";
                            DateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
                            if (task.getRecordStartTime() != null && task.getRecordEndTime() != null)
                                recordName += "_" + df.format(task.getRecordStartTime()) + "_" + df.format(task.getRecordEndTime());
                            liveSceneRecordEntity.setRecordName(recordName);
                        } else
                            liveSceneRecordEntity.setRecordName(scene.getSceneSign() + "_" + streamName);
                        liveSceneRecordEntity.setTitleImage(scene.getTitleImage());
                        liveSceneRecordEntity.setUri("/" + mezzanine.getFileName());
                        liveSceneRecordEntity.setDuration(Double.valueOf(mezzanine.getDuration()));
                        liveSceneRecordEntity.setStartTime((int) (task.getRecordStartTime().getTime() / 1000));
                        liveSceneRecordEntity.setStopTime((int) (task.getRecordEndTime().getTime() / 1000));
                        liveSceneRecordEntity.setRecordStatus(SceneConstants.RECORD_TO_SHOW);
                        liveSceneRecordEntity.setIsDelete(SceneConstants.NOT_DELETE);

                        liveSceneRecordEntity.setMediaId(entity.getId());
                        // 设置回顾类型
                        liveSceneRecordEntity.setRecordType(LiveConstants.RecordType.M3U8_RECORD);

                        entity.setOriMediaUrl(liveSceneRecordEntity.getUri());
                    } else {
                        log.error("未生成地址信息:" + videoId);
                    }
                }
                if(StringUtils.isNoneBlank(entity.getMediaUrl()) && !entity.getMediaUrl().endsWith(".m3u8")){
                	entity.setState(SceneConstants.MediaState.Normal.value());
                }
                this.baseMapper.updateById(entity);
                if (liveSceneRecordEntity != null) {
                    liveSceneRecordService.insert(liveSceneRecordEntity);
                }

                // 转码任务
//                this.createTranscode(entity.getId(), entity.getMediaSource(), videoId, LiveConstants.TranscodeStatus.TRANSCODEING);

            } catch (Exception e) {
                entity.setState(SceneConstants.MediaState.UploadFail.value());
                e.printStackTrace();
            }
        }
    }

    @Override
    public void addLiveRecordVideoComplete(String videoId, String domainName, String appName, String streamName, String recordStartTime, String recordEndTime, String eventTime) {
        if (StringUtils.isBlank(domainName) || StringUtils.isBlank(appName) || StringUtils.isBlank(streamName)) return;

        LiveStreamRecordTaskEntity entity = new LiveStreamRecordTaskEntity();
        entity.setDomainName(domainName);
        entity.setAppName(appName);
        entity.setStreamName(streamName);
        entity.setVideoId(videoId);
        entity.setIsOk(0);

        try {
            if (StringUtils.isNotBlank(recordStartTime)) {
                entity.setRecordStartTime(df.parse(recordStartTime));
            }
            if (StringUtils.isNotBlank(recordEndTime))
                entity.setRecordEndTime(df.parse(recordEndTime));
            if (StringUtils.isNotBlank(eventTime))
                entity.setStartTime(df.parse(eventTime));
        } catch (ParseException e) {

        }
        liveStreamRecordTaskService.insert(entity);

        // TODO 加入媒体库
        LiveMultimediaEntity multimediaEntity = new LiveMultimediaEntity();
        LiveSceneLiveInfoEntity liveSceneLiveInfoEntity = liveSceneLiveInfoService.findLiveInfoByLiveDomainAppAndStream(domainName, appName, streamName);
        if (liveSceneLiveInfoEntity == null || liveSceneLiveInfoEntity.getTenantId() == null || liveSceneLiveInfoEntity.getTenantId() <= 0) {
            LiveSceneEntity liveSceneEntity = liveSceneService.selectBySign(appName);
            if (liveSceneEntity != null && liveSceneEntity.getTenantId() != null) {
                multimediaEntity.setTenantId(liveSceneEntity.getTenantId());
            }
        } else {
            multimediaEntity.setTenantId(liveSceneLiveInfoEntity.getTenantId());
            try {
                if (liveSceneLiveInfoEntity.getUserId() != null && liveSceneLiveInfoEntity.getUserId() > 0)
                    multimediaEntity.setCreatorId(Long.valueOf(liveSceneLiveInfoEntity.getUserId() + ""));
            } catch (Exception e) {

            }
        }
        String title = appName + "_" + streamName;
        multimediaEntity.setState(SceneConstants.MediaState.Transcoding.value());
        multimediaEntity.setMediaSource(SceneConstants.MediaSource.RECORD);
        multimediaEntity.setMediaId(videoId);
        multimediaEntity.setCreateDate(new Date());
        multimediaEntity.setIsDelete(0);
        multimediaEntity.setTitle(title);

        this.baseMapper.insert(multimediaEntity);
        // 处理转码任务
//        this.createTranscode(entity.getId().intValue(), LiveConstants.ServiceType.RECORD, videoId, LiveConstants.TranscodeStatus.TRANSCODEING);
    }

    @Override
    public void transcodeComplete(String videoId, TranscodeCompleteDto dto) throws ClientException {
        // 处理媒体库信息
        LiveMultimediaEntity liveMultimedia = new LiveMultimediaEntity();
        liveMultimedia.setMediaId(videoId);
        liveMultimedia = this.baseMapper.selectOne(liveMultimedia);
        if (liveMultimedia == null || liveMultimedia.getId() == null) {
            // 更新转码任务
//            this.updateTranscode(videoId, LiveConstants.TranscodeStatus.TRANSCODE_FAIL);
            log.error("未找到素材信息 videoId ： " + videoId);
            return;
        }
        String snapshot = null;
        try {
            liveMultimedia.setMediaUrl(extractString(dto.getFileUrl(), "/", 3));
            liveMultimedia.setMediaWidth(dto.getWidth() == null ? 0 : dto.getWidth().intValue());
            liveMultimedia.setMediaHeight(dto.getHeight() == null ? 0 : dto.getHeight().intValue());
            liveMultimedia.setMediaDuration(dto.getDuration());
            liveMultimedia.setMediaBitrate(dto.getBitrate());
            liveMultimedia.setMediaFps(dto.getFps());
            liveMultimedia.setMediaSize(dto.getSize() == null ? 0 : dto.getSize());

            GetVideoInfoResponse videoInfoResponse = liveClient.liveUploadToVoD().getVideoInfo(videoId);
            snapshot = extractString(videoInfoResponse.getVideo().getCoverURL(), "/", 3);
            liveMultimedia.setCoverUrl(snapshot);
            List<String> snapshots = new ArrayList<>();
            if (videoInfoResponse.getVideo().getSnapshots() != null && videoInfoResponse.getVideo().getSnapshots().size() > 0) {
                for (String str : videoInfoResponse.getVideo().getSnapshots()) {
                    if (StringUtils.isNotBlank(str)) {
                        snapshots.add(extractString(str, "/", 3));
                    }
                }
                liveMultimedia.setMediaSnapshots(StringUtils.join(snapshots, ","));
            }
            liveMultimedia.setState(SceneConstants.MediaState.Normal.value());
            // 录制语音mp3单独处理
            liveMultimedia.setMediaType(dto.getIsAudio() ? SceneConstants.MediaType.AUDIO.getValue() : SceneConstants.MediaType.VIDEO.getValue());
            liveMultimedia.setLastUpdateDate(new Date());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //处理转码任务
        LiveStreamRecordTaskEntity task = liveStreamRecordTaskService.selectByVideoId(videoId);
        if (task != null) {

            task.setIsOk(1);//转码完成
            String domainName = task.getDomainName();
            String appName = task.getAppName();
            String streamName = task.getStreamName();
            if (dto != null) {
                if (!"success".equals(dto.getStatus()))
                    log.error("transcodeComplete error");
                try {
                    if (StringUtils.isNotBlank(dto.getStartTime()))
                        task.setStartTime(df.parse(dto.getStartTime()));
                    if (StringUtils.isNotBlank(dto.getFinishTime()))
                        task.setEndTime(df.parse(dto.getFinishTime()));
                } catch (ParseException e) {

                }
            }
            liveStreamRecordTaskService.updateById(task);
            if (dto == null) //无录制返回值，不处理录制配置和回顾
                return;

            //查询现场
            LiveSceneEntity scene;
            if (SceneConstants.CASTER_APP_NAME.equals(appName)) {
                LiveCasterEntity liveCasterEntity = liveCasterService.selectByAppNameAndStreamName(appName, streamName);
                scene = liveSceneService.selectById(liveCasterEntity.getSceneId());
            } else {
                scene = liveSceneService.selectBySign(appName);
            }
            if (scene == null) {
                log.error("transcodeComplete error, can not find LiveSceneEntity");
                return;
            }
            //删除录制配置
            //查询是否有未完成的录制任务
//            List<LiveStreamRecordTaskEntity> tasks;
            String recordName = "";
            Integer userId = null;
            if (SceneConstants.CASTER_APP_NAME.equals(appName)) {//导播台流录制
//                tasks = liveStreamRecordTaskService.selectUnOkTasks(domainName, appName, streamName);
                recordName = "导播台";
            } else {//推流录制
//                tasks = liveStreamRecordTaskService.selectUnOkTasks(domainName, appName);
                LiveSceneLiveInfoEntity infoEntity = liveSceneLiveInfoService.findLiveInfoByLiveDomainAppAndStream(domainName, appName, streamName);
                if (infoEntity != null) {
                    recordName = infoEntity.getInfoName();
                    userId = infoEntity.getUserId();
                }
            }
//            if (tasks == null || tasks.size() == 0) {//任务均完成，//删除录制配置
//                if (SceneConstants.LIVE_STATE_REVIEW.equals(scene.getLiveState())) {
//                    if (SceneConstants.CASTER_APP_NAME.equals(appName)) {
//                        liveClient.liveRecord().deleteLiveRecordVodConfig(appName, streamName);
//                    } else {
//                        liveClient.liveRecord().deleteLiveRecordVodConfig(appName, "*");
//                    }
//                }
//            }
            //保存回顾信息
            Date now = new Date();
            String title = scene.getSceneSign() + "_" + streamName;
            String cateId = liveClient.liveRecord().getLiveRecordConfig().getVodRecordCategory();
            liveMultimedia.setTitle(title);
            liveMultimedia.setCateId(cateId);
            liveMultimedia.setOriFileName(streamName);
            liveClient.liveUploadToVoD().updateVideoInfo(videoId, title, null, Long.valueOf(cateId), null);

//            LiveSceneRecordEntity liveSceneRecordEntity = new LiveSceneRecordEntity();
            LiveSceneRecordEntity liveSceneRecordEntity = liveSceneRecordService.selectOne(
                    new EntityWrapper<LiveSceneRecordEntity>().eq("media_id", liveMultimedia.getId()).eq("record_type", LiveConstants.RecordType.MP4_RECORD)
            );

            LiveSceneLiveInfoEntity infoEntity = liveSceneLiveInfoService.findLiveInfoByLiveDomainAppAndStream(domainName, appName, streamName);

            if (liveSceneRecordEntity == null){

                liveSceneRecordEntity = new LiveSceneRecordEntity();

                if (userId != null) {
                    liveSceneRecordEntity.setCreatorId(userId);
                }
                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 (task.getRecordStartTime() != null && task.getRecordEndTime() != null)
                        recordName += "_" + df.format(task.getRecordStartTime()) + "_" + df.format(task.getRecordEndTime());
                    liveSceneRecordEntity.setRecordName(recordName);
                } else
                    liveSceneRecordEntity.setRecordName(scene.getSceneSign() + "_" + streamName);
                liveSceneRecordEntity.setTitleImage(scene.getTitleImage());
                liveSceneRecordEntity.setUri(extractString(dto.getFileUrl(), "/", 3));
                liveSceneRecordEntity.setDuration(Double.valueOf(dto.getDuration()));
                liveSceneRecordEntity.setStartTime((int) (task.getRecordStartTime().getTime() / 1000));
                liveSceneRecordEntity.setStopTime((int) (task.getRecordEndTime().getTime() / 1000));
                liveSceneRecordEntity.setRecordStatus(SceneConstants.RECORD_TO_SHOW);
                liveSceneRecordEntity.setIsDelete(SceneConstants.NOT_DELETE);
                liveSceneRecordEntity.setMediaId(liveMultimedia.getId());

                if (StringUtils.isNotBlank(snapshot))// 更新标题图
                    liveSceneRecordEntity.setTitleImage(snapshot);
                // 设置回顾类型
                if (StringUtils.isNotBlank(liveSceneRecordEntity.getUri())){
                    if (liveSceneRecordEntity.getUri().endsWith(".mp3")){
                        liveSceneRecordEntity.setRecordType(LiveConstants.RecordType.MP3_RECORD);
                    } else {
                        liveSceneRecordEntity.setRecordType(LiveConstants.RecordType.MP4_RECORD);
                    }
                }
                // 202010225_Matt 录制转文字
                if (infoEntity != null){
                    if (infoEntity.getIsTxt() != null && 1 == infoEntity.getIsTxt()){
                        if (liveSceneRecordEntity.getUri().endsWith(".mp4")){

                            List<LiveProperties.Template> templates = properties.getTemplates();

                            if (templates != null && templates.size() > 0){
                                for (LiveProperties.Template template : templates){
                                    if ("统一云剪辑mp3转码".equals(template.getTemplateName())){
                                        RpcResponse<SubmitTranscodeJobsResponse> submitResponse = liveClient.liveTransCode().submitTransCodeJobs(videoId, template.getTemplateId());
                                        if (!ResponseResult.ERROR.equals(submitResponse.getResult())){
                                            liveSceneRecordEntity.setToTxtStatus(0);
                                            liveSceneRecordEntity.setIsTxt(1);
                                        }
                                    }
                                }
                            }
                        }else if (liveSceneRecordEntity.getUri().endsWith(".mp3")){
                            // 语音文件转文字
//                            String mp3Url = "http://" + properties.getDomains().getMedia().getDomainName() + extractString(dto.getFileUrl(), "/", 3);
//                            String voiceToTextTaskId = liveClient.liveAudio().submitFileTransRequest(mp3Url, "platform/live/notify/voiceToText");
//
//                            liveSceneRecordEntity.setTaskId(voiceToTextTaskId);
//                            liveSceneRecordEntity.setVoiceUrl(mp3Url);
//                            liveSceneRecordEntity.setToTxtStatus(2);
//                            liveSceneRecordEntity.setIsTxt(1);
                        }
                    }else {
                        liveSceneRecordEntity.setTaskId(null);
                        liveSceneRecordEntity.setVoiceUrl(null);
                        liveSceneRecordEntity.setToTxtStatus(0);
                        liveSceneRecordEntity.setIsTxt(0);
                    }
                }else {
                    log.info("获取现场直播信息失败");
                }

                liveSceneRecordService.insert(liveSceneRecordEntity);
            }else {
                // 语音文件转文字
//                String mp3Url = "http://" + properties.getDomains().getMedia().getDomainName() + extractString(dto.getFileUrl(), "/", 3);
//                String voiceToTextTaskId = liveClient.liveAudio().submitFileTransRequest(mp3Url, "platform/live/notify/voiceToText");
//
//                liveSceneRecordEntity.setTaskId(voiceToTextTaskId);
//                liveSceneRecordEntity.setVoiceUrl(mp3Url);
//
//                liveSceneRecordService.updateById(liveSceneRecordEntity);
            }
        }

        this.baseMapper.updateById(liveMultimedia);
        // 更新转码任务
//        this.updateTranscode(videoId, LiveConstants.TranscodeStatus.TRANSCODE_SUCCESS);
    }

    @Override
    public void updateOriMediaUrl(String videoId, String fileUrl, Long size) {
    	EntityWrapper<LiveMultimediaEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("media_id", videoId);
        LiveMultimediaEntity updateEntity = this.selectOne(wrapper);
        if(updateEntity == null || updateEntity.getId() == null){
        	log.error("未找到素材信息 videoId : " + videoId);
        	return;
        }
        updateEntity.setMediaUrl(StringUtils.isBlank(fileUrl) ? null : extractString(fileUrl, "/", 3));
//        updateEntity.setState(SceneConstants.MediaState.Transcoding.value());// TODO 上传视频默认必须转码，不转码需要重新处理
//        boolean result = this.update(updateEntity, wrapper);
        if(StringUtils.isNotBlank(updateEntity.getMediaUrl()) && !updateEntity.getMediaUrl().endsWith(".m3u8")){
        	updateEntity.setState(SceneConstants.MediaState.Normal.value());
        }
        boolean result = this.updateById(updateEntity);
        if (!result) {
            log.error("未找到素材信息 videoId : " + videoId);
        }
        // 转码任务
//        LiveMultimediaEntity entity = this.selectOne(wrapper);
//        this.createTranscode(entity.getId(), entity.getMediaType(), videoId, LiveConstants.TranscodeStatus.TRANSCODEING);
    }

    private String extractString(String oriStr, String subStr, int i) {
        if (StringUtils.isBlank(oriStr) || StringUtils.isBlank(subStr) || i < 0) {
            return null;
        }
        for (int j = 0; j < i; j++) {
            if (j == i - 1) {
                oriStr = oriStr.substring(oriStr.indexOf(subStr));
            } else {
                oriStr = oriStr.substring(oriStr.indexOf(subStr) + 1);
            }
        }
        return oriStr;
    }

    @Override
    public void createTranscode(Integer serviceId, Integer serviceType, String videoId, Integer transcodeStatus) {

        LiveTranscodeInfoEntity infoEntity = new LiveTranscodeInfoEntity();
        List<LiveTranscodeJobEntity> jobEntityList = new ArrayList<>();

        try {

            RpcResponse<List<TranscodeTask>> rpcResponse = liveClient.liveTransCode().transCodeTaskList(videoId, null, null);

            if (ResponseResult.ERROR.equals(rpcResponse.getResult())) {
                log.error("获取转码任务列表失败");
                return;
            }
            List<TranscodeTask> taskList = rpcResponse.getResponse();

            if (null == taskList || taskList.size() == 0)
                return;
            TranscodeInfo info = liveClient.liveTransCode().transCodeTaskInfo(taskList.get(0).getTranscodeTaskId()).getResponse();

            List<TranscodeJob> jobList = info.getTranscodeJobs();

            infoEntity.setVideoId(videoId);
            infoEntity.setServiceId(serviceId);
            infoEntity.setServiceType(serviceType);
            infoEntity.setTranscodeTemplateGroupId(properties.getDomains().getMedia().getTemplateGroupId());
            infoEntity.setTranscodeStatus(transcodeStatus);
            infoEntity.setTranscodeTaskId(info.getTranscodeTaskId());

            if (transcodeStatus.equals(LiveConstants.TranscodeStatus.TRANSCODEING)) {
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                infoEntity.setCreationTime(df.format(new Date()));
            }

            for (TranscodeJob job : jobList) {
                LiveTranscodeJobEntity jobEntity = new LiveTranscodeJobEntity();

                BeanUtils.copyProperties(job, jobEntity);
                jobEntity.setServiceId(serviceId);
                jobEntity.setServiceType(serviceType);
                jobEntity.setTranscodeTemplateGroupId(properties.getDomains().getMedia().getTemplateGroupId());
                jobEntity.setTranscodeTaskId(info.getTranscodeTaskId());
                jobEntity.setTranscodeStatus(transcodeStatus);

                jobEntityList.add(jobEntity);
            }

            liveTranscodeInfoService.insert(infoEntity);
            liveTranscodeJobService.insertBatch(jobEntityList);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateTranscode(String videoId, Integer transcodeStatus) {

        // 根据videoId获取
        LiveTranscodeInfoEntity infoEntity = liveTranscodeInfoService.getByVideoId(videoId);
        if(infoEntity==null || infoEntity.getId()!=null){
        	return;
        }
        List<LiveTranscodeJobEntity> jobEntityList = liveTranscodeJobService.getByTaskId(infoEntity.getTranscodeTaskId());

        if (null == jobEntityList || jobEntityList.size() == 0) {
            log.error("获取转码任务信息失败");
            return;
        }

        // 设置转码状态
        infoEntity.setTranscodeStatus(transcodeStatus);
        for (LiveTranscodeJobEntity job : jobEntityList) {
            job.setTranscodeStatus(transcodeStatus);
        }

        if (LiveConstants.TranscodeStatus.TRANSCODE_SUCCESS.equals(transcodeStatus)) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            infoEntity.setCompleteTime(df.format(now));
            for (LiveTranscodeJobEntity job : jobEntityList) {
                job.setCompleteTime(df.format(now));
            }
        }

        liveTranscodeInfoService.updateById(infoEntity);
        liveTranscodeJobService.updateBatchById(jobEntityList);
    }

    @Override
    public boolean reTranscode(String videoId) {

        // 根据videoId获取
        LiveTranscodeInfoEntity infoEntity = liveTranscodeInfoService.getByVideoId(videoId);
        List<LiveTranscodeJobEntity> jobEntityList = liveTranscodeJobService.getByTaskId(infoEntity.getTranscodeTaskId());

        if (StringUtils.isBlank(infoEntity.getTranscodeTemplateGroupId()) || null == jobEntityList || jobEntityList.size() == 0) {
            log.error("获转码任务信息失败");
            return false;
        }

        if (LiveConstants.TranscodeStatus.TRANSCODE_SUCCESS.equals(infoEntity.getTranscodeStatus())) {
            log.error("视频已转码成功，不能重新转码");
            return false;
        }

        // 新建转码任务
        final RpcResponse<SubmitTranscodeJobsResponse> rpcResponse = liveClient.liveTransCode().submitTransCodeJobs(videoId, infoEntity.getTranscodeTemplateGroupId());

        if (ResponseResult.ERROR.equals(rpcResponse.getResult())) {
            log.info("执行新建转码任务失败");
            return false;
        }

        // 设置转码状态
        infoEntity.setTranscodeStatus(LiveConstants.TranscodeStatus.TRANSCODEING);
        for (LiveTranscodeJobEntity job : jobEntityList) {
            job.setTranscodeStatus(LiveConstants.TranscodeStatus.TRANSCODEING);
        }
        liveTranscodeInfoService.updateById(infoEntity);
        liveTranscodeJobService.updateBatchById(jobEntityList);

        return true;
    }

    @Override
    public LiveMultimediaEntity getByMediaUrl(String mediaUrl) {
        EntityWrapper<LiveMultimediaEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("media_url", mediaUrl);
        return this.selectOne(wrapper);
    }
    
    @Override
	public void saveToLocal(String videoUrl,String title, HttpServletResponse response){
    	InputStream is = null;
		OutputStream os = null;
		HttpURLConnection con = null;
		try {
			 response.reset();
			 videoUrl = (videoUrl.indexOf("?")>0 ? videoUrl.substring(0, videoUrl.lastIndexOf("?")) : videoUrl);
			 URL url = new URL(videoUrl);
			// 打开连接
			con = (HttpURLConnection) url.openConnection();;
			// 设置请求超时为5s
//			con.setConnectTimeout(5 * 1000);
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            con.connect();
			// 输入流
			is = con.getInputStream();
			String fileName = (StringUtils.isBlank(title)? new Date().getTime() : title)+"."+videoUrl.substring(videoUrl.lastIndexOf(".")+1);  
			response.setContentType("application/force-download;charset=UTF-8");
//			response.setCharacterEncoding("utf-8");
//			response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
			response.setHeader("FileName", URLEncoder.encode(fileName, "UTF-8"));
//			response.setHeader("Access-Control-Expose-Headers", "FileName");
			os = response.getOutputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024 * 1024 * 5];
			// 读取到的数据长度
			int len;
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
//			response.setContentType("application/force-download;charset=UTF-8");
//			response.setHeader("FileName", URLEncoder.encode(fileName, "UTF-8"));
//			InputStream fis = new BufferedInputStream(is);
//		    byte[] buffer = new byte[fis.available()];
//		    fis.read(buffer);
//		    fis.close();
//		    System.out.println(fis.available()+"-------------------"+response.getBufferSize());
//			os = new BufferedOutputStream(response.getOutputStream());
//			os.write(buffer);// 输出文件
//			os.flush();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
            if (os != null) {
                try {
                	os.flush();
                    os.close();
                } catch (IOException e) {
                    os = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
            if (is != null) {
                try {
                	is.close();
                } catch (IOException e) {
                	is = null;
                    throw new RuntimeException(e);
                } finally {
                    if (con != null) {
                        con.disconnect();
                        con = null;
                    }
                }
            }
        }
	}

    /**
     * 图片压缩
     *
     * @param sourceEntity 源素材
     * */
    private String compressImage(LiveMultimediaEntity sourceEntity){

        if (StringUtils.isBlank(sourceEntity.getMediaUrl()))
            return null;

        String sourceMediaUrl = sourceEntity.getMediaUrl();

        // gif类型不可压缩
        if (sourceEntity.getMediaUrl().endsWith(".gif"))
            return sourceMediaUrl;
        // 源文件宽高不能超过30000px
        if (null == sourceEntity.getMediaHeight() || null == sourceEntity.getMediaWidth()
                || sourceEntity.getMediaHeight() > 30000 || sourceEntity.getMediaWidth() > 30000)
            return sourceMediaUrl;
        // 源文件大小不超过20MB(即20971520字节)
        if (null == sourceEntity.getMediaSize() || sourceEntity.getMediaSize() > 20971520)
            return sourceMediaUrl;

        // 返回拼接压缩后地址
        return sourceMediaUrl + properties.getCompressImage().getGeometricFormat();
    }
}
