package com.platform.modules.live.service.impl;/**
 * Created by TROY on 2019/5/24.
 */

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyun.vod.upload.resp.UploadVideoResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.platform.autoconfigure.live.LiveProperties;
import com.platform.common.utils.FileUtils;
import com.platform.modules.live.constants.SceneConstants;
import com.platform.modules.live.entity.LiveMultimediaEntity;
import com.platform.modules.live.service.LiveMultimediaService;
import com.platform.modules.live.service.LiveMultimediaSyncService;
import com.platform.modules.plm.util.MaterialUtils;
import com.platform.plugs.live.LiveClient;
import com.platform.plugs.live.rpcEntity.LiveUploadVideo;

/**
 * @author TROY
 * @version V1.0
 * @ClassName: LiveMultimediaSyncServiceImpl
 * @Description: TODO
 * @date 2019/5/24 16:00
 */
@Service
public class LiveMultimediaSyncServiceImpl implements LiveMultimediaSyncService {
	@Autowired
	private LiveMultimediaService liveMultimediaService;
	@Autowired
	private LiveClient liveClient;
	@Autowired
	private LiveProperties properties;

	@Async
	@Override
	public void uploadMediaSync(String identifier, String filename, Integer mid) {
		// 获取素材信息
		LiveMultimediaEntity entity;
		if (null!=mid) {
			entity = liveMultimediaService.selectById(mid);
		} else {
			entity = liveMultimediaService.selectOne(new EntityWrapper<LiveMultimediaEntity>().eq
					("ori_file_identifier", identifier).orderBy("id", false));
		}
		LiveMultimediaEntity updateEntity = new LiveMultimediaEntity();
		updateEntity.setId(entity.getId());
		updateEntity.setState(SceneConstants.MediaState.Uploading.value());
		//20200317 weiyan 转码回调函数根据videoId获取不到素材信息问题
		
		boolean delDir = false;
		if (null!=entity && null != entity.getMediaType()) {
			if (SceneConstants.MediaType.IMAGE.getValue().equals(entity.getMediaType())) {
				// 图片上传
				UploadImageResponse response = liveClient.liveUploadToVoD().uploadImageStream(entity.getTitle(),
						filename, null, "default", FileUtils.getSuffix(filename), entity.getTags(), false, null);
				if (response.isSuccess()) {
					updateEntity.setMediaId(response.getImageId());
					updateEntity.setRequestId(response.getRequestId());
					updateEntity.setMediaUrl(extractString(response.getImageURL(), "/", 3));
					try {
						liveMultimediaService.getImageInfo(response.getImageId(), updateEntity);
						// 20200313_Mxy 图片上传状态修改
						updateEntity.setState(SceneConstants.MediaState.Normal.value());
					} catch (Exception e) {
						updateEntity.setState(SceneConstants.MediaState.UploadFail.value());
					}
					delDir = true;
				}
			} else if (SceneConstants.MediaType.VIDEO.getValue().equals(entity.getMediaType()) ||
					SceneConstants.MediaType.AUDIO.getValue().equals(entity.getMediaType())){
				// 音视频上传
				LiveUploadVideo liveUploadVideo = new LiveUploadVideo.Builder().description(entity.getDescription())
						.tags(entity.getTags()).templateGroupId(properties.getDomains().getMedia().getTemplateGroupId()).build();
				UploadVideoResponse response = liveClient.liveUploadToVoD().uploadLocalVideo(entity.getTitle(), filename, liveUploadVideo);
				if (response.isSuccess()) {
					//20200317 weiyan 转码回调函数根据videoId获取不到素材信息问题
//					try {
//						liveMultimediaService.getVideoMezzanineInfo(response.getVideoId(), updateEntity);
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
					File f = new File(filename);
		            updateEntity.setMediaSize(MaterialUtils.getFileSize(f));
		            
					updateEntity.setState(SceneConstants.MediaState.Uploading.value());
					updateEntity.setMediaId(response.getVideoId());
					updateEntity.setRequestId(response.getRequestId());
					updateEntity.setLastUpdateDate(new Date());
					delDir = true;
				}
			}
		}
		//20200317 weiyan 转码回调函数根据videoId获取不到素材信息问题
		// 删除文件
		if (delDir) {
			try {
				Path file = Paths.get(filename);
				Files.delete(file);
				Files.delete(file.getParent());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		// 更新素材信息
		liveMultimediaService.updateById(updateEntity);
	}

	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;
	}
}
