package cn.com.ctop.crawler.modules.oceanengine.service.impl;

import cn.com.ctop.common.module.utils.Base64Utils;
import cn.com.ctop.common.module.utils.HttpUtils2;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.crawler.modules.oceanengine.entity.DouyinHot;
import cn.com.ctop.crawler.modules.oceanengine.entity.EffectCase;
import cn.com.ctop.crawler.modules.oceanengine.entity.HotMaterial;
import cn.com.ctop.crawler.modules.oceanengine.mapper.EffectCaseMapper;
import cn.com.ctop.crawler.modules.oceanengine.service.IDouyinHotService;
import cn.com.ctop.crawler.modules.oceanengine.service.IEffectCaseService;
import cn.com.ctop.crawler.modules.oceanengine.service.IHotMaterialService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Service
@Primary

public class EffectCaseServiceImpl extends ServiceImpl<EffectCaseMapper, EffectCase> implements IEffectCaseService {
    @Autowired
    private IDouyinHotService douyinHotService;
    @Autowired
    private IHotMaterialService hotMaterialService;
    @Override
    public IPage<EffectCase> queryHotFeeds(String userName, String start, String end, String orderByColumn, String orderByType, Integer pageNo, Integer pageSize) {
        QueryWrapper<EffectCase> queryWrapper = new QueryWrapper<>();
        if (null != userName && !"".equals(userName)) {
            queryWrapper.like("author", "%" + userName + "%");
        }
        if (null != start && !"".equals(start) && null != end && !"".equals(end)) {
            queryWrapper.between("create_time", start, end);
        }
        if (null != orderByType && "desc".equals(orderByType)) {
            if("create_time".equals(orderByColumn)){
                queryWrapper.orderByAsc(orderByColumn);
            }else{
                queryWrapper.orderByDesc(orderByColumn);
            }
        } else {
            if("create_time".equals(orderByColumn)){
                queryWrapper.orderByDesc(orderByColumn);
            }else{
                queryWrapper.orderByAsc(orderByColumn);
            }
        }
        Page<EffectCase> page = new Page<>(pageNo, pageSize);
        return this.page(page, queryWrapper);
    }

    @Override
    public Map<String, Object> getVideoUrl(String id, Integer type) throws Exception {
        Map<String, Object> result = new HashMap<>();
        String url = null;
        String vid = null;
        if (null != type && type == 1) {
            //抖音热门
            DouyinHot douyinHot = douyinHotService.getById(id);
            vid = douyinHot.getVideoId();
        } else if (type == 2) {
            //效果案例
            EffectCase effectCase = this.getById(id);
            vid = effectCase.getVid();
        } else {
            //广告雷达
            HotMaterial hotMaterial = hotMaterialService.getById(id);
            vid = hotMaterial.getVid();
        }
        url = getRealVideoUrl("https://aweme.snssdk.com/aweme/v1/playwm/?video_id=" + vid + "&line=0");
        if (null == url || "".equals(url.trim())) {
            url = getVideoUrl(vid);
        }
        result.put("url", url);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    public static String getVideoUrl(String vid) throws Exception {
        String url = "http://i.snssdk.com/video/urls/1/toutiao/mp4/" + vid;
        String result = HttpUtils2.httpGetRequest(url);
        ObjectMapper mapper = new ObjectMapper();
        if (result != null) {
            JsonNode node = mapper.readTree(result);
            String mainUrl = node.get("data").get("video_list").get("video_1").get("main_url").asText();
            return Base64Utils.decode(mainUrl);
        }
        return null;
    }

    public static String getVideoUrlByVid(String vid) {
        String url = "https://aweme.snssdk.com/aweme/v1/playwm/?video_id=" + vid + "&line=0";
        return getRealVideoUrl(url);
    }

    public static String getRealVideoUrl(String url) {
        try {
            URL serverUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) serverUrl
                    .openConnection();
            conn.setRequestMethod("GET");
            // 必须设置false，否则会自动redirect到Location的地址
            conn.setInstanceFollowRedirects(false);
            conn.addRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.8) Firefox/3.6.8");
            conn.connect();
            String location = conn.getHeaderField("Location");
            return location;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
