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.ai.service.IKuaiShouVideoLastTimeService;
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.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

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

    @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, Integer channelType, String appVersion, Integer videoCnt) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("signature");
        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);
        }
        if (null != channelType && channelType != 2) {
            queryWrapper.eq("channel_type", channelType);
        }

        if (null != appVersion && !appVersion.trim().equals("")) {
            queryWrapper.likeRight("photo_name", appVersion);
        }
        if (null != videoCnt && videoCnt != 0) {
            queryWrapper.last("limit " + videoCnt);
        }
        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(String photoId) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("photo_id", photoId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public void etlVideoBaseInfoByStaDate(String statDate) {
        videoGetMapper.etlVideoBaseInfoByStaDate(statDate);
    }

    @Override
    public List<JSONObject> getVideoInfoAndImageList(List<JSONObject> materialList) {
        List<Long> photoIdList = new ArrayList();
        for (int i = 0; i < materialList.size(); i++) {
            JSONObject materialJson = materialList.get(i);
            photoIdList.add(materialJson.getLong("photo_id"));
        }
        Map<Long, JSONObject> materialMap = new HashMap<>();
        List<String> videoCodeList = new ArrayList<>();

        List<JSONObject> videoList = videoGetMapper.getVideoInfoByPhotoIds(photoIdList);
        Map<String, List<String>> imageMap = new HashMap<>();
        for (int i = 0; i < videoList.size(); i++) {
            JSONObject jsonObject = videoList.get(i);
            materialMap.put(jsonObject.getLong("photoId"), jsonObject);
            videoCodeList.add(jsonObject.getString("signature"));
            imageMap.put(jsonObject.getString("signature"), new ArrayList<>());
        }
        imageMap = this.getImageListByMd5(videoCodeList, imageMap);
        for (int i = 0; i < materialList.size(); i++) {
            JSONObject materialJson = materialList.get(i);
            Long photoId = materialJson.getLong("photo_id");
            JSONObject jsonObject = materialMap.get(photoId);
            if (Check.isNull(jsonObject)) {
                continue;
            }
            String signature = jsonObject.getString("signature");
            materialJson.put("signature", signature);
            materialJson.put("material_type", jsonObject.getInteger("materialType"));
            materialJson.put("channel_type", jsonObject.getString("channelType"));
            materialJson.put("photo_name", jsonObject.getString("photoName"));
            List<String> imageList = imageMap.get(signature);
            materialJson.put("imageList", imageList);
        }
        return materialList;
    }

    private Map<String, List<String>> getImageListByMd5(List<String> videoCodeList, Map<String, List<String>> imageMap) {
        List<JSONObject> imageList = lastTimeService.getImageListByMd5List(videoCodeList);
        for (int i = 0; i < imageList.size(); i++) {
            JSONObject jsonObject = imageList.get(i);
            if (Check.isNull(jsonObject)) {
                continue;
            }
            String video_signature = jsonObject.getString("video_signature");
            List<String> jsonObjects = imageMap.get(video_signature);
            jsonObjects.add(jsonObject.getString("signature"));
        }
        return imageMap;
    }

    @Override
    public List<KuaiShouVideoGet> getVideoInfoGroupBySignature(String date) {
        QueryWrapper<KuaiShouVideoGet> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("signature").likeRight("stat_date", date);
        queryWrapper.groupBy("signature");
        return this.list(queryWrapper);
    }

    @Override
    public Integer getTotalCountByAccount(Long accountId) {
        return videoGetMapper.getTotalCountByAccount(accountId);
    }

    @Override
    public Integer getTotalCountByAccountAndStatDate(Long accountId, String statDate) {
        return videoGetMapper.getTotalCountByAccountAndStatDate(accountId, statDate);
    }

    @Override
    public Integer getEffectiveCountByAccountId(Long accountId) {
        return videoGetMapper.getEffectiveCountByAccountId(accountId);
    }

    @Override
    public Integer getHotMoneyCountByAccountId(Long accountId) {
        return videoGetMapper.getHotMoneyCountByAccountId(accountId);
    }

    @Override
    public List<KuaiShouVideoGet> getZeroVideoByParams(Long accountId, String startTime, String endTime, Long videoCnt, String appVersion, Integer channelType, Integer relativeCnt) {
        return videoGetMapper.getZeroVideoByParams(accountId, startTime, endTime, videoCnt, appVersion, channelType, relativeCnt);
    }

    @Override
    public List<KuaiShouVideoGet> getHistoryTopVideoByParams(Long accountId, String startTime, String endTime, Long videoCnt, String appVersion, Integer channelType) {
        return videoGetMapper.getHistoryTopVideoByParams(accountId, startTime, endTime, videoCnt, appVersion, channelType);
    }

    /**
     * 素造接口，获取同步供应商素材标签数据
     */
    @Override
    public void getSuZaoList(String token, Long accountId, int page, String startDate) {
        String url = "https://ad.e.kuaishou.com/rest/openapi/v1/ad_creator/video/list";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token);
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("advertiser_id", accountId);
        param.put("page", page);
        param.put("page_size", 200);
        param.put("start_date", startDate);
        param.put("end_date", DateUtils.formatDate(new Date(), DateUtils.NEW_FORMAT));
        String result = HttpUtils.httpPostRequest(url, param, headers);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (Check.isNull(resultJson)) {
            return;
        }
        Integer code = resultJson.getInteger("code");
        String message = resultJson.getString("message");
        if (null == code || code != 0) {
            log.error("获取快手素造列表数据异常:{},accountId:{}", message, accountId);
            return;
        }
        JSONObject dataJson = resultJson.getJSONObject("data");
        if (Check.isNull(dataJson)) {
            return;
        }
        JSONArray details = dataJson.getJSONArray("details");
        if (Check.isNull(details)) {
            return;
        }
        List<KuaiShouVideoGet> videoGetList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            JSONObject detailJson = details.getJSONObject(i);
            if (Check.isNull(detailJson)) {
                continue;
            }
            KuaiShouVideoGet videoGet = new KuaiShouVideoGet();
            videoGet.setMaterialTag(detailJson.getString("material_tag"));
            videoGet.setSupplierAccountId(detailJson.getLong("supplier_account_id"));
            videoGet.setSupplierAccountName(detailJson.getString("supplier_account_name"));
            videoGet.setId(accountId + detailJson.getString("photo_id"));
            videoGetList.add(videoGet);
        }
        if (!Check.isNull(videoGetList)) {
            videoGetMapper.updateBatch(videoGetList);
        }
        getSuZaoList(token, accountId, page + 1, startDate);
    }

    @Override
    public List<JSONObject> getAccountIds() {
        return videoGetMapper.getAccountIds();
    }

    @Override
    public List<String> queryPhotoIdsByProjectAndMd5(Long projectId, String signature, JSONArray accountId) {
        return videoGetMapper.queryPhotoIdsByProjectAndMd5(projectId, signature, accountId);
    }

    @Override
    public JSONObject getVideoByPhotoIdAndAccountId(Long accountId, String photoId) {
        return videoGetMapper.getVideoByPhotoIdAndAccountId(accountId, photoId);
    }

    @Override
    public List<JSONObject> getVideoListByDate(Date startDate, Date endDate) {
        return videoGetMapper.getVideoListByDate(startDate, endDate);
    }

    @Override
    public List<String> getDateList() {
        return videoGetMapper.getDateList();
    }

    @Override
    public List<KuaiShouVideoGet> getVideoListByPhotoIds(JSONArray photoIds, Long accountId) {
        return videoGetMapper.getVideoListByPhotoIds(photoIds, accountId);
    }
}
