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

import cn.com.ctop.common.module.entity.MaterialCutFrame;
import cn.com.ctop.common.module.mapper.MaterialCutFrameMapper;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
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.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;


/**
 * 截屏
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-12-25
 */
@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";

    /**
     * 获取素材关键帧
     *
     * @param url
     */
    @Override
    public void getCutFrame(String url, String materialId, String height, String width) throws IOException {


        try {


            String zeroFrameUrl = url + "?x-oss-process=video/snapshot,t_00000,m_fast";

            // String localPath = LoadFileUtil.downLoadFromUrl(zeroFrameUrl, PropertiesUtils.getValue("kuaishou_config", "video_sava_path"));
            String localPath = LoadFileUtil.downLoadFromUrl(zeroFrameUrl, "D:\\tets1");
            String md5 = LoadFileUtil.getMD5(localPath);
            LoadFileUtil.delFile(localPath);

            MaterialCutFrame cutFrame = new MaterialCutFrame();
            cutFrame.setCode(md5);
            cutFrame.setUrl(zeroFrameUrl);
            cutFrame.setMaterialMd5(materialId);
            cutFrame.setCutFrameIndex(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);

            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
            snapshotConfig.put("Time", "3");
            // SnapshotConfig->Interval/Num
            snapshotConfig.put("Interval", "2");
            snapshotConfig.put("Num", "9");
            // 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);
            // call api
            SubmitSnapshotJobResponse response;

            response = client.getAcsResponse(request);

        /*    String requestId = response.getRequestId();
            String jobId = response.getSnapshotJob().getId();
*/
            for (int i = 0; i < 100; i++) {

                Thread.sleep(5 * 1000);
                QuerySnapshotJobListRequest request1 = new QuerySnapshotJobListRequest();
                request1.setSnapshotJobIds(response.getSnapshotJob().getId());
                QuerySnapshotJobListResponse response1 = client.getAcsResponse(request1);
                String s = JSON.toJSONString(response1);
                JSONObject jsonObject = JSONObject.parseObject(s);
                if (!Check.isNull(jsonObject)) {
                    JSONObject json = (JSONObject) jsonObject.getJSONArray("snapshotJobList").get(0);
                    String state = json.getString("state");
                    if ("Success".equals(state)) {
                        Integer count = json.getInteger("count");
                        for (int j = 1; j <= count; j++) {
                            String urlStr = "";
                            if (j < 10) {
                                urlStr = String.format(
                                        "https://%s.%s.aliyuncs.com/" + ossOutputObject1 + "output_0000" + j + ".jpg",
                                        ossBucket,
                                        ossLocation);
                            } else if (j >= 10 && j < 100) {
                                urlStr = String.format(
                                        "https://%s.%s.aliyuncs.com/" + ossOutputObject1 + "output_000" + j + ".jpg",
                                        ossBucket,
                                        ossLocation);
                            } else if (j > 100) {
                                urlStr = String.format(
                                        "https://%s.%s.aliyuncs.com/" + ossOutputObject1 + "output_00" + j + ".jpg",
                                        ossBucket,
                                        ossLocation);
                            }
                            String cutFramePath = LoadFileUtil.downLoadFromUrl(urlStr, "D:\\tets1");
                            String cutFrameMd5 = LoadFileUtil.getMD5(cutFramePath);
                            LoadFileUtil.delFile(cutFramePath);
                            cutFrame = new MaterialCutFrame();
                            cutFrame.setCode(cutFrameMd5);
                            cutFrame.setUrl(urlStr);
                            cutFrame.setMaterialMd5(materialId);
                            cutFrame.setCutFrameIndex(j);
                            this.save(cutFrame);
                        }

                        break;
                    }
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}
