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

import cn.com.ctop.common.module.constant.OssConstant;
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.LoadFileUtil;
import cn.com.ctop.common.module.utils.MpsUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.mts.model.v20140618.QuerySnapshotJobListRequest;
import com.aliyuncs.mts.model.v20140618.QuerySnapshotJobListResponse;
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.List;


/**
 * 截屏
 *
 * @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;

    /**
     * 获取素材关键帧
     *
     * @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);


            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 void loadCutFrame(String jobId, String videoSignature) {
        try {
            DefaultProfile profile = DefaultProfile.getProfile(
                    "cn-beijing",
                    "LTAIbNbqWzSOklQV",
                    "1rkPz7JNoXk8sJevPaeYHWqfkQXBGh");
            IAcsClient client = new DefaultAcsClient(profile);

            QuerySnapshotJobListRequest request = new QuerySnapshotJobListRequest();
            request.setSnapshotJobIds(jobId);
            QuerySnapshotJobListResponse response = client.getAcsResponse(request);
            JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(response));
            if (jsonObject == null) {
                return;
            }
            JSONObject json = (JSONObject) jsonObject.getJSONArray("snapshotJobList").get(0);
            String state = json.getString("state");
            if (null == state || !"Success".equals(state)) {
                return;
            }
            String loadImage = "cutFrame/" + videoSignature + "/";

            Integer count = json.getInteger("count");
            for (int j = 1; j <= count; j++) {
                String urlStr = null;
                if (j < 10) {
                    urlStr = String.format(
                            OssConstant.formatUrl + loadImage + "output_0000" + j + ".jpg",
                            ossBucket,
                            ossLocation);
                } else if (j < 100) {
                    urlStr = String.format(
                            OssConstant.formatUrl + loadImage + "output_000" + j + ".jpg",
                            ossBucket,
                            ossLocation);
                } else if (j > 100) {
                    urlStr = String.format(
                            OssConstant.formatUrl + loadImage + "output_00" + j + ".jpg",
                            ossBucket,
                            ossLocation);
                }
                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(j);
                this.save(cutFrame);
                LoadFileUtil.delFile(cutFramePath);

            }

            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 List<MaterialCutFrame> getListByVideoSignature(String videoSignature) {
        return materialCutFrameMapper.getListByVideoSignature(videoSignature);
    }



}
