package cn.com.ctop.kuaishou.modules.batch.service.impl;

import cn.com.ctop.common.module.entity.MaterialCutFrame;
import cn.com.ctop.common.module.service.IMaterialCutFrameService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.LoadFileUtil;
import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
import cn.com.ctop.kuaishou.modules.batch.entity.vo.KuaiShouVideoGetVo;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouVideoGetMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
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 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;

/**
 * @Description: 快手-获取视频接口
 * @Author: jeecg-boot
 * @Date: 2019-07-25
 * @Version: V1.0
 */
@Slf4j
@Service
public class KuaiShouVideoGetServiceImpl extends ServiceImpl<KuaiShouVideoGetMapper, KuaiShouVideoGet> implements IKuaiShouVideoGetService {
    @Autowired
    private KuaiShouVideoGetMapper videoGetMapper;
    @Autowired
    private IMaterialCutFrameService materialCutFrameService;
    @Value("${oss.replace.download}")
    private String downloadUrl;

    @Override
    public void replaceBatch(List<KuaiShouVideoGet> videoGets) {
        videoGetMapper.replaceBatch(videoGets);
    }

    /**
     * 获取关键帧
     *
     * @param
     */
    @Override
    public synchronized void getKeyFrame(String token, Long accountId, String videoMd5, String photoId) {
        try {
            if (Check.isNull(videoMd5)) {
                return;
            }
            QueryWrapper<MaterialCutFrame> cutFrameQueryWrapper = new QueryWrapper<>();
            cutFrameQueryWrapper.eq("video_signature", videoMd5);
            cutFrameQueryWrapper.last("limit 1");
            MaterialCutFrame one = materialCutFrameService.getOne(cutFrameQueryWrapper);
            if (!Check.isNull(one)) {
                return;
            }
            log.info("开始视频抽帧,md5:{}", videoMd5);
            String url = "https://ad.e.kuaishou.com/rest/openapi/v1/tool/key_frame";
            JSONArray photoArr = new JSONArray();
            photoArr.add(photoId);
            Map<String, String> headers = new HashMap<>();
            headers.put("Access-Token", token);
            headers.put("Content-Type", "application/json");
            JSONObject requestJson = new JSONObject();
            requestJson.put("advertiser_id", accountId);
            requestJson.put("photo_ids", photoArr);
            String result = HttpUtils.kuaiShouhttpPostRequest(url, requestJson.toJSONString(), headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!Check.isNull(resultJson)) {
                Integer code = resultJson.getInteger("code");
                if (code == 0) {
                    JSONArray dataArr = resultJson.getJSONArray("data");
                    if (!Check.isNull(dataArr)) {
                        for (int i = 0; i < dataArr.size(); i++) {
                            String imageUrl = dataArr.getString(i);
                            String localPath = LoadFileUtil.downLoadFromUrl(imageUrl, downloadUrl);
                            String md5 = null;
                            try {
                                md5 = LoadFileUtil.getMD5(localPath);
                            } catch (IOException e) {
                                e.printStackTrace();
                                continue;
                            }
                            Map<String, Object> deleteMap = new HashMap<>();
                            deleteMap.put("video_signature", videoMd5);
                            deleteMap.put("signature", md5);
                            materialCutFrameService.removeByMap(deleteMap);
                            MaterialCutFrame materialCutFrame = new MaterialCutFrame();
                            materialCutFrame.setImageIndex(i);
                            materialCutFrame.setVideoSignature(videoMd5);
                            materialCutFrame.setUrl(imageUrl);
                            materialCutFrame.setSignature(md5);
                            materialCutFrameService.save(materialCutFrame);
                            LoadFileUtil.delFile(localPath);
                        }
                    }
                }
            }


            // }

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

    }

    @Override
    public List<KuaiShouVideoGetVo> getVideoList(Map<String, Object> requestMap) {
        return videoGetMapper.getVideoList(requestMap);
    }

    @Override
    public List<KuaiShouVideoGet> getNewVideoByAccountId(Long accountId, Integer aiStatus) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        if (null != accountId && accountId != 0) {
            queryWrapper.eq("account_id", accountId);
        }
        queryWrapper.orderByDesc("stat_date");
        return this.list(queryWrapper);
    }


    @Override
    public List<KuaiShouVideoGet> getNewVideoDescDate(Long accountId, Integer newVideoCnt) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        if (null != accountId && accountId != 0) {
            queryWrapper.eq("account_id", accountId);
        }
        if (null != newVideoCnt && newVideoCnt > 0) {
            queryWrapper.orderByDesc("stat_date");
            queryWrapper.last("limit " + newVideoCnt);
        }
        return this.list(queryWrapper);
    }


    @Override
    public List<KuaiShouVideoGet> getNewVideoBetweenTime(Long accountId, String startTime, String endTime) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        if (null != accountId && accountId != 0) {
            queryWrapper.eq("account_id", accountId);
        }
        if (null != startTime && null != endTime) {
            queryWrapper.le("stat_date", endTime);
            queryWrapper.gt("stat_date", startTime);
        }
        return this.list(queryWrapper);
    }

    @Override
    public List<JSONObject> getVideoListByMap(Map<String, Object> requestMap) {
        return videoGetMapper.getVideoListByMap(requestMap);
    }


    @Override
    public List<KuaiShouVideoGet> selectPhotoIdsByAccountId(Long accountId) {
        return videoGetMapper.selectPhotoIdsByAccountId(accountId);
    }

    @Override
    public KuaiShouVideoGet getVideoByPhotoId(Long photo_id) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("photo_id", photo_id);
        queryWrapper.last("limit 1");
        KuaiShouVideoGet videoGet = videoGetMapper.selectOne(queryWrapper);
        return videoGet;
    }

}
