package com.xxl.job.executor.common.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.executor.common.entity.MaterialCutFrame;
import com.xxl.job.executor.common.entity.MaterialCutFrameTask;
import com.xxl.job.executor.common.mapper.MaterialCutFrameMapper;
import com.xxl.job.executor.common.service.IMaterialCutFrameService;
import com.xxl.job.executor.common.service.IMaterialCutFrameTaskService;
import com.xxl.job.executor.utils.Check;
import com.xxl.job.executor.utils.CloudVideoProcessUtil;
import com.xxl.job.executor.utils.CosUtil;
import com.xxl.job.executor.utils.LoadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 截屏
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-12-25
 */
@Slf4j
@Service
public class MaterialCutFrameServiceImpl extends ServiceImpl<MaterialCutFrameMapper, MaterialCutFrame> implements IMaterialCutFrameService {

    private static String ossLocation = "oss-cn-beijing";
    private static String ossBucket = "ctop-media";
    private static String ossOutputObject = "output_{Count}.jpg";

    @Value("${jeecg.path.image-upload}")
    private String imageUpLoadPath;


    @Autowired
    private IMaterialCutFrameTaskService cutFrameTaskService;
    @Autowired
    private MaterialCutFrameMapper materialCutFrameMapper;

    @Override
    public List<MaterialCutFrame> getListByVideoSignature(String videoSignature) {
        return materialCutFrameMapper.getListByVideoSignature(videoSignature);
    }


    //腾讯云抽帧
    @Override
    public void getCosCutFrame(String url, String materialId) throws IOException {
        try {

            QueryWrapper<MaterialCutFrameTask> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("video_signature", materialId);
            queryWrapper.last("limit 1");
            MaterialCutFrameTask checkCutFrame = cutFrameTaskService.getOne(queryWrapper);
            if (!Check.isNull(checkCutFrame)) {
                log.info("已存推荐封面");
                return;
            }

            //抽帧ossOutputObject1
            String ossOutputObject1 = "/cutFrame/" + materialId + "/_";
            String replaceUrl = url.replace("https://" + CosUtil.bucket + ".cos.ap-chongqing.myqcloud.com", "");  //地址
            String resp = CosUtil.processMedia(replaceUrl, ossOutputObject1);
            JSONObject respJson = JSONObject.parseObject(resp);
            String jobId = respJson.getString("TaskId"); //{"Response": {"TaskId": "2600000655-WorkflowTask-c0b385f27c4993437029b5da175542aet0","RequestId": "4c23ce23-087f-4d4b-b73b-907d77d6d78d" } }
            MaterialCutFrameTask cutFrameTask = new MaterialCutFrameTask();
            cutFrameTask.setJobStatus(0);
            cutFrameTask.setJobId(jobId);
            cutFrameTask.setCloud_type(2);
            cutFrameTask.setVideoSignature(materialId);
            cutFrameTaskService.save(cutFrameTask);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }


    //抽帧任务状态查询，如果完成则把抽帧入库
    @Override
    public void loadCosCutFrame(String jobId, String videoSignature) {
        try {
            String resp = CosUtil.describeTaskDetail(jobId);
            if (Check.isNull(resp)) {
                return;
            }

            JSONObject respJson = JSONObject.parseObject(resp);
            String status = respJson.getString("Status");

            if (!"FINISH".equals(status)) {
                return;
            }


            JSONArray resultSetArray = respJson.getJSONObject("WorkflowTask").getJSONArray("MediaProcessResultSet");
            if (Check.isNull(resultSetArray)) {
                return;
            }
            JSONObject resultSetObject = resultSetArray.getJSONObject(0);
            if (Check.isNull(resultSetObject)) {
                return;
            }
            JSONArray snapshotArray = resultSetObject.getJSONObject("SampleSnapshotTask").getJSONObject("Output").getJSONArray("ImagePathSet");

            if (Check.isNull(snapshotArray)) {
                return;
            }

            for (int i = 0; i < snapshotArray.size(); i++) {
                String imagePath = snapshotArray.getString(i);
                String urlStr = "https://" + CosUtil.bucket + ".cos.ap-chongqing.myqcloud.com" + imagePath;

                //下载到本地获取图片md5
                String cutFramePath = LoadFileUtil.downLoadFromUrl(urlStr, imageUpLoadPath);
                String cutFrameMd5 = LoadFileUtil.getMD5(cutFramePath);

                MaterialCutFrame cutFrame = new MaterialCutFrame();
                cutFrame.setSignature(cutFrameMd5);
                cutFrame.setUrl(urlStr);
                cutFrame.setVideoSignature(videoSignature);
                cutFrame.setImageIndex(i);
                this.save(cutFrame);
            }

            QueryWrapper<MaterialCutFrameTask> updateQueryWrapper = new QueryWrapper<>();
            updateQueryWrapper.eq("job_id", jobId);
            updateQueryWrapper.eq("video_signature", videoSignature);
            MaterialCutFrameTask updateTask = new MaterialCutFrameTask();
            updateTask.setJobStatus(1);
            cutFrameTaskService.update(updateTask, updateQueryWrapper);
        } catch (Exception e) {
            log.error(e.getMessage());
        }

    }


    @Override
    public void getTencentCutFrame(String videoUrl, String materialId, String coveUrl) {
        try {

            if (Check.isNull(materialId)) {
                return;
            }
            String loadImage = "cutFrame/" + materialId + "/${Number}.jpg";
            QueryWrapper<MaterialCutFrame> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("video_signature", materialId);
            queryWrapper.last("limit 1");
            MaterialCutFrame checkMaterialCutFrame = this.getOne(queryWrapper);
            if (!Check.isNull(checkMaterialCutFrame)) {
                log.info("已存推荐封面");
                return;
            }
            // 添加首帧
            String coverCutFramePath = LoadFileUtil.downLoadFromUrl(coveUrl, imageUpLoadPath);
            String CutFrameMd5 = LoadFileUtil.getMD5(coverCutFramePath);
            MaterialCutFrame coveCutFrame = new MaterialCutFrame();
            coveCutFrame.setSignature(CutFrameMd5);
            coveCutFrame.setUrl(coveUrl);
            coveCutFrame.setVideoSignature(materialId);
            coveCutFrame.setImageIndex(0);
            this.save(coveCutFrame);
            LoadFileUtil.delFile(coverCutFramePath);
            // 请求从数据接口 获取其余14张截图
            getCut(materialId, videoUrl, loadImage, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void getCut(String materialId, String videoUrl, String loadImage, Integer count) {
        try {
            Map<String, Object> coverMap = CloudVideoProcessUtil.videoCutFrameHandle(videoUrl, loadImage);
            for (int i = 0; i <= 13; i++) {
                String url = (String) coverMap.get(String.valueOf(i));
                if (!Check.isNull(url)) {
                    String cutFramePath = LoadFileUtil.downLoadFromUrl(url, imageUpLoadPath);
                    String cutFrameMd5 = LoadFileUtil.getMD5(cutFramePath);
                    Map<String, Object> deleteMap = new HashMap<>();
                    deleteMap.put("video_signature", materialId);
                    deleteMap.put("signature", cutFrameMd5);
                    this.removeByMap(deleteMap);
                    MaterialCutFrame cutFrame = new MaterialCutFrame();
                    cutFrame.setSignature(cutFrameMd5);
                    cutFrame.setUrl(url);
                    cutFrame.setVideoSignature(materialId);
                    cutFrame.setImageIndex(i + 1);
                    this.save(cutFrame);
                    LoadFileUtil.delFile(cutFramePath);
                }
            }

        } catch (Exception e) {
            log.info("抽帧异常,code:{}", materialId);
            e.printStackTrace();
            if (count >= 4) {
                return;
            }
            getCut(materialId, videoUrl, loadImage, count + 1);

        }

    }

    @Override
    public boolean updateTencentCutFrame(String videoMD5) {
        boolean result = true;
        Map<String, Object> coverMap = CloudVideoProcessUtil.supplementFrameUrl(videoMD5);
        for (int i = 0; i <= 13; i++) {
            String url = (String) coverMap.get(String.valueOf(i));
            if (!Check.isNull(url)) {
                String cutFramePath = LoadFileUtil.downLoadFromUrl(url, imageUpLoadPath);
                String cutFrameMd5 = null;
                try {
                    cutFrameMd5 = LoadFileUtil.getMD5(cutFramePath);
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
                QueryWrapper<MaterialCutFrame> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("video_signature", videoMD5);
                queryWrapper.eq("image_index", i + 1);
                MaterialCutFrame cutFrame = new MaterialCutFrame();
                cutFrame.setSignature(cutFrameMd5);
                cutFrame.setUrl(url);
                result = this.update(cutFrame, queryWrapper);
                LoadFileUtil.delFile(cutFramePath);
            }
        }
        return result;
    }

    @Override
    public MaterialCutFrame getCutFrameByCode(String code) {
        QueryWrapper<MaterialCutFrame> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("video_signature", code);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public  List<JSONObject>  getProgramCreativeCover(String signature) {
        return materialCutFrameMapper.getProgramCreativeCover(signature);
    }


}
