package com.platform.modules.qk.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.vod.model.v20170321.*;
import com.baomidou.mybatisplus.plugins.Page;
import com.platform.autoconfigure.live.LiveProperties;
import com.platform.common.annotation.SysLog;
import com.platform.common.utils.PageUtils;
import com.platform.common.utils.R;
import com.platform.modules.live.aspect.ClipsTenant;
import com.platform.modules.live.service.LiveMultimediaService;
import com.platform.modules.qk.entity.EditProjectEntity;
import com.platform.modules.qk.entity.EditProjectMaterialEntity;
import com.platform.modules.qk.service.VideoService;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.plugs.live.LiveClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;

@RestController
@RequestMapping(value = "api/clips")
@Api(value = "云剪辑",tags = "云剪辑")
public class AliyunClipsController extends AbstractController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private LiveClient liveClient;
    @Autowired
    private LiveMultimediaService liveMultimediaService;
    @Autowired
    private LiveProperties properties;

    /**
     * 查询转码模板组列表
     */
    @GetMapping("/listTemplateGroup")
    @SysLog("查询转码模板组列表")
    @ApiOperation(value = "查询转码模板组列表", notes = "查询转码模板组列表")
    @ApiImplicitParams({
    })
    public R listTranscodeTemplateGroup(ListTranscodeTemplateGroupRequest request ) {

        AcsResponse response = videoService.request(request);
        if(response == null  ){
            return R.error("查询转码模板组列表错误");
        }
        return R.ok().put("info",response);
    }
    /**
     * 查询转码模板组列表
     */
    @GetMapping("/InfoTemplateGroup")
    @SysLog("查询单一转码模板组详细配置")
    @ApiOperation(value = "查询单一转码模板组详细配置", notes = "查询单一转码模板组详细配置")
    @ApiImplicitParams({
            @ApiImplicitParam(name="transcodeTemplateGroupId",value="转码模板组ID",paramType="query",dataType="String",required = true)
    })
    public R infoTranscodeTemplateGroup(GetTranscodeTemplateGroupRequest  request ) {

        AcsResponse response = videoService.request(request);
        if(response == null  ){
            return R.error("查询单一转码模板组详细配置错误");
        }
        return R.ok().put("info",response);
    }

	/**
	 * 创建云剪辑项目
	 * @param request
	 * @return
	 */
	@PostMapping("/add")
	@SysLog("创建云剪辑")
    @ApiOperation(value = "创建云剪辑", notes = "创建云剪辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name="title",value="云剪辑工程标题",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="description",value="云剪辑工程描述",paramType="query",dataType="String"),
            @ApiImplicitParam(name="timeline",value="云剪辑工程时间线(JSON)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="coverURL",value="云剪辑工程封面",paramType="query",dataType="String")
    })
	public R add(AddEditingProjectRequest request) {
//        AddEditingProjectRequest request = new AddEditingProjectRequest();
//        request.setCoverURL(editingProject.getCoverURL());
//        request.setTitle(editingProject.getTitle());
//        request.setTimeline (editingProject.getTimeline());
//        request.setDescription (editingProject.getDescription());

        AddEditingProjectResponse response = videoService.addEditProject(request);
        if(response == null  ){
            return R.error("创建云剪辑错误");
        }
        EditProjectEntity vo = new EditProjectEntity();
        AddEditingProjectResponse.Project project = response.getProject();
        vo.setProjectId(project.getProjectId());
        if (getUser() != null)
            vo.setCreateUser(getUserId().intValue());
        vo.setCreateDate(new Date());
        vo.setTitle(project.getTitle());
        vo.setTimeline(request.getTimeline());
        vo.setDescription(project.getDescription());
        vo.setCoverUrl(request.getCoverURL());
        vo.setStatus("Normal");
        videoService.insertProject(vo);


        return R.ok().put("info",response);
	}
    /**
     * 创建云剪辑项目
     * @param request
     * @return
     */
    @PostMapping("/update")
    @SysLog("修改云剪辑")
    @ApiOperation(value = "修改云剪辑", notes = "修改云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑项目id",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="title",value="云剪辑工程标题",paramType="query",dataType="String"),
            @ApiImplicitParam(name="description",value="云剪辑工程描述",paramType="query",dataType="String"),
            @ApiImplicitParam(name="timeline",value="云剪辑工程时间线(JSON)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="coverURL",value="云剪辑工程封面",paramType="query",dataType="String")
    })
    @ClipsTenant
    public R update(UpdateEditingProjectRequest request) {// TODO
        UpdateEditingProjectResponse response = videoService.updateEditingProject(request);
        if(response == null  ){
            return R.error("修改云剪辑错误").put("info",response);
        }
        EditProjectEntity epe = videoService.findProjectByProjectId(request.getProjectId());
        if(epe != null ) {

            epe.setTitle(request.getTitle());
            epe.setDescription(request.getDescription());
            epe.setModifiedTime(new Date());
            epe.setCoverUrl(request.getCoverURL());
            videoService.updateProjectByProjectId(epe);
        }


        return R.ok();
    }

    /**
     * 获取云剪辑项目
     * @param request
     * @return
     */
    @GetMapping("/info")
    @SysLog("获取云剪辑")
    @ApiOperation(value = "获取云剪辑", notes = "获取云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID" ,paramType="query",dataType="String",required = true),
    })
    @ClipsTenant
    public R info(GetEditingProjectRequest request) {// TODO
       GetEditingProjectResponse response = videoService.getEditingProject(request);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("project_id", request.getProjectId());
        map.put("material_type", "4");
        List list = videoService.queryWatermarkList(map);
        if(response == null  ){
            return R.error("获取云剪辑错误").put("info",response);
        }
        return R.ok().put("info",response.getProject()).put("watermarkList",list);
    }

    /**
     * 删除云剪辑项目
     * @param request
     * @return
     */
    @GetMapping("/del")
    @SysLog("删除云剪辑")
    @ApiOperation(value = "删除云剪辑", notes = "删除云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectIds",value="云剪辑工程ID",paramType="query",dataType="String",required = true)
    })
    @ClipsTenant("projectIds")
    public R del(DeleteEditingProjectRequest request) {// TODO
        DeleteEditingProjectResponse response = videoService.deleteEditingProject(request);
        if(response == null && request.getProjectIds() == null  ){
            return R.error("删除云剪辑错误").put("info",response);
        }
        if(request.getProjectIds() != null ){
            String ids = request.getProjectIds();
            String[] idarr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList, idarr);

            videoService.deleteProjectByProjectIds(idList);
        }


        return R.ok();
    }
    /**
     * 创建云剪辑项目
     *
     * @return
     */
    @PostMapping("/updateLocal")
    @SysLog("本地保存云剪辑")
    @ApiOperation(value = "本地保存云剪辑", notes = "本地保存云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑项目id",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="title",value="云剪辑工程标题",paramType="query",dataType="String"),
            @ApiImplicitParam(name="description",value="云剪辑工程描述",paramType="query",dataType="String"),
            @ApiImplicitParam(name="timeline",value="云剪辑工程时间线(JSON)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="coverURL",value="云剪辑工程封面",paramType="query",dataType="String")
    })
    @ClipsTenant
    public R updateLocal(EditProjectEntity request) {// TODO
        String reMessage ="";
        try {
            if(request.getProjectId() == null){
                return R.error("修改云剪辑错误").put("errmessage","项目ID 不能为空");
            }else {
                EditProjectEntity  pvo = videoService.findProjectByProjectId(request.getProjectId());
                if(pvo == null ){
                    request.setStatus("Normal");
                    videoService.insertProject(request);
                }else{
                    request.setStatus(pvo.getStatus());
                    request.setMaterialId(pvo.getMaterialId());
                    videoService.updateProjectByProjectId(request);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("修改云剪辑错误").put("message",e.getMessage());
        }
        return R.ok();
    }
    /**
     * 获取云剪辑项目
     * @param
     * @return
     */
    @GetMapping("/infoLocal")
    @SysLog("获取本地云剪辑")
    @ApiOperation(value = "获取本地云剪辑", notes = "获取本地云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID" ,paramType="query",dataType="String",required = true),
    })
    @ClipsTenant
    public R infoLocal(String projectId) {// TODO
        EditProjectEntity vo = videoService.findProjectByProjectId(projectId);

        return R.ok().put("info",vo);
    }
    /**
     * 搜索云剪辑项目
     * @param request
     * @return
     */
    @GetMapping("/search")
    @SysLog("搜索云剪辑")
    @ApiOperation(value = "搜索云剪辑", notes = "搜索云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="startTime",value="CreationTime（创建时间）的开始时间。",paramType="query",dataType="String"),
            @ApiImplicitParam(name="endTime",value="CreationTime（创建时间）的结束时间。\n",paramType="query",dataType="String"),
            @ApiImplicitParam(name="status",value="云剪辑工程状态 ,Normal（草稿）\n" +
                    "Producing（合成中）\n" +
                    "Produced（合成成功）\n" +
                    "ProduceFailed（合成失败）",paramType="query",dataType="String"),
            @ApiImplicitParam(name="title",value="云剪辑工程标题",paramType="query",dataType="String"),
            @ApiImplicitParam(name="pageNo",value="页号",paramType="query",dataType="String"),
            @ApiImplicitParam(name="pageSize",value="分页大小",paramType="query",dataType="String"),
            @ApiImplicitParam(name="sortBy",value="创建时间排序(Desc，Asc)",paramType="query",dataType="String"),
    })
    public R search(SearchEditingProjectRequest request) {// TODO
        if(request.getPageNo()==null ||request.getPageNo() <=0 ){
            request.setPageNo(1);
        }
        if(request.getPageSize()==null ){
            request.setPageSize(10);
        }
        SearchEditingProjectResponse response = videoService.searchEditingProject(request);
        if(response == null  ){
            return R.error("搜索云剪辑错误").put("info",response);
        }

         List<SearchEditingProjectResponse.Project> list = response.getProjectList();



//        PageUtils page = new PageUtils(null,0, request.getPageSize(), request.getPageNo());
//        if(response.getProjectList() != null) {
            PageUtils page = new PageUtils(response.getProjectList(), response.getTotal()==null?0:response.getTotal(), request.getPageSize(), request.getPageNo());
//        }
        return R.ok().put("page",page);
    }
    /**
     * 搜索云剪辑项目
     * @param request
     * @return
     */
    @GetMapping("/searchNew")
    @SysLog("搜索云剪辑")
    @ApiOperation(value = "搜索云剪辑", notes = "搜索云剪辑",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="startTime",value="CreationTime（创建时间）的开始时间。",paramType="query",dataType="String"),
            @ApiImplicitParam(name="endTime",value="CreationTime（创建时间）的结束时间。\n",paramType="query",dataType="String"),
            @ApiImplicitParam(name="status",value="云剪辑工程状态 ,Normal（草稿）\n" +
                    "Producing（合成中）\n" +
                    "Produced（合成成功）\n" +
                    "ProduceFailed（合成失败）",paramType="query",dataType="String"),
            @ApiImplicitParam(name="title",value="云剪辑工程标题",paramType="query",dataType="String"),
            @ApiImplicitParam(name="pageNo",value="页号",paramType="query",dataType="String"),
            @ApiImplicitParam(name="pageSize",value="分页大小",paramType="query",dataType="String"),
            @ApiImplicitParam(name="sortBy",value="创建时间排序(Desc，Asc)",paramType="query",dataType="String")
    })
    public R searchNew(SearchEditingProjectRequest request) {
        if(request.getPageNo()==null ||request.getPageNo() <=0 ){
            request.setPageNo(1);
        }
        if(request.getPageSize()==null ){
            request.setPageSize(10);
        }
        Map<String, Object> map = new HashMap<>();

        map.put("status",request.getStatus());
        map.put("title",request.getTitle());
        map.put("page",request.getPageNo());
        map.put("limit",request.getPageSize());
        SysUserEntity user = getUser();
        if (user != null || user.getTenantId() != null || user.getTenantId() > 0)
            map.put("tenantId", user.getTenantId());
       // List list = videoService.queryProjectListByMap(map);
       Page<Map> page1 =videoService.queryProjectPageByMap(map);



//        PageUtils page = new PageUtils(null, 0, request.getPageSize(), 1);
//        if(list != null) {
//             page = new PageUtils(list, list.size(), request.getPageSize(), request.getPageNo());
//        }
//            return R.ok().put("page",page);
        return R.ok().put("page",page1);

    }

    /**
     * 设置云剪辑工程素材
     * @param request
     * @return
     */
    //@Login
    @GetMapping("/materials/add")
    @SysLog("设置云剪辑工程素材")
    @ApiOperation(value = "设置云剪辑工程素材", notes = "设置云剪辑工程素材",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="materialIds",value="云剪辑素材ID",paramType="query",dataType="String",required = true),
    })
    @ClipsTenant
    public R addMaterials(SetEditingProjectMaterialsRequest request) {// TODO
        SetEditingProjectMaterialsResponse response = videoService.setEditingProjectMaterials(request);

        if(response == null  ){
            return R.error("设置云剪辑工程素材错误").put("info",response);
        }
        return R.ok();
    }

    /**
     * 设置云剪辑工程图片素材
     * @param projectId
     * @param materialType
     * @param materialIds
     * @return
     */
    //@Login
    @PostMapping("/materials/addNew")
    @SysLog("设置云剪辑工程图片素材")
    @ApiOperation(value = "设置云剪辑工程图片素材", notes = "设置云剪辑工程图片素材",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="materialType",value="云剪辑图片素材类型,用逗号分割( 1视频 2语音 3图片 4水印 5..)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="materialIds",value="云剪辑图片素材ID,用逗号分割",paramType="query",dataType="String")
    })
    @ClipsTenant
    public R addImageMaterials(String projectId,String materialIds ,String materialType) {// TODO
//        EditProjectMaterialEntity response = videoService.setEditingProjectMaterials(request);
    if(StringUtils.isBlank(projectId) ){
        return R.error("设置图片云剪辑工程素材错误")
                .put("info", "projectId("+projectId+") or materialIds("+materialIds+") is null");
    }
    List<EditProjectMaterialEntity> list = new ArrayList<EditProjectMaterialEntity>();
       //String materialIds = request.getMaterialIds();
       //String projectId = request.getProjectId();
       if(projectId != null) {

           if (materialIds != null ) {
               String[] mlist = materialIds.split(",");
               String[] typeList = {};
               if(materialType != null){
                   if(materialType.indexOf(",") != -1 ) {
                       typeList = materialType.split(",");
                   }else{
                       typeList = new String[1];
                       typeList[0] = materialType;
                   }
               }

               int i = 0;
               for (i = 0; i < mlist.length; i++) {
                   EditProjectMaterialEntity entity = new EditProjectMaterialEntity();
                   entity.setMaterialId(mlist[i]);
                   if(typeList != null && i < typeList.length ) {
                       entity.setMaterialType(typeList[i]);
                   }
                   entity.setProjectId(projectId);
                   SysUserEntity user = getUser();
                   if(user != null) {
                       entity.setCreateUser(user.getUserId().intValue());
                   }
                  // entity.setCreateDate(new Date());
                   list.add(entity);
               }
           }

           try {
               Map<String, Object> map = new HashMap<String, Object>();
               map.put("project_id", projectId);
               videoService.deleteByMap(map);
               if (list.size() > 0) {
                   videoService.insertBatch(list);
               }
           } catch (Exception e) {
               e.printStackTrace();
               return R.error("设置图片云剪辑工程素材错误").put("info", e.getMessage());
           }
       }else{
           return R.error("设置图片云剪辑工程素材错误").put("info","项目ID不能为空");
       }

        return R.ok();
    }
    /**
     * 获取云剪辑工程图片素材列表
     * @param projectId
     * @param materialType
     * @return
     */
    //@Login
    @GetMapping("/materials/getNew")
    @SysLog("获取云剪辑工程图片素材列表")
    @ApiOperation(value = "获取云剪辑工程图片素材列表", notes = "获取云剪辑工程图片素材列表",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="materialType",value="云剪辑图片素材类型( 1视频 2语音 3图片 4水印 5..)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="pageNo",value="页号",paramType="query",dataType="String"),
            @ApiImplicitParam(name="pageSize",value="分页大小",paramType="query",dataType="String")
    })
    @ClipsTenant
    public R getImageMaterials(String projectId,String materialType,String pageNo,String pageSize) {// TODO



        List<EditProjectMaterialEntity> list = new ArrayList<EditProjectMaterialEntity>();
        //String projectId = request.getProjectId();
        if(projectId != null) {

            try {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("project_id", projectId);
                map.put("material_type", materialType);
                map.put("page",StringUtils.defaultIfBlank(pageNo,"1"));
                map.put("limit",StringUtils.defaultIfBlank(pageSize,"10"));
              //  map.put("is_delete", "0");
                List<HashMap> page= videoService.queryList(map);


                return R.ok().put("list",page);
            } catch (Exception e) {
                e.printStackTrace();
                return R.error("获取云剪辑工程图片素材列表").put("info", e.getMessage());
            }
        }
        return R.error("获取云剪辑工程图片素材列表").put("info","项目ID不能为空");

    }
    /**GetEditingProjectMaterials
     * 获取云剪辑工程素材
     * @param request
     * @return
     */
    //@Login
    @GetMapping("/materials/get")
    @SysLog("获取云剪辑工程素材")
    @ApiOperation(value = "获取云剪辑工程素材", notes = "获取云剪辑工程素材",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID",paramType="query",dataType="String",required = true),
            @ApiImplicitParam(name="type",value="素材类型。取值范围：\n" +
                    "video（视频）\n" +
                    "audio（纯音频）",paramType="query",dataType="String")
    })
    @ClipsTenant
    public R getMaterials(GetEditingProjectMaterialsRequest request) {// TODO
        GetEditingProjectMaterialsResponse response = videoService.getEditingProjectMaterials(request);
        if(response == null  ){
            return R.error("获取云剪辑工程素材错误").put("info",response);
        }
//        List<GetEditingProjectMaterialsResponse.Material> list =  response.getMaterialList();
//        for (GetEditingProjectMaterialsResponse.Material material:  list) {
//
//        }

        return R.ok().put("list",response.getMaterialList());
    }

//    /**
//     * 设置视频水印
//     * @param request
//     * @return
//     */
//    //@Login
//    @GetMapping("/watermark/add")
//    @SysLog("设置视频水印")
//    @ApiOperation(value = "设置视频水印", notes = "设置视频水印",produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="name",value="水印名称",paramType="query",dataType="String",required = true),
//            @ApiImplicitParam(name="type",value="水印类型",paramType="query",dataType="String",required = true),
//            @ApiImplicitParam(name="watermarkConfig",value="水印显示位置、效果等配置",paramType="query",dataType="String",required = true),
//            @ApiImplicitParam(name="fileUrl",value="水印文件oss地址。",paramType="query",dataType="String",required = true)
//    })
//    public R addWatermark(AddWatermarkRequest request) {
//        AddWatermarkResponse response = videoService.setAddWatermarkRequest(request);
//        if(response == null  ){
//            return R.error("设置视频水印错误");
//        }
//        return R.ok().put("info",response);
//    }
//    /**
//     * 删除视频水印
//     * @param request
//     * @return
//     */
//    //@Login
//    @GetMapping("/watermark/del")
//    @SysLog("删除视频水印")
//    @ApiOperation(value = "删除视频水印", notes = "删除视频水印",produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="watermarkId",value="视频水印ID",paramType="query",dataType="String",required = true)
//    })
//    public R delWatermark(DeleteWatermarkRequest request) {
//        AcsResponse response = videoService.request(request);
//        if(response == null  ){
//            return R.error("删除视频水印错误");
//        }
//        return R.ok().put("info",response);
//    }
//    /**
//     * 获取视频水印
//     * @param request
//     * @return
//     */
//    //@Login
//    @GetMapping("/watermark/get")
//    @SysLog("获取视频水印")
//    @ApiOperation(value = "获取视频水印", notes = "获取视频水印",produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="watermarkId",value="视频水印ID",paramType="query",dataType="String",required = true)
//    })
//    public R getWatermark(GetWatermarkRequest request) {
//        AcsResponse response = videoService.request(request);
//        if(response == null  ){
//            return R.error("获取视频水印错误");
//        }
//        return R.ok().put("info",response);
//    }
//    /**
//     * 获取视频水印列表
//     * @param request
//     * @return
//     */
//    //@Login
//    @GetMapping("/watermark/list")
//    @SysLog("获取视频水印列表")
//    @ApiOperation(value = "获取视频水印列表", notes = "获取视频水印列表",produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//    })
//    public R listWatermark(ListWatermarkRequest request) {
//        AcsResponse response = videoService.request(request);
//        if(response == null  ){
//            return R.error("获取视频水印列表错误");
//        }
//        return R.ok().put("info",response);
//    }
//    /**
//     * 设置缺省视频水印
//     * @param request
//     * @return
//     */
//    //@Login
//    @GetMapping("/watermark/setDefault")
//    @SysLog("设置缺省视频水印")
//    @ApiOperation(value = "设置缺省视频水印", notes = "设置缺省视频水印",produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="watermarkId",value="视频水印ID",paramType="query",dataType="String",required = true)
//    })
//    public R getWatermark(SetDefaultWatermarkRequest request) {
//        AcsResponse response = videoService.request(request);
//        if(response == null  ){
//            return R.error("设置缺省视频水印错误");
//        }
//        return R.ok().put("info",response);
//    }
//    /**
//     * 修改视频水印
//     * @param request
//     * @return
//     */
//    //@Login
//    @GetMapping("/watermark/upd")
//    @SysLog("修改视频水印")
//    @ApiOperation(value = "修改视频水印", notes = "修改视频水印",produces = MediaType.APPLICATION_JSON_VALUE)
//    @ApiImplicitParams({
//            @ApiImplicitParam(name="watermarkId",value="视频水印ID",paramType="query",dataType="String",required = true),
//            @ApiImplicitParam(name="name",value="水印名称",paramType="query",dataType="String",required = true),
//            @ApiImplicitParam(name="watermarkConfig",value="水印显示位置、效果等配置",paramType="query",dataType="String",required = true),
//    })
//    public R updWatermark(UpdateWatermarkRequest request) {
//        AcsResponse response = videoService.request(request);
//        if(response == null  ){
//            return R.error("修改视频水印错误");
//        }
//        return R.ok().put("info",response);
//    }
    /**ProduceEditingProjectVideo
     * 视频合成
     * @param request
     * @return
     */
    //@Login
//    @GetMapping("/produce")
    @RequestMapping(value ="/produce", method = {RequestMethod.POST,RequestMethod.GET})
    @SysLog("视频合成")
    @ApiOperation(value = "视频合成", notes = "视频合成",produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name="projectId",value="云剪辑工程ID",paramType="query",dataType="String"),
            @ApiImplicitParam(name="title",value="云剪辑工程标题",paramType="query",dataType="String"),
            @ApiImplicitParam(name="description",value="云剪辑工程描述",paramType="query",dataType="String"),
            @ApiImplicitParam(name="timeline",value="云剪辑工程时间线(JSON)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="coverURL",value="云剪辑工程封面",paramType="query",dataType="String"),
            @ApiImplicitParam(name="mediaMetadata",value="合成视频的元数据(JSON)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="produceConfig",value="合成配置(JSON)",paramType="query",dataType="String"),
            @ApiImplicitParam(name="userData",value="自定义设置(JSON)支持消息回调等设置。",paramType="query",dataType="String"),
            @ApiImplicitParam(name="watermarkId",value="水印素材ID",paramType="query",dataType="String")
    })
    @ClipsTenant
    public R produce(ProduceEditingProjectVideoRequest request,String watermarkId) {// TODO
            if(request.getProjectId() == null){
                return R.error("生成云剪辑错误").put("errmessage","项目ID 不能为空");
            }
            ProduceEditingProjectVideoResponse response = videoService.produceEditingProjectVideo(request);
            if(response == null  ){
                return R.error("视频合成错误").put("info",response);
            }
            String mid = response.getMediaId();
            String reMessage = "";
            try {

                EditProjectEntity pvo = videoService.findProjectByProjectId(request.getProjectId());

                if (pvo == null) {//异常。
                    pvo = new EditProjectEntity();
                    pvo.setTimeline(request.getTimeline());
                    pvo.setDescription(request.getDescription());
                    pvo.setCoverUrl(request.getCoverURL());
                }
               String mediaMetadata  = request.getMediaMetadata();
                try {
                    JSONObject jsonobj = JSONObject.parseObject(mediaMetadata);

                    pvo.setTitle(StringUtils.defaultIfBlank(jsonobj.getString("Title"),request.getDescription()));
                    pvo.setDescription(StringUtils.defaultIfBlank(jsonobj.getString("Description"),request.getDescription()));

                }catch(Exception e){

                }

                pvo.setDelete(0);
                pvo.setId(null);
                pvo.setCreateUser((getUser()!=null?getUser().getUserId().intValue():null));
                pvo.setProjectId(new Date().getTime()+"");
                pvo.setMaterialId(mid);
                pvo.setStatus("Producing");
                videoService.insertProject(pvo);
            } catch (Exception e) {
                e.printStackTrace();
                return R.error("生成云剪辑错误").put("message", e.getMessage());
            }

//        if(!StringUtils.isBlank(watermarkId)) {
//            videoService.deleteWatermarkByProjectId(response.getProjectId());
//
//            EditProjectWatermarkEntity entity = new EditProjectWatermarkEntity();
//            entity.setProjectId(response.getProjectId());
//            entity.setMaterialType("4");
//            entity.setMaterialId(watermarkId);
//            videoService.insertWatermark(entity);
//        }

        return R.ok().put("info",response).put("watermarkId",watermarkId);
    }

	//判断整数（int）
	private boolean isInteger(String str) {
		if (null == str || "".equals(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("^[+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	//判断浮点数（double和float）
	private boolean isDouble(String str) {
		if (null == str || "".equals(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("^[+]?[\\d]*[.\\d]*$");
		return pattern.matcher(str).matches();
	}

	private boolean isURL(String strUrl) {
		if(!strUrl.startsWith("http://") && !strUrl.startsWith("https://")){
			return false;
		}
		int counts = 0;
		boolean flag =  false;
		while (counts < 5) {
		   try {
			   	URL url  = new URL(strUrl);
			   	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			   	if (connection.getResponseCode() == 200) {
				   flag = true;
			    }
		    	break;
		   	} catch (Exception ex) {
			   continue;
		   	}
		}
		return flag;
	}

	@GetMapping("/templateList")
    @ApiOperation(value = "获取转码模板列表", notes = "获取转码模板列表")
    public R getTemplateList(){

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

        return R.ok().put("list", templates);
    }
}
