package cn.com.ctop.job.kuaishou.handler;

import cn.com.ctop.common.module.entity.MaterialInfo;
import cn.com.ctop.common.module.entity.VideoWatermarkTask;
import cn.com.ctop.common.module.service.IMaterialInfoService;
import cn.com.ctop.common.module.service.IVideoWatermarkTaskService;
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 cn.com.ctop.common.module.utils.PropertiesUtils;
import com.aliyuncs.mts.model.v20140618.QueryJobListResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class WatermarkVideoJob {
    @Autowired
    private IVideoWatermarkTaskService videoWaterMarkService;
    @Autowired
    private IMaterialInfoService materialInfoService;

    // TODO 待删除
    @XxlJob("videoWatermarkJob")
    public void execute() throws Exception {
        QueryWrapper<VideoWatermarkTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("status", "Submitted", "Transcoding");
        List<VideoWatermarkTask> list = videoWaterMarkService.list(queryWrapper);
        if (list != null && !list.isEmpty()) {
            for (VideoWatermarkTask videoWatermarkTask : list) {
                QueryJobListResponse.Job job = MpsUtils.getJobStatus(videoWatermarkTask.getJobId());
                if ("TranscodeSuccess".equals(job.getState())) {
                    String url = "https://ctop-media.oss-cn-beijing.aliyuncs.com/" + job.getOutput().getOutputFile().getObject();
                    String localPath = LoadFileUtil.downLoadFromUrl(url, PropertiesUtils.getValue("kuaishou_config", "video_sava_path"));
                    LoadFileUtil.delFile(localPath);
                    QueryWrapper<MaterialInfo> materialInfoQueryWrapper = new QueryWrapper<>();
                    materialInfoQueryWrapper.eq("watermark_code", job.getJobId());
                    MaterialInfo materialInfo = materialInfoService.getOne(materialInfoQueryWrapper);
                    if (Check.isNull(materialInfo)) {
                        videoWaterMarkService.removeById(videoWatermarkTask.getId());
                        continue;
                    }
                    materialInfo.setWatermarkUrl(url);
                    materialInfoService.saveOrUpdate(materialInfo);
                    videoWatermarkTask.setVideoUrl(url);
                    videoWatermarkTask.setStatus(job.getState());
                    videoWatermarkTask.setVideoId(materialInfo.getId());
                    videoWaterMarkService.updateById(videoWatermarkTask);
                }
            }
        }
    }
}
