package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.MaterialCutFrame;
import cn.com.ctop.common.module.entity.MaterialCutFrameTask;
import cn.com.ctop.common.module.mapper.MaterialCutFrameMapper;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.service.IMaterialCutFrameTaskService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CloudVideoProcessUtil;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.common.module.utils.MpsUtils;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobRequest;
import com.aliyuncs.mts.model.v20140618.SubmitSnapshotJobResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.net.URLEncoder;
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";

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


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

    /**
     * 获取素材关键帧
     *
     * @param url
     */
    @Override
    public void getCutFrame(String url, String materialId, Long secondDuration, String height, String width) 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;

            }

            String zeroFrameUrl = url + "?x-oss-process=video/snapshot,t_00000,m_fast";
            String localPath = LoadFileUtil.downLoadFromUrl(zeroFrameUrl, imageUpLoadPath);
            String md5 = LoadFileUtil.getMD5(localPath);
            LoadFileUtil.delFile(localPath);

            MaterialCutFrame cutFrame = new MaterialCutFrame();
            cutFrame.setSignature(md5);
            cutFrame.setUrl(zeroFrameUrl);
            cutFrame.setVideoSignature(materialId);
            cutFrame.setImageIndex(0);
            this.save(cutFrame);


            // DefaultAcsClient
            // 地域ID // RAM账号的AccessKey ID // RAM账号Access Key Secret
            String ossOutputObject1 = "cutFrame/" + materialId + "/";
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-beijing",
                    "LTAIbNbqWzSOklQV",
                    "1rkPz7JNoXk8sJevPaeYHWqfkQXBGh");
            IAcsClient client = new DefaultAcsClient(profile);
            // request
            SubmitSnapshotJobRequest request = new SubmitSnapshotJobRequest();
            // Input
            JSONObject input = new JSONObject();
            input.put("Location", ossLocation);
            input.put("Bucket", ossBucket);
            //   https://ctop-media.oss-cn-beijing.aliyuncs.com/video/2020-06-03/bp%E8%95%89%E4%B8%8B%E7%9B%B4%E6%92%AD2-1591188835505.mp4
            String replaceUrl = url.replace("https://ctop-media.oss-cn-beijing.aliyuncs.com/", "");
            input.put("Object", replaceUrl);

            request.setInput(input.toJSONString());


            // SnapshotConfig
            JSONObject snapshotConfig = new JSONObject();
            // SnapshotConfig->OutputFile
            JSONObject output = new JSONObject();
            output.put("Location", ossLocation);
            output.put("Bucket", ossBucket);


            String ossOutputObject = "output_{Count}.jpg";
            output.put("Object", URLEncoder.encode(ossOutputObject1 + ossOutputObject, "utf-8"));

            snapshotConfig.put("OutputFile", output.toJSONString());
            // SnapshotConfig->Time
            //   Integer time = ((secondDuration.intValue() - 2) / 14) + 1; // 时长 / 14 == 间隔时间

            double num = (double) (secondDuration - 2) / 15;
            long rint = Math.round(num);
            log.info("相隔时间数：{}", rint);
            snapshotConfig.put("Time", 2000);
            // SnapshotConfig->Interval/Num
            snapshotConfig.put("Interval", rint);
            snapshotConfig.put("Num", "14");
            // SnapshotConfig->Width/Height
            snapshotConfig.put("Height", height);
            snapshotConfig.put("Width", width);
            // SnapshotConfig
            request.setSnapshotConfig(snapshotConfig.toJSONString());
            // PipelineId
            String pipelineId = MpsUtils.getPipelineId(client);
            request.setPipelineId(pipelineId);
            SubmitSnapshotJobResponse response = client.getAcsResponse(request);
            String jobId = response.getSnapshotJob().getId();
            MaterialCutFrameTask cutFrameTask = new MaterialCutFrameTask();
            cutFrameTask.setJobStatus(0);
            cutFrameTask.setJobId(jobId);
            cutFrameTask.setVideoSignature(materialId);
            cutFrameTaskService.save(cutFrameTask);
        } catch (Exception e) {
            log.error(e.getMessage());
        }


    }

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

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

    @Override
    public MaterialCutFrame selectByMd5(String md5) {
        QueryWrapper<MaterialCutFrame> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("signature", md5);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);

    }

    @Override
    public JSONObject getCutFrameByVideoMd5(String photoId, String imageToken) {
        return materialCutFrameMapper.getCutFrameByVideoMd5(photoId, imageToken);
    }


}
