package cn.com.poc.thirdparty.resource.tianju.api;


import cn.com.poc.common.constant.CommonConstant;
import cn.com.poc.common.utils.http.LocalHttpClient;
import cn.com.poc.thirdparty.resource.tianju.api.constant.TianNewsChannelEnum;
import cn.com.poc.thirdparty.resource.tianju.api.entity.*;
import cn.com.yict.framemax.core.exception.BusinessException;
import cn.com.yict.framemax.frame.service.FmxParamConfigService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: Zackery
 * @Description: 天聚API
 * @Date: 2024/4/16 10:49
 */
@Service
public class TianApi implements TianBaseApi {

    private Logger logger = LoggerFactory.getLogger(TianApi.class);

    @Resource
    private FmxParamConfigService paramConfigService;

    /**
     * 获取百度热搜榜
     */
    public TianCommonResult<TianBaiduTopSearch> getBaiduTopSearch() {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = BAIDU_TOP_SEARCH + "?" + KEY + "=" + encodeKey;
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianBaiduTopSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚百度热搜榜数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取头条热搜榜
     */
    public TianCommonResult<TianToutiaoTopSearch> getToutiaoTopSearch() {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = TOUTIAO_TOP_SEARCH + "?" + KEY + "=" + encodeKey;
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianToutiaoTopSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚头条热搜榜数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取抖音热搜榜
     */
    public TianCommonResult<TianDouyinTopSearch> getDouyinTopSearch() {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = DOUYIN_TOP_SEARCH + "?" + KEY + "=" + encodeKey;
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianDouyinTopSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚抖音热搜榜数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取微博热搜榜
     */
    public TianCommonResult<TianWeiboTopSearch> getWeiboTopSearch() {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = WEIBO_TOP_SEARCH + "?" + KEY + "=" + encodeKey;
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianWeiboTopSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚微博热搜榜数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取全网热搜榜
     */
    public TianCommonResult<TianNetworkTopSearch> getNetworkTopSearch() throws Exception {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = NETWORK_TOP_SEARCH + "?" + KEY + "=" + encodeKey;
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianNetworkTopSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚全网热搜榜数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取微信热搜榜
     */
    public TianCommonResult<TianWxTopSearch> getWxTopSearch() throws Exception {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = WX_TOP_SEARCH + "?" + KEY + "=" + encodeKey;
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianWxTopSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚微信热搜榜数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取微信精选
     */
    public TianResult<TianWxNewSearch> getWxNewSearch(TianWxNewRequest wxNewRequest) throws Exception {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeNum = URLEncoder.encode(String.valueOf(wxNewRequest.getNum()), StandardCharsets.UTF_8.toString());
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = WX_NEW_SEARCH + "?" + KEY + "=" + encodeKey
                    + "&" + NUM + "=" + encodeNum;
            if (wxNewRequest.getWord() != null) {
                String encodeWord = URLEncoder.encode(wxNewRequest.getWord(), StandardCharsets.UTF_8.toString());
                url = url + "&" + WORD + "=" + encodeWord;
            }
            if (wxNewRequest.getPage() != null) {
                String encodePage = URLEncoder.encode(String.valueOf(wxNewRequest.getPage()), StandardCharsets.UTF_8.toString());
                url = url + "&" + PAGE + "=" + encodePage;
            }
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            TianCommonResult<TianWxNewSearch> tianCommonResult = JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianWxNewSearch>>() {
            });
            TianResult<TianWxNewSearch> tianResult = new TianResult<>();
            tianResult.setList(tianCommonResult.getResult().getList());
            tianResult.setCurpage(tianCommonResult.getResult().getCurpage());
            tianResult.setAllnum(tianCommonResult.getResult().getAllnum());
            return tianResult;
        } catch (Exception e) {
            logger.info("调用天聚微信精选数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取新闻分类
     */
    public TianCommonResult<TianNewsSortSearch> getNewsSortSearch(TianNewsSortRequest newsSortRequest) throws Exception {
        String url = null;
        try {
            String key = paramConfigService.getParam(KEY_SITE);
            String encodeNum = URLEncoder.encode(String.valueOf(newsSortRequest.getNum()), StandardCharsets.UTF_8.toString());
            String encodeCol = URLEncoder.encode(String.valueOf(newsSortRequest.getCol()), StandardCharsets.UTF_8.toString());
            String encodeKey = URLEncoder.encode(key, StandardCharsets.UTF_8.toString());
            url = ALLNEWS_SEARCH + "?" + KEY + "=" + encodeKey
                    + "&" + NUM + "=" + encodeNum
                    + "&" + COL + "=" + encodeCol;
            if (newsSortRequest.getRand() != null) {
                String encodeRand = URLEncoder.encode(String.valueOf(newsSortRequest.getRand()), StandardCharsets.UTF_8.toString());
                url = url + "&" + RAND + "=" + encodeRand;
            }
            if (newsSortRequest.getWord() != null) {
                String encodeWord = URLEncoder.encode(newsSortRequest.getWord(), StandardCharsets.UTF_8.toString());
                url = url + "&" + WORD + "=" + encodeWord;
            }
            if (newsSortRequest.getPage() != null) {
                String encodePage = URLEncoder.encode(String.valueOf(newsSortRequest.getPage()), StandardCharsets.UTF_8.toString());
                url = url + "&" + PAGE + "=" + encodePage;
            }
            HttpUriRequest httpUriRequest = RequestBuilder.post()
                    .setUri(url)
                    .addHeader(urlencodedHeader)
                    .build();
            CloseableHttpResponse httpResponse = LocalHttpClient.execute(httpUriRequest);
            String responseStr = EntityUtils.toString(httpResponse.getEntity());
            return JSON.parseObject(responseStr, new TypeReference<TianCommonResult<TianNewsSortSearch>>() {
            });
        } catch (Exception e) {
            logger.info("调用天聚新闻分类数据异常，请求路径:{}", url);
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 获取新闻频道分类
     */
    public TianResult<TianNewsChannel> getNewsSortChannel() throws Exception {

        try {
            //新闻频道分类数据
            TianResult<TianNewsChannel> tianResult = new TianResult<>();
            List<TianNewsChannel> channels = new ArrayList<>();
            for (TianNewsChannelEnum value : TianNewsChannelEnum.values()) {
                if (CommonConstant.YOrN.Y.equals(value.getIsShow())) {
                    channels.add(new TianNewsChannel(value.getId(), value.getNewType()));
                }
            }
            tianResult.setList(channels);
            return tianResult;
        } catch (Exception e) {
            logger.info("调用天聚新闻频道分类数据异常");
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }

    /**
     * 根据频道ID获取新闻分类数据
     */
    public TianResult<TianNewsSortSearch> getNewsSortChannelSearch(TianNewsSortRequest newsSortRequest) throws Exception {
        try {
            TianResult<TianNewsSortSearch> tianResult = new TianResult<>();
            TianCommonResult<TianNewsSortSearch> newsSortSearch = getNewsSortSearch(newsSortRequest);
            tianResult.setList(newsSortSearch.getResult().getNewslist());
            tianResult.setAllnum(newsSortSearch.getResult().getAllnum());
            tianResult.setCurpage(newsSortSearch.getResult().getCurpage());
            return tianResult;
        } catch (Exception e) {
            logger.info("根据ID调用天聚新闻频道数据异常");
            throw new BusinessException("采集数据异常，请联系开发人员");
        }
    }
}
