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

import cn.com.ctop.common.module.entity.MusicInfo;
import cn.com.ctop.common.module.entity.MusicType;
import cn.com.ctop.common.module.service.MusicInfoService;
import cn.com.ctop.common.module.service.MusicTypeService;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.crawler.modules.core.entity.CrawlerDouyinMusicTask;
import cn.com.ctop.crawler.modules.core.service.CrawlerDouyinMusicTaskService;
import cn.com.ctop.crawler.modules.douyin.service.DouyinMusicService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@Service
public class DouyinMusicServiceImpl implements DouyinMusicService {
    @Autowired
    private CrawlerDouyinMusicTaskService crawlerDouyinMusicTaskService;
    @Autowired
    private MusicInfoService musicInfoService;
    @Autowired
    private MusicTypeService musicTypeService;
    @Override
    public void getHotMusicList(){
        String url = "https://creator.douyin.com/aweme/v1/creator/data/billboard/?aid=2906&app_name=aweme_creator_platform&device_platform=web&referer=https:%2F%2Fcreator.douyin.com%2F&user_agent=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64%3B+rv:80.0)+Gecko%2F20100101+Firefox%2F80.0&cookie_enabled=true&screen_width=1536&screen_height=864&browser_language=zh-CN&browser_platform=Win32&browser_name=Mozilla&browser_version=5.0+(Windows)&browser_online=true&timezone_name=Asia%2FShanghai&billboard_type=6&_signature=_02B4Z6wo00901FbWCdAAAIBB6k9NWx0O5TxW0w1AAErn2F8l9l2jOfxyCzOfdlXpqs7Jz3K5YWTQ7ZxQ8a4bqx85bUqwtY.OgdqWoKF.cc5mFNk3AkmG5Z2RIj7cSmXlNU1zG59k7E65Lt8n40";
        Map<String,String> headerMap = new HashMap<>();
        headerMap.put("Referer","https://creator.douyin.com/billboard/music");
        headerMap.put("Cookie","MONITOR_WEB_ID=69612188090;ttcid=0270ed5a06644d8ca4cd65a7e5ad3a6036;s_v_web_id=ketjic0a_4EKpH1vA_rtXt_4EGc_BPnk_CZ9O5Gu0xDe8; passport_csrf_token=2ab18108bd0281d8db0641cc40132349; ttwid=1%7Ckh0S_WTrqe8BOM-YBNvf-AKjQyFR5u3GBgRZy8sKt0o%7C1599544523%7C67c55021b4b2aceb7b136b60b4a02297c6b9cced82bdec7203e80161f3051b8e;odin_tt=c25bf19d139bccd7ba8ee127c39f25b4702f0213cd6bcceacec30ec6df0b7a47d5df942bbc2748ceded3383d4088d5ac;sso_uid_tt=f27d6ff96b247f66520f4d577d9f6a37;sso_uid_tt_ss=f27d6ff96b247f66520f4d577d9f6a37;toutiao_sso_user=ae007bb2f15d01e9ac72a585ddd73703;toutiao_sso_user_ss=ae007bb2f15d01e9ac72a585ddd73703;passport_auth_status=b880b63ad5785c54fe7da286bd8a6c8f%2C;sid_guard=a437b759fe88d695e2778f45ddd0132f%7C1599544553%7C5184000%7CSat%2C+07-Nov-2020+05%3A55%3A53+GMT;uid_tt=3146be8778efa32f0d7d7203d53049f3;uid_tt_ss=3146be8778efa32f0d7d7203d53049f3;sid_tt=a437b759fe88d695e2778f45ddd0132f;sessionid=a437b759fe88d695e2778f45ddd0132f;sessionid_ss=a437b759fe88d695e2778f45ddd0132f;oc_login_type=LOGIN_PERSON; csrf_token=R5sJbie9TbF0k6BqwMASbsek; SLARDAR_WEB_ID=69612188090;tt_scid=WIdNPLYcFCAZuQRtN72sb9Z9mP95Hlma5gr9VX1anidEKoiRiBKKisWUm5ORhK8t3375");
        headerMap.put("Host","creator.douyin.com");
        headerMap.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0");
        String result = HttpUtils.httpGet(url,null,headerMap);
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode rootNode = mapper.readTree(result);
            int size = rootNode.get("billboard_data").size();
            if(size > 0){
                Iterator<JsonNode> nodeList = rootNode.get("billboard_data").iterator();
                while (nodeList.hasNext()){
                    JsonNode dataNode = nodeList.next();
                    String author = dataNode.get("author").asText();
                    Integer duration = dataNode.get("duration").asInt();
                    String imgUrl = dataNode.get("img_url").asText();
                    String title = dataNode.get("title").asText();
                    String link = dataNode.get("link").asText();
                    Integer value = dataNode.get("value").asInt();
                    String mid = link.substring(link.lastIndexOf("/")+1,link.length());
                    QueryWrapper<MusicInfo> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("source","douyin");
                    queryWrapper.eq("ext_id",mid);

                    MusicInfo musicInfoEntity = musicInfoService.getOne(queryWrapper);
                    if(musicInfoEntity == null){
                        musicInfoEntity = new MusicInfo();
                        musicInfoEntity.setExtId(Long.parseLong(mid));
                        musicInfoEntity.setUsedCount(value);
                        musicInfoEntity.setCoverUrl(imgUrl);
                        musicInfoEntity = this.getMusicInfo(musicInfoEntity);
                        musicInfoService.save(musicInfoEntity);
                        CrawlerDouyinMusicTask crawlerDouyinMusicTask = new CrawlerDouyinMusicTask();
                        crawlerDouyinMusicTask.setId(Long.parseLong(mid));
                        crawlerDouyinMusicTask.setStatus("done");
                        crawlerDouyinMusicTaskService.replaceInto(crawlerDouyinMusicTask);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void parseTag(MusicInfo musicInfo){
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode extraNode = mapper.readTree(musicInfo.getExtInfo());
            JsonNode tagNode = extraNode.get("tags_v2");
            if (tagNode != null && tagNode.size() > 0){
                Iterator<String> tagTypeList = tagNode.getFieldNames();
                while (tagTypeList.hasNext()){
                    String tagType = tagTypeList.next();
                    Iterator<String> tagList = tagNode.get(tagType).getFieldNames();
                    while (tagList.hasNext()){
                        String tag = tagList.next();
                        JsonNode tagValueNode = tagNode.get(tagType).get(tag);
                        for (int i = 0; i < tagValueNode.size(); i++){
                            String tagValue = tagValueNode.get(i).asText();
                            QueryWrapper<MusicType> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("music_id",musicInfo.getId())
                                    .eq("ext_type",tag)
                                    .eq("ext_type_value",tagValue).last(" limit 1");

                            MusicType musicType = musicTypeService.getOne(queryWrapper);
                            if (musicType == null){
                                musicType = new MusicType();
                                musicType.setAuthor(musicInfo.getAuthor());
                                musicType.setExtType(tag);
                                musicType.setExtTypeValue(tagValue);
                                musicType.setMusicId(musicInfo.getId());
                                musicType.setMusicName(musicInfo.getName());
                                musicTypeService.save(musicType);
                            }
                        }
                    }
                }
            }
            CrawlerDouyinMusicTask crawlerDouyinMusicTask = new CrawlerDouyinMusicTask();
            crawlerDouyinMusicTask.setId(musicInfo.getExtId());
            crawlerDouyinMusicTask.setStatus("parsed");
            crawlerDouyinMusicTaskService.updateById(crawlerDouyinMusicTask);
        }catch (Exception e){
            CrawlerDouyinMusicTask crawlerDouyinMusicTask = new CrawlerDouyinMusicTask();
            crawlerDouyinMusicTask.setId(musicInfo.getExtId());
            crawlerDouyinMusicTask.setStatus("error");
            crawlerDouyinMusicTaskService.updateById(crawlerDouyinMusicTask);
            e.printStackTrace();
        }
    }

    @Override
    public MusicInfo getMusicInfo(MusicInfo musicInfo){
        String url = "https://www.iesdouyin.com/web/api/v2/music/info/?music_id="+musicInfo.getExtId();
        String result = HttpUtils.httpGet(url,null,null);
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode rootNode = mapper.readTree(result);
            String musicUrl = rootNode.get("music_info").get("play_url").get("url_list").get(0).asText();
            String author = rootNode.get("music_info").get("author").asText();
//            String coverLarge = rootNode.get("music_info").get("cover_large").get("uri").asText();
//            String filename = coverLarge.substring(coverLarge.lastIndexOf("/")+1);
            String title = rootNode.get("music_info").get("title").asText();
            Integer duration = rootNode.get("music_info").get("duration").asInt();
//            String coverUrl = "https://p29-dy.byteimg.com/aweme/100x100/iesmusic-cn-local/v1/tt-obj/image/"+filename+".jpeg";
            musicInfo.setSource("douyin");
            musicInfo.setAuthor(author);
            musicInfo.setCoverUrl("");
            musicInfo.setName(title);
            musicInfo.setDuration(duration);
            musicInfo.setMusicUrl(musicUrl);
            String extra = rootNode.get("music_info").get("extra").asText();
            musicInfo.setExtInfo(extra);
            JsonNode extraRoot = mapper.readTree(extra);
            JsonNode extraNode = extraRoot.get("similar_music_ids");
            musicInfoService.save(musicInfo);
            CrawlerDouyinMusicTask crawlerDouyinMusic = new CrawlerDouyinMusicTask();
            crawlerDouyinMusic.setId(musicInfo.getExtId());
            crawlerDouyinMusic.setStatus("done");
            crawlerDouyinMusicTaskService.updateById(crawlerDouyinMusic);
            parseTag(musicInfo);
            if (extraNode != null && extraNode.size() > 0){
                Iterator<JsonNode> extraList = extraNode.iterator();
                while (extraList.hasNext()){
                    JsonNode dataNode = extraList.next();
                    int size = dataNode.size();
                    for (int i = 0; i < size; i++){
                        CrawlerDouyinMusicTask crawlerDouyinMusicTask = crawlerDouyinMusicTaskService.getById(dataNode.get(i).asLong());
                        if(crawlerDouyinMusicTask == null){
                            crawlerDouyinMusicTask = new CrawlerDouyinMusicTask();
                            crawlerDouyinMusicTask.setId(dataNode.get(i).asLong());
                            crawlerDouyinMusicTask.setStatus("init");
                            crawlerDouyinMusicTaskService.replaceInto(crawlerDouyinMusicTask);
                        }
                    }
                }
            }
        } catch (IOException e) {
            CrawlerDouyinMusicTask crawlerDouyinMusic = new CrawlerDouyinMusicTask();
            crawlerDouyinMusic.setId(musicInfo.getExtId());
            crawlerDouyinMusic.setStatus("error");
            crawlerDouyinMusicTaskService.updateById(crawlerDouyinMusic);
            e.printStackTrace();
        }
        return musicInfo;
    }
    public static void main(String[] args){
        DouyinMusicServiceImpl douyinMusicService = new DouyinMusicServiceImpl();
        MusicInfo musicInfo = new MusicInfo();
        musicInfo.setExtId(12646L);
        douyinMusicService.getMusicInfo(musicInfo);
    }
}
