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

import cn.com.ctop.common.module.entity.IpPool;
import cn.com.ctop.common.module.service.IIpPoolService;
import cn.com.ctop.crawler.modules.account.entity.KuaishouAdAccount;
import cn.com.ctop.crawler.modules.account.entity.KuaishouAppAccount;
import cn.com.ctop.crawler.modules.account.entity.KuaishouIosAccount;
import cn.com.ctop.crawler.modules.account.service.IKuaishouAppAccountService;
import cn.com.ctop.crawler.modules.core.service.IKuaishouCrawlerService;
import cn.com.ctop.crawler.modules.core.util.KuaishouUtil;
import cn.com.ctop.crawler.modules.log.entity.CrawlerLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Random;

@Service
public class KuaishouCrawlerServiceImpl implements IKuaishouCrawlerService {
    @Autowired
    private IIpPoolService iIpPoolService;
    @Autowired
    private IKuaishouAppAccountService kuaishouAppAccountService;

    @Override
    public String getVideoFeeds(KuaishouAppAccount kuaishouAppAccount, Integer page) {
        IpPool ipPool = iIpPoolService.getAvaliableIp();
//        String.format(kuaishouAppAccount.getBodyParam(), String.valueOf(page.intValue()), String.valueOf(100 + page.intValue()), String.valueOf(page.intValue()))
        String bodyParam = kuaishouAppAccount.getBodyParam().replaceFirst("%s", String.valueOf(page.intValue())).replaceFirst("%s", String.valueOf(100 + page.intValue())).replaceFirst("%s", String.valueOf(page.intValue()));
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(
                kuaishouAppAccount.getUrl(),
                kuaishouAppAccount.getPath(),
                String.format(kuaishouAppAccount.getUrlParam(), String.valueOf(System.currentTimeMillis())).replace(" ", "-"),
                bodyParam,
                String.format(kuaishouAppAccount.getHeaderParam(), randomRequestId()),
                kuaishouAppAccount.getToken(), ipPool);
        if (crawlerLog != null){
            return crawlerLog.getResponseBody();
        }
        return null;
    }

    @Override
    public String getVideoFeeds(KuaishouIosAccount kuaishouIosAccount){
        IpPool ipPool = iIpPoolService.getAvaliableIp();
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(
                kuaishouIosAccount.getUrl(),
                kuaishouIosAccount.getPath(),
                kuaishouIosAccount.getUrlParam().replace(" ","-"),
                kuaishouIosAccount.getBodyParam(),
                kuaishouIosAccount.getHeaderParam(),
                kuaishouIosAccount.getToken(), ipPool);
        if (crawlerLog != null){
            return crawlerLog.getResponseBody();
        }
        return null;
    }

    @Override
    public String getUserProfile(Long userId) {
        IpPool ipPool = iIpPoolService.getAvaliableIp();
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch("http://api.ksapisrv.com", "/rest/n/user/profile/v2", String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(ALP-AL00)&appver=6.5.6.9739&ftt=&isp=CUCC&kpn=KUAISHOU&lon=116.489647&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=0&country_code=cn&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&net=WIFI&did=ANDROID_99fc74cb7188a11f&lat=39.958823", System.currentTimeMillis()), String.format("token=5bc0b7924afc4a13a542a980138e20fd-1153842485&user=%s&sig=6417d1fcaa8b0e08cf95cb55f8071da1&client_key=3c2cd3f3&pv=true&__NStokensig=234e8e4c1f82a2e217bee01286fd8fa66f47461c78657901aa2e53dcdd1b811f", String.valueOf(userId)), String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com", randomRequestId()), "2f8b6f33da6c4159bf5f2d7882af5bf1-1153842485", ipPool);
        if (crawlerLog != null) {
            return crawlerLog.getResponseBody();
        }
        return null;
    }

    @Override
    public String getAdAccountVideoFeeds(KuaishouAdAccount kuaishouAdAccount, String pcursor) {
        IpPool ipPool = iIpPoolService.getAvaliableIp();
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch("http://api.ksapisrv.com", "/rest/n/feed/profile2", String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(ALP-AL00)&appver=6.5.6.9739&ftt=&isp=CUCC&kpn=KUAISHOU&lon=116.489647&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=0&country_code=cn&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&net=WIFI&did=ANDROID_99fc74cb7188a11f&lat=39.958823", System.currentTimeMillis()), String.format("token=2f8b6f33da6c4159bf5f2d7882af5bf1-1153842485&user_id=%s&lang=zh&count=30&privacy=public&referer=ks://profile/%s/-1/-1/8&browseType=1&sig=6417d1fcaa8b0e08cf95cb55f8071da1&client_key=3c2cd3f3&os=android&__NStokensig=d23103cf6c7c88a21ee3cfc07c34cd25879f522c72d237b8408fe6db086960b3&pcursor=" + pcursor, kuaishouAdAccount.getKsid(), kuaishouAdAccount.getKsid()), String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com", randomRequestId()), "2f8b6f33da6c4159bf5f2d7882af5bf1-1153842485", ipPool);
        if (crawlerLog != null){
            return crawlerLog.getResponseBody();
        }
        return null;
    }

    @Override
    public String getMusicTypeList(String llsid){
//        IpPool ipPool = iIpPoolService.getAvaliableIp();
        String token = "a7805c554d6a453ea3350b629b28fed9-1144829703";
        String staticStr = String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(VOG-AL10)&appver=6.5.5.9591&ftt=&isp=CUCC&kpn=KUAISHOU&lon=0&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=1144829703&country_code=cn&pm_tag=&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&extId=4db221a192e4d1d713c5dafb204400a8&net=WIFI&did=ANDROID_07264410e70db2ca&lat=0", String.valueOf(System.currentTimeMillis()));
        String paramStr = String.format("type=0&channel=141&llsid="+llsid+"&photoDuration=0&recoMusicMeta=&os=android&token=%s&cs=false&client_key=3c2cd3f3&__NS_sig3=2189731219daa23b36ec93140ecd7494f48a48e813&kuaishou.api_st=Cg9rdWFpc2hvdS5hcGkuc3QSsAF_IxHX9h-6duQiaMu7o-G89jpC9EnpoJeUMj7YhcOk1GM2_bDCgJKAiXkOwzZwMgxFNaeHnUY3MA696XRlsWaP2ermxyhUftx4N-SWe5CU9GwI77yQMFasot8A7BO9d0lua9Xz6raSA4O80lMCyxQGGb9FLhwRC1NOB56S6FzUcu5WEekzgOXLyp-4183efDKcQNm0Kg6bQu91KLn7V8h401Lwj1FWacLzuTMc7wxiIxoSgZ_Nba6SSgega5pcXl8O1pthIiDXU6aKxF7-piTZn4gN7MG9NcqBda10hanRm4PfkGobtigFMAE", token);
        String headerStr = String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com",randomRequestId());
        String url = "http://apihb6.gifshow.com";
        String path = "/rest/n/music/channel/music";
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(url, path, staticStr, paramStr, headerStr, token, null);
        return crawlerLog.getResponseBody();
    }

    public static void main(String[] args) {

    }

    @Override
    public String musicSearchSuggest(String keyword) throws UnsupportedEncodingException {
//        IpPool ipPool = iIpPoolService.getAvaliableIp();
        String token = "a7805c554d6a453ea3350b629b28fed9-1144829703";
        String staticStr = String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(VOG-AL10)&appver=6.5.5.9591&ftt=&isp=CUCC&kpn=KUAISHOU&lon=0&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=1144829703&country_code=cn&pm_tag=&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&extId=4db221a192e4d1d713c5dafb204400a8&net=WIFI&did=ANDROID_07264410e70db2ca&lat=0", String.valueOf(System.currentTimeMillis()));
        String paramStr = "keyword="+URLEncoder.encode(keyword,"UTF-8")+"&cs=false&sig=e27b8b11808aad7d21fd8122cf20bf0a&client_key=3c2cd3f3&__NS_sig3=2189731419daa7335afae1d97b6495e3c4396e7aaa&os=android&kuaishou.api_st=Cg9rdWFpc2hvdS5hcGkuc3QSsAF_IxHX9h-6duQiaMu7o-G89jpC9EnpoJeUMj7YhcOk1GM2_bDCgJKAiXkOwzZwMgxFNaeHnUY3MA696XRlsWaP2ermxyhUftx4N-SWe5CU9GwI77yQMFasot8A7BO9d0lua9Xz6raSA4O80lMCyxQGGb9FLhwRC1NOB56S6FzUcu5WEekzgOXLyp-4183efDKcQNm0Kg6bQu91KLn7V8h401Lwj1FWacLzuTMc7wxiIxoSgZ_Nba6SSgega5pcXl8O1pthIiDXU6aKxF7-piTZn4gN7MG9NcqBda10hanRm4PfkGobtigFMAE&__NStokensig=027a830ffe1bda42ed011a341631bed7b2654d80e2e2cfb9494ffabbdf8034d1&token="+token;
        String headerStr = String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com",randomRequestId());
        String url = "http://apihb6.gifshow.com";
        String path = "/rest/n/music/search/suggest";
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(url, path, staticStr, paramStr, headerStr, token, null);
        return crawlerLog.getResponseBody();
    }

    @Override
    public String musicSearchList(String keyword) throws UnsupportedEncodingException {
//        IpPool ipPool = iIpPoolService.getAvaliableIp();
        String token = "a7805c554d6a453ea3350b629b28fed9-1144829703";
        String staticStr = String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(VOG-AL10)&appver=6.5.5.9591&ftt=&isp=CUCC&kpn=KUAISHOU&lon=0&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=1144829703&country_code=cn&pm_tag=&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&extId=4db221a192e4d1d713c5dafb204400a8&net=WIFI&did=ANDROID_07264410e70db2ca&lat=0", String.valueOf(System.currentTimeMillis()));
        String paramStr = "keyword="+ URLEncoder.encode(keyword,"UTF-8") +"&cs=false&sig=e27b8b11808aad7d21fd8122cf20bf0a&client_key=3c2cd3f3&os=android&__NS_sig3=2189731219daa23b36ec93140ecd7494f48a48e813&kuaishou.api_st=Cg9rdWFpc2hvdS5hcGkuc3QSsAF_IxHX9h-6duQiaMu7o-G89jpC9EnpoJeUMj7YhcOk1GM2_bDCgJKAiXkOwzZwMgxFNaeHnUY3MA696XRlsWaP2ermxyhUftx4N-SWe5CU9GwI77yQMFasot8A7BO9d0lua9Xz6raSA4O80lMCyxQGGb9FLhwRC1NOB56S6FzUcu5WEekzgOXLyp-4183efDKcQNm0Kg6bQu91KLn7V8h401Lwj1FWacLzuTMc7wxiIxoSgZ_Nba6SSgega5pcXl8O1pthIiDXU6aKxF7-piTZn4gN7MG9NcqBda10hanRm4PfkGobtigFMAE&token="+token;
        String headerStr = String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com",randomRequestId());
        String url = "http://apihb6.gifshow.com";
        String path = "/rest/n/music/search/v3";
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(url, path, staticStr, paramStr, headerStr, token, null);
        return crawlerLog.getResponseBody();
    }

    @Override
    public String getMusicList(String channel, String llsid){
//        IpPool ipPool = iIpPoolService.getAvaliableIp();
        String token = "a7805c554d6a453ea3350b629b28fed9-1144829703";
        String staticStr = String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(VOG-AL10)&appver=6.5.5.9591&ftt=&isp=CUCC&kpn=KUAISHOU&lon=0&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=1144829703&country_code=cn&pm_tag=&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&extId=4db221a192e4d1d713c5dafb204400a8&net=WIFI&did=ANDROID_07264410e70db2ca&lat=0", String.valueOf(System.currentTimeMillis()));
        String paramStr = String.format("type=0&channel="+channel+"&llsid="+llsid+"&photoDuration=0&recoMusicMeta=&os=android&token=%s&cs=false&client_key=3c2cd3f3&__NS_sig3=2189731219daa23b36ec93140ecd7494f48a48e813&kuaishou.api_st=Cg9rdWFpc2hvdS5hcGkuc3QSsAF_IxHX9h-6duQiaMu7o-G89jpC9EnpoJeUMj7YhcOk1GM2_bDCgJKAiXkOwzZwMgxFNaeHnUY3MA696XRlsWaP2ermxyhUftx4N-SWe5CU9GwI77yQMFasot8A7BO9d0lua9Xz6raSA4O80lMCyxQGGb9FLhwRC1NOB56S6FzUcu5WEekzgOXLyp-4183efDKcQNm0Kg6bQu91KLn7V8h401Lwj1FWacLzuTMc7wxiIxoSgZ_Nba6SSgega5pcXl8O1pthIiDXU6aKxF7-piTZn4gN7MG9NcqBda10hanRm4PfkGobtigFMAE", token);
        String headerStr = String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com",randomRequestId());
        String url = "http://apihb6.gifshow.com";
        String path = "/rest/n/music/channel/music";
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(url, path, staticStr, paramStr, headerStr, token, null);
        return crawlerLog.getResponseBody();
    }


    @Override
    public String getAdFeeds(){
        IpPool ipPool = iIpPoolService.getAvaliableIp();
        String token = "a7805c554d6a453ea3350b629b28fed9-1144829703";
        String staticStr = String.format("app=0&kpf=ANDROID_PHONE&ver=6.5&c=HUAWEI&mod=HUAWEI(VOG-AL10)&appver=6.5.5.9591&ftt=&isp=CUCC&kpn=KUAISHOU&lon=0&language=zh-cn&sys=ANDROID_9&max_memory=384&ud=1144829703&country_code=cn&pm_tag=&oc=HUAWEI&hotfix_ver=&did_gt=%s&iuid=&extId=4db221a192e4d1d713c5dafb204400a8&net=WIFI&did=ANDROID_07264410e70db2ca&lat=0", String.valueOf(System.currentTimeMillis()));
        String paramStr = String.format("campaign_id=4129735&client_key=3c2cd3f3&os=android&__NStokensig=6338a81daf2be08b4dfcec2867fd39c45ffa59f02a3b687e80e1f1eafd3053e5&token=%s", token);
        String headerStr = String.format("User-Agent=kwai-android&Connection=keep-alive&Accept-Language=zh-cn&X-REQUESTID=%s&Content-Type=application/x-www-form-urlencoded&Host=api.ksapisrv.com",randomRequestId());
        String url = "http://api.ksapisrv.com";
        String path = "/rest/n/ad/list";
        CrawlerLog crawlerLog = KuaishouUtil.kuaishouAppDataFeatch(url, path, staticStr, paramStr, headerStr, token, ipPool);
        return crawlerLog.getResponseBody();
    }

    private String randomRequestId() {
        int temp = 436669999 - 436650000;
        int nextInt = new Random().nextInt(temp) + 436650000;
        return String.valueOf(nextInt);
    }
}
