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

import cn.com.ctop.common.module.utils.Check;
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.IKuaishouAdAccountService;
import cn.com.ctop.crawler.modules.core.service.IKuaishouCrawlerService;
import cn.com.ctop.kuaishou.modules.app.entity.AppAd;
import cn.com.ctop.kuaishou.modules.app.entity.AppFeeds;
import cn.com.ctop.kuaishou.modules.app.entity.AppResult;
import cn.com.ctop.kuaishou.modules.app.entity.AppVideo;
import cn.com.ctop.kuaishou.modules.app.service.IAppAdService;
import cn.com.ctop.kuaishou.modules.app.service.IAppVideoService;
import cn.com.ctop.kuaishou.modules.app.service.IKuaishouAppService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author yumeng
 * 2019年11月12日10:04:00
 */
@Slf4j
@Service
@Primary
public class KuaishouAppServiceImpl implements IKuaishouAppService {
    @Autowired
    private IKuaishouCrawlerService kuaishouCrawlerService;
    @Autowired
    private IAppAdService appAdService;
    @Autowired
    private IAppVideoService appVideoService;
    @Autowired
    private IKuaishouAdAccountService kuaishouAdAccountService;

    @Override
    public void adFetch(KuaishouAppAccount kuaishouAppAccount, Integer page) {
        String videoFeeds = kuaishouCrawlerService.getVideoFeeds(kuaishouAppAccount, page);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            AppResult appResult = mapper.readValue(videoFeeds, new TypeReference<AppResult>() {
            });
            if (appResult != null) {
                List<AppFeeds> feeds = appResult.getFeeds();
                if (!Check.isNull(feeds)) {
                    for (AppFeeds appFeeds : feeds) {
                        AppAd ad = appFeeds.getAd();
                        if (ad != null) {
                            if (ad.getAdCover() == null) {
                                continue;
                            }
                            ad.setTime(appFeeds.getTime());
                            ad.setCoverUrl(ad.getAdCover().getCoverUrls().get(0).getUrl().replace(".kpg", ".jpg"));
                            ad.setMvUrl(appFeeds.getMainMvUrls().get(0).getUrl());
                            ad.setRecoReason(appFeeds.getRecoReason());
                            ad.setUserId(appFeeds.getUserId());
                            ad.setPageId(appFeeds.getPhotoId());
                            ad.setPhotoId(appFeeds.getPhotoId());
                            ad.setUserName(appFeeds.getUserName());
                            ad.setPhotoStatus(appFeeds.getPhotoStatus());
                            ad.setShareInfo(appFeeds.getShareInfo());
                            ad.setViewCount(appFeeds.getViewCount());
                            ad.setLikeCount(appFeeds.getLikeCount());
                            ad.setCommentCount(appFeeds.getCommentCount());
                            ad.setForwardCount(appFeeds.getForwardCount());
                            ad.setUnlikeCount(appFeeds.getUnlikeCount());
                            ad.setCaption(appFeeds.getCaption());
                            ad.setWidth(ad.getAdCover().getWidth());
                            ad.setHeight(ad.getAdCover().getHeight());
                            ad.setType(appFeeds.getType());
                            ad.setAppName(ad.getAppName().replace(".apk", "").replace(".APK", "").replace("ios", "").replace("IOS", ""));
                            appAdService.saveOrUpdate(ad);
                            KuaishouAdAccount kuaishouAdAccount = kuaishouAdAccountService.getById(ad.getUserId());
                            if (kuaishouAdAccount == null) {
                                kuaishouAdAccount = new KuaishouAdAccount();
                                kuaishouAdAccount.setKsid(ad.getUserId());
                                kuaishouAdAccount.setName(ad.getUserName());
                                kuaishouAdAccountService.save(kuaishouAdAccount);
                                this.adAccountFetch(kuaishouAdAccount, "");
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void adAccountFetch(KuaishouAdAccount kuaishouAdAccount, String pcursor) {
        String userProfileStr = kuaishouCrawlerService.getUserProfile(kuaishouAdAccount.getKsid());
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            JsonNode userProfileNode = mapper.readTree(userProfileStr);
            int photoCount = userProfileNode.get("userProfile").get("ownerCount").get("photo").asInt();
            QueryWrapper<AppVideo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", kuaishouAdAccount.getKsid());
            int videoCount = appVideoService.count(queryWrapper);
            if (photoCount <= videoCount) {
                return;
            }
            String adAccountVideoFeeds = kuaishouCrawlerService.getAdAccountVideoFeeds(kuaishouAdAccount, pcursor);
            JsonNode node = mapper.readTree(adAccountVideoFeeds);
            List<AppVideo> list = mapper.readValue(node.get("feeds").toString(), new TypeReference<List<AppVideo>>() {
            });
            pcursor = node.get("pcursor").asText();
            if (list != null) {
                for (AppVideo appVideo : list) {
                    if (appVideo.getCoverThumbnailUrls() != null) {
                        appVideo.setCoverUrl(appVideo.getCoverThumbnailUrls().get(0).getUrl());
                    }
                    if (appVideo.getMainMvUrls() != null) {
                        appVideo.setMvUrl(appVideo.getMainMvUrls().get(0).getUrl());
                    }

                    appVideoService.saveOrUpdate(appVideo);
                }
            }
            Thread.sleep(10000);
            if (pcursor != null && !"no_more".equals(pcursor)) {
                adAccountFetch(kuaishouAdAccount, pcursor);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void adFetch(KuaishouIosAccount kuaishouIosAccount) {
        String videoFeeds = kuaishouCrawlerService.getVideoFeeds(kuaishouIosAccount);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            AppResult appResult = mapper.readValue(videoFeeds, new TypeReference<AppResult>() {
            });
            if (appResult != null && appResult.getFeeds() != null) {
                for (AppFeeds appFeeds : appResult.getFeeds()) {
                    AppAd ad = appFeeds.getAd();
                    if (ad != null) {
                        if (ad.getAdCover() == null) {
                            continue;
                        }
                        ad.setTime(appFeeds.getTime());
                        ad.setCoverUrl(ad.getAdCover().getCoverUrls().get(0).getUrl().replace(".kpg", ".jpg"));
                        ad.setMvUrl(appFeeds.getMainMvUrls().get(0).getUrl());
                        ad.setRecoReason(appFeeds.getRecoReason());
                        ad.setUserId(appFeeds.getUserId());
                        ad.setPageId(appFeeds.getPhotoId());
                        ad.setPhotoId(appFeeds.getPhotoId());
                        ad.setUserName(appFeeds.getUserName());
                        ad.setPhotoStatus(appFeeds.getPhotoStatus());
                        ad.setShareInfo(appFeeds.getShareInfo());
                        ad.setViewCount(appFeeds.getViewCount());
                        ad.setLikeCount(appFeeds.getLikeCount());
                        ad.setCommentCount(appFeeds.getCommentCount());
                        ad.setForwardCount(appFeeds.getForwardCount());
                        ad.setUnlikeCount(appFeeds.getUnlikeCount());
                        ad.setCaption(appFeeds.getCaption());
                        ad.setWidth(ad.getAdCover().getWidth());
                        ad.setHeight(ad.getAdCover().getHeight());
                        ad.setType(appFeeds.getType());
                        String appName = ad.getAppName();
                        if (null != appName && !"".equals(appName.trim())) {
                            ad.setAppName(ad.getAppName().replace(".apk", "").replace(".APK", "").replace("ios", "").replace("IOS", ""));
                        }
                        appAdService.saveOrUpdate(ad);
                        KuaishouAdAccount kuaishouAdAccount = kuaishouAdAccountService.getById(ad.getUserId());
                        if (kuaishouAdAccount == null) {
                            kuaishouAdAccount = new KuaishouAdAccount();
                            kuaishouAdAccount.setKsid(ad.getUserId());
                            kuaishouAdAccount.setName(ad.getUserName());
                            kuaishouAdAccountService.save(kuaishouAdAccount);
                            this.adAccountFetch(kuaishouAdAccount, "");
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
