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

import cn.com.ctop.common.module.entity.HttpClientEntity;
import cn.com.ctop.common.module.entity.IpPool;
import cn.com.ctop.common.module.service.IIpPoolService;
import cn.com.ctop.common.module.utils.HttpClientUtils;
import cn.com.ctop.common.module.utils.HttpUtils2;
import cn.com.ctop.kuaishou.modules.graphql.entity.KuaishouPublicFeeds;
import cn.com.ctop.kuaishou.modules.graphql.entity.KuaishouUserCookie;
import cn.com.ctop.kuaishou.modules.graphql.entity.KuaishouWebData;
import cn.com.ctop.kuaishou.modules.graphql.entity.KuaishouWebResult;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouUserCookieService;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouUserService;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouVideoService;
import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
import cn.com.ctop.kuaishou.modules.graphql.vo.KuaishouAcceptVO;
import cn.com.ctop.kuaishou.modules.graphql.vo.KuaishouQrStartVO;
import cn.com.ctop.kuaishou.modules.graphql.vo.KuaishouUserVO;
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 com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.fontbox.ttf.CmapSubtable;
import org.apache.fontbox.ttf.GlyphData;
import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.MD5Util;
import org.jeecg.common.util.RedisUtil;
import org.openqa.selenium.Point;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yumeng
 * 2019年11月12日10:04:00
 */
@Slf4j
@Service
public class KuaishouWebInterfaceServiceImpl implements IKuaishouWebInterfaceService {
    @Autowired
    private IKuaishouUserService kuaishouUserService;
    @Autowired
    private IKuaishouVideoService kuaishouVideoService;
    @Autowired
    private IKuaishouUserCookieService kuaishouUserCookieService;
    @Autowired
    private IIpPoolService iIpPoolService;
    @Autowired
    private RedisUtil redisUtil;
    public static String GRAPHQL_URL = "https://live.kuaishou.com/graphql";

    public String userInfoQuery() {
        String queryStr = "{\"operationName\":\"userInfoQuery\",\"variables\":{},\"query\":\"query userInfoQuery {\\n  kshellBalance {\\n    kshell\\n    __typename\\n  }\\n  ownerInfo {\\n    id\\n    principalId\\n    kwaiId\\n    eid\\n    userId\\n    profile\\n    name\\n    description\\n    sex\\n    constellation\\n    cityName\\n    following\\n    living\\n    watchingCount\\n    isNew\\n    privacy\\n    timestamp\\n    feeds {\\n      eid\\n      photoId\\n      thumbnailUrl\\n      timestamp\\n      __typename\\n    }\\n    verifiedStatus {\\n      verified\\n      description\\n      type\\n      new\\n      __typename\\n    }\\n    countsInfo {\\n      fan\\n      follow\\n      photo\\n      liked\\n      open\\n      playback\\n      private\\n      __typename\\n    }\\n    bannedStatus {\\n      banned\\n      defriend\\n      isolate\\n      socialBanned\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";
        return queryStr;
    }

    public String userLogin(String qrToken) {
        String queryStr = "{\"operationName\":\"UserLogin\",\"variables\":{\"userLoginInfo\":{\"authToken\":\"" + qrToken + "\",\"sid\":\"kuaishou.live.web\"}},\"query\":\"mutation UserLogin($userLoginInfo: FlatObject) {\\n  login(userLoginInfo: $userLoginInfo) {\\n    result\\n    __typename\\n  }\\n}\\n\"}";
        return queryStr;
    }

    public String subCommentListQuery(String photoId, Long rootCommentId, String pcursor) {
        String queryStr = "{\"operationName\":\"subCommentListQuery\",\"variables\":{\"photoId\":\"" + photoId + "\",\"rootCommentId\":\"" + rootCommentId + "\",\"pcursor\":\"" + pcursor + "\",\"count\":20},\"query\":\"query subCommentListQuery($photoId: String, $rootCommentId: String, $pcursor: String, $count: Int) {\\n  subCommentList(photoId: $photoId, rootCommentId: $rootCommentId, pcursor: $pcursor, count: $count) {\\n    pcursor\\n    subCommentsList {\\n      commentId\\n      authorId\\n      authorName\\n      content\\n      headurl\\n      timestamp\\n      authorEid\\n      status\\n      replyToUserName\\n      replyTo\\n      replyToEid\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";
        return queryStr;
    }

    public String commentListQuery(String photoId, String pcursor) {
        String queryStr = "{\"operationName\":\"commentListQuery\",\"variables\":{\"pcursor\":\"" + pcursor + "\",\"photoId\":\"" + photoId + "\",\"page\":1,\"count\":20},\"query\":\"query commentListQuery($photoId: String, $page: Int, $pcursor: String, $count: Int) {\\n  shortVideoCommentList(photoId: $photoId, page: $page, pcursor: $pcursor, count: $count) {\\n    commentCount\\n    realCommentCount\\n    pcursor\\n    commentList {\\n      commentId\\n      authorId\\n      authorName\\n      content\\n      headurl\\n      timestamp\\n      authorEid\\n      status\\n      subCommentCount\\n      subCommentsPcursor\\n      likedCount\\n      liked\\n      subComments {\\n        commentId\\n        authorId\\n        authorName\\n        content\\n        headurl\\n        timestamp\\n        authorEid\\n        status\\n        replyToUserName\\n        replyTo\\n        replyToEid\\n        __typename\\n      }\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";
        return queryStr;
    }

    public String videoFeeds(String principalId, String pcursor) {
        String queryStr = "{\"operationName\":\"publicFeedsQuery\",\"variables\":{\"principalId\":\"" + principalId + "\",\"pcursor\":\"" + pcursor + "\",\"count\":24},\"query\":\"query publicFeedsQuery($principalId: String, $pcursor: String, $count: Int) {\\n  publicFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) {\\n    pcursor\\n    live {\\n      user {\\n        id\\n        kwaiId\\n        eid\\n        profile\\n        name\\n        living\\n        __typename\\n      }\\n      watchingCount\\n      src\\n      title\\n      gameId\\n      gameName\\n      categoryId\\n      liveStreamId\\n      playUrls {\\n        quality\\n        url\\n        __typename\\n      }\\n      followed\\n      type\\n      living\\n      redPack\\n      liveGuess\\n      anchorPointed\\n      latestViewed\\n      expTag\\n      __typename\\n    }\\n    list {\\n      photoId\\n      caption\\n      thumbnailUrl\\n      poster\\n      viewCount\\n      likeCount\\n      commentCount\\n      timestamp\\n      workType\\n      type\\n      useVideoPlayer\\n      imgUrls\\n      imgSizes\\n      magicFace\\n      musicName\\n      location\\n      liked\\n      onlyFollowerCanComment\\n      relativeHeight\\n      width\\n      height\\n      user {\\n        id\\n        eid\\n        name\\n        profile\\n        __typename\\n      }\\n      expTag\\n      __typename\\n    }\\n    __typename\\n  }\\n}\\n\"}";
        return queryStr;
    }

    @Override
    public Map<String, Object> subCommentList(String userId, String ksid, String photoId, Long rootCommentId, String pcursor) {
        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<KuaishouUserCookie>();
        Map<String, Object> resultMap = new HashMap<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("ksid", ksid);
        KuaishouUserCookie kuaishouUserCookie = kuaishouUserCookieService.getOne(queryWrapper);
        if (kuaishouUserCookie != null) {
            if (pcursor == null) {
                pcursor = "";
            }
            IpPool ipPool = iIpPoolService.getAvaliableIp();
            Map<String, Object> params = new HashMap<String, Object>();
            HttpClientEntity httpClientEntity = new HttpClientEntity();
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
            httpClientEntity.setUrl("https://live.kuaishou.com/graphql");
            httpClientEntity.setResult("");
            httpClientEntity.setCookieStore(cookieTransfer(kuaishouUserCookie.getCookie()));
            httpClientEntity.setHeaders(getHeaders());
            httpClientEntity.setParams(params);
            try {
                httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, subCommentListQuery(photoId, rootCommentId, pcursor));
                ObjectMapper mapper = new ObjectMapper();
                resultMap = mapper.readValue(httpClientEntity.getResult(), new TypeReference<Map<String, Object>>() {
                });
                JsonNode resultNode = mapper.readTree(httpClientEntity.getResult()).get("data");
                if (resultNode.get("subCommentList").isNull() || resultNode.get("subCommentList").get("pcursor").isNull()) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                    return subCommentList(userId, ksid, photoId, rootCommentId, pcursor);
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (ipPool != null) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                }
                return subCommentList(userId, ksid, photoId, rootCommentId, pcursor);
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> commentList(String userId, String ksid, String photoId, String pcursor) {
        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<KuaishouUserCookie>();
        Map<String, Object> resultMap = new HashMap<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("ksid", ksid);
        KuaishouUserCookie kuaishouUserCookie = kuaishouUserCookieService.getOne(queryWrapper);
        if (kuaishouUserCookie != null) {
            if (pcursor == null) {
                pcursor = "";
            }
            IpPool ipPool = iIpPoolService.getAvaliableIp();
            Map<String, Object> params = new HashMap<String, Object>();
            BasicClientCookie basicClientCookie1 = new BasicClientCookie("did", "web_" + MD5Util.getMd5(new Date().toString()));
            BasicClientCookie basicClientCookie2 = new BasicClientCookie("didv", "1570780462000");
            BasicClientCookie basicClientCookie3 = new BasicClientCookie("clientid", "3");
            BasicClientCookie basicClientCookie4 = new BasicClientCookie("client_key", "65890b29");
            basicClientCookie1.setDomain("live.kuaishou.com");
            basicClientCookie2.setDomain("live.kuaishou.com");
            basicClientCookie3.setDomain("live.kuaishou.com");
            basicClientCookie4.setDomain("live.kuaishou.com");
            CookieStore cookieStore = new BasicCookieStore();
            cookieStore.addCookie(basicClientCookie1);
            cookieStore.addCookie(basicClientCookie2);
            cookieStore.addCookie(basicClientCookie3);
            cookieStore.addCookie(basicClientCookie4);
            HttpClientEntity httpClientEntity = new HttpClientEntity();
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            try {
                httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
                httpClientEntity.setHeaders(getHeaders());
                httpClientEntity.setParams(params);
                httpClientEntity.setUrl("https://live.kuaishou.com/graphql");
                httpClientEntity.setResult("");
                httpClientEntity.setCookieStore(cookieStore);
                httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, commentListQuery(photoId, pcursor));

                ObjectMapper mapper = new ObjectMapper();
                if (httpClientEntity.getResult() == null) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                    return commentList(userId, ksid, photoId, pcursor);
                }
                resultMap = mapper.readValue(httpClientEntity.getResult(), new TypeReference<Map<String, Object>>() {
                });
                JsonNode resultNode = mapper.readTree(httpClientEntity.getResult()).get("data");
                if (resultNode.get("shortVideoCommentList").isNull() || resultNode.get("shortVideoCommentList").get("pcursor").isNull()) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                    return commentList(userId, ksid, photoId, pcursor);
                }
            } catch (Exception e) {
                if (ipPool != null) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                }
                e.printStackTrace();
                return commentList(userId, ksid, photoId, pcursor);
            }
        }
        return resultMap;
    }

    public Map<String, String> getTTfNumber(KuaishouUserCookie kuaishouUserCookie) throws Exception {
        HttpClientEntity httpClientEntity = new HttpClientEntity();
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(null));
        httpClientEntity.setUrl("https://live.kuaishou.com/profile/" + kuaishouUserCookie.getEid() + "?csr=true");
        httpClientEntity.setResult("");
        httpClientEntity.setCookieStore(cookieTransfer(kuaishouUserCookie.getCookie()));
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(new HashMap<>());
        httpClientEntity = httpClientUtils.httpGetRequest(httpClientEntity);

        Pattern p = Pattern.compile("fontscn\\w+\\.ttf");
        Matcher m = p.matcher(httpClientEntity.getResult());
        String ttf = "";
        while (m.find()) {
            ttf = m.group();
        }
        Map<String, String> map = HttpUtils2.fontsMap.get(ttf);
        if (map == null) {
            map = kuaishouTtf(ttf);
        }
        return map;
    }

    @Override
    public Map<String, Object> videoList(String userId, String ksid, String pcursor) {

        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<KuaishouUserCookie>();
        Map<String, Object> resultMap = new HashMap<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("ksid", ksid);
        KuaishouUserCookie kuaishouUserCookie = kuaishouUserCookieService.getOne(queryWrapper);
        if (kuaishouUserCookie != null) {
            if (pcursor == null) {
                pcursor = "";
            }
            IpPool ipPool = iIpPoolService.getAvaliableIp();
            Map<String, Object> params = new HashMap<String, Object>();
            HttpClientEntity httpClientEntity = new HttpClientEntity();
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
            httpClientEntity.setResult("");
            httpClientEntity.setCookieStore(cookieTransfer(kuaishouUserCookie.getCookie()));
            httpClientEntity.setParams(params);
            httpClientEntity.setHeaders(getHeaders());
            httpClientEntity.setUrl("https://live.kuaishou.com/graphql");
            try {
                httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, videoFeeds(kuaishouUserCookie.getEid(), pcursor));
                String result = httpClientEntity.getResult();
                if (httpClientEntity.getResult() == null) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                    return videoList(userId, ksid, pcursor);
                }
                Map<String, String> map = getTTfNumber(kuaishouUserCookie);
                for (String key : map.keySet()) {
                    result = result.replace(key, map.get(key));
                }

                ObjectMapper mapper = new ObjectMapper();
                resultMap = mapper.readValue(result, new TypeReference<Map<String, Object>>() {
                });
                JsonNode resultNode = mapper.readTree(httpClientEntity.getResult()).get("data");
                if (resultNode.get("publicFeeds").isNull() || resultNode.get("publicFeeds").get("pcursor").isNull()) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                    return videoList(userId, ksid, pcursor);
                }
            } catch (Exception e) {
                if (ipPool != null) {
                    ipPool.setStatus(2);
                    iIpPoolService.updateById(ipPool);
                }
                e.printStackTrace();
                return videoList(userId, ksid, pcursor);
            }
        }
        return resultMap;
    }

    public Map<String, String> kuaishouTtf(String ttfName) {
        Map<String, String> fontMap = new HashMap<String, String>();
        try {
            URL url = new URL("https://static.yximgs.com/udata/pkg/kuaishou-front-end-live/" + ttfName);
            URLConnection urlconn = url.openConnection();
            TTFParser ttfParser = new TTFParser();
            TrueTypeFont ttf = ttfParser.parse(urlconn.getInputStream());
            GlyphData[] datas = ttf.getGlyph().getGlyphs();
            CmapSubtable[] tables = ttf.getCmap().getCmaps();
            CmapSubtable table = tables[0];

            for (int i = 0; i <= 13; i++) {
                GlyphData data = datas[i];
                if (data != null) {
                    float fx = data.getBoundingBox().getLowerLeftX();
                    float fy = data.getBoundingBox().getLowerLeftY();
                    float rx = data.getBoundingBox().getUpperRightX();
                    float ry = data.getBoundingBox().getUpperRightY();
                    Integer num = getKuaishouNumber(String.valueOf(rx - fx) + "#" + String.valueOf(ry - fy));
                    fontMap.put(String.valueOf((char) table.getCharCodes(i).get(0).intValue()), String.valueOf(num));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fontMap;
    }

    public Integer getKuaishouNumber(String key) {
        Map<String, Integer> kuaishouNumberMap = new HashMap<>();
        kuaishouNumberMap.put("494.0#735.0", 0);
        kuaishouNumberMap.put("265.0#713.0", 1);
        kuaishouNumberMap.put("495.0#719.0", 2);
        kuaishouNumberMap.put("500.0#736.0", 3);
        kuaishouNumberMap.put("510.0#718.0", 4);
        kuaishouNumberMap.put("493.0#722.0", 5);
        kuaishouNumberMap.put("491.0#737.0", 6);
        kuaishouNumberMap.put("498.0#704.0", 7);
        kuaishouNumberMap.put("492.0#738.0", 8);
        kuaishouNumberMap.put("484.0#737.0", 9);
        return kuaishouNumberMap.get(key);
    }

    @Override
    public Map<String, Object> commentDelete(String userId, String ksid, String photoId, Long commentId) {
        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<KuaishouUserCookie>();
        Map<String, Object> resultMap = new HashMap<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("ksid", ksid);
        KuaishouUserCookie kuaishouUserCookie = kuaishouUserCookieService.getOne(queryWrapper);
        if (kuaishouUserCookie != null) {
            IpPool ipPool = iIpPoolService.getAvaliableIp();
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("photoId", photoId);
            params.put("commentId", commentId);
            Map<String, String> headers = getHeaders();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            headers.put("kpn", "GAME_ZONE");
            headers.put("kpf", "PC_WEB");
            HttpClientEntity httpClientEntity = new HttpClientEntity();
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
            httpClientEntity.setUrl("https://live.kuaishou.com/rest/wd/comment/delete");
            httpClientEntity.setResult("");
            httpClientEntity.setCookieStore(cookieTransfer(kuaishouUserCookie.getCookie()));
            List<Cookie> list = httpClientEntity.getCookieStore().getCookies();
            String did = "";
            for (Cookie ck : list) {
                if ("did".equals(ck.getName())) {
                    did = ck.getValue();
                }
            }
            headers.put("Referer", "https://live.kuaishou.com/u/" + kuaishouUserCookie.getEid() + "/" + photoId + "?did=" + did);
            httpClientEntity.setHeaders(headers);
            httpClientEntity.setParams(params);

            try {
                httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
                ObjectMapper mapper = new ObjectMapper();
                resultMap = mapper.readValue(httpClientEntity.getResult(), new TypeReference<Map<String, Object>>() {
                });
                Integer code = ((Integer) resultMap.get("result"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> commentAdd(String userId, String ksid, String photoId, String content, Long replyToCommentId, Long replyTo) {
        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<KuaishouUserCookie>();
        Map<String, Object> resultMap = new HashMap<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("ksid", ksid);
        KuaishouUserCookie kuaishouUserCookie = kuaishouUserCookieService.getOne(queryWrapper);
        if (kuaishouUserCookie != null) {
            IpPool ipPool = iIpPoolService.getAvaliableIp();
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("photoId", photoId);
            params.put("principalId", kuaishouUserCookie.getEid());
            params.put("content", content);
            params.put("replyToCommentId", replyToCommentId);
            params.put("replyTo", replyTo);
            Map<String, String> headers = getHeaders();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            headers.put("kpn", "GAME_ZONE");
            headers.put("kpf", "PC_WEB");
            HttpClientEntity httpClientEntity = new HttpClientEntity();
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
            httpClientEntity.setUrl("https://live.kuaishou.com/rest/wd/photo/comment/add");
            httpClientEntity.setResult("");
            httpClientEntity.setCookieStore(cookieTransfer(kuaishouUserCookie.getCookie()));
            List<Cookie> list = httpClientEntity.getCookieStore().getCookies();
            String did = "";
            for (Cookie ck : list) {
                if ("did".equals(ck.getName())) {
                    did = ck.getValue();
                }
            }
            headers.put("Referer", "https://live.kuaishou.com/u/" + kuaishouUserCookie.getEid() + "/" + photoId + "?did=" + did);
            httpClientEntity.setHeaders(headers);
            httpClientEntity.setParams(params);
            try {
                httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
                ObjectMapper mapper = new ObjectMapper();
                resultMap = mapper.readValue(httpClientEntity.getResult(), new TypeReference<Map<String, Object>>() {
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

    private CookieStore cookieTransfer(String json) {
        CookieStore cookieStore = new BasicCookieStore();
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonNode = mapper.readTree(json);
            SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:m:s aa", Locale.ENGLISH);
            if (jsonNode != null) {
                JsonNode cookiesNode = jsonNode.get("cookies");
                if (cookiesNode != null && cookiesNode.isArray()) {
                    Iterator<JsonNode> iterator = cookiesNode.iterator();
                    while (iterator.hasNext()) {
                        JsonNode cookieNode = iterator.next();
                        BasicClientCookie basicClientCookie = new BasicClientCookie(cookieNode.get("name").asText(), cookieNode.get("value").asText());
                        if (cookieNode.has("creationDate")) {
                            basicClientCookie.setCreationDate(sdf.parse(cookieNode.get("creationDate").asText()));
                        }
                        if (cookieNode.has("cookieExpiryDate")) {
                            basicClientCookie.setExpiryDate(sdf.parse(cookieNode.get("cookieExpiryDate").asText()));
                        }
                        if (cookieNode.has("cookieVersion")) {
                            basicClientCookie.setVersion(cookieNode.get("cookieVersion").asInt());
                        }
                        if (cookieNode.has("isSecure")) {
                            basicClientCookie.setSecure(cookieNode.get("isSecure").asBoolean());
                        }
                        if (cookieNode.has("cookieDomain")) {
                            basicClientCookie.setDomain(cookieNode.get("cookieDomain").asText());
                        }
                        if (cookieNode.has("cookiePath")) {
                            basicClientCookie.setPath(cookieNode.get("cookiePath").asText());
                        }
                        cookieStore.addCookie(basicClientCookie);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cookieStore;
    }

    public void getVedioList(String principalId, String pcursor, String ttf, int times) {
        String jsonStr = "{" +
                "\"operationName\":\"publicFeedsQuery\"," +
                "\"variables\":{\"principalId\":\"" + principalId + "\",\"pcursor\":\"" + pcursor + "\",\"count\":24}," +
                "\"query\":\"query publicFeedsQuery($principalId: String, $pcursor: String, $count: Int) " +
                "{" +
                "publicFeeds(principalId: $principalId, pcursor: $pcursor, count: $count) " +
                "{    " +
                "pcursor    " +
                "live " +
                "{      " +
                "user " +
                "{        " +
                "id        " +
                "kwaiId        " +
                "eid        " +
                "profile        " +
                "name        " +
                "living        " +
                "}      " +
                "watchingCount      " +
                "src      " +
                "title      " +
                "gameId      " +
                "gameName      " +
                "categoryId      " +
                "liveStreamId      " +
                "playUrls " +
                "{        " +
                "quality        " +
                "url        " +
                "}      " +
                "followed      " +
                "type      " +
                "living      " +
                "redPack      " +
                "liveGuess      " +
                "anchorPointed      " +
                "latestViewed      " +
                "expTag      " +
                "}    " +
                "list " +
                "{      " +
                "photoId      " +
                "caption      " +
                "thumbnailUrl      " +
                "poster      " +
                "viewCount      " +
                "likeCount      " +
                "commentCount      " +
                "timestamp      " +
                "workType      " +
                "type      " +
                "useVideoPlayer      " +
                "imgUrls      " +
                "imgSizes      " +
                "magicFace      " +
                "musicName      " +
                "location      " +
                "liked      " +
                "onlyFollowerCanComment      " +
                "relativeHeight      " +
                "width      " +
                "height      " +
                "user " +
                "{        " +
                "id        " +
                "eid        " +
                "name        " +
                "profile        " +
                "}      " +
                "expTag      " +
                "}    " +
                "}" +
                "}\"" +
                "}";
        try {
            if (times > 5) {
                return;
            }
            String result = HttpUtils2.callingGraph(GRAPHQL_URL, jsonStr);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            KuaishouWebResult<KuaishouWebData> data = mapper.readValue(result, new TypeReference<KuaishouWebResult<KuaishouWebData>>() {
            });
            KuaishouPublicFeeds feeds = data.getData().getPublicFeeds();
            if (feeds.getPcursor() == null || !"no_more".equals(feeds.getPcursor())) {
                Thread.sleep((int) Math.random() * 5000 + 10000);
                getVedioList(principalId, feeds.getPcursor(), ttf, ++times);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getSecurity(String url) {
        String detectionPoint = "{\"a\":false,\"b\":true,\"c\":true,\"d\":true,\"e\":false,\"f\":false,\"g\":false,\"h\":true,\"i\":true,\"j\":false,\"k\":false,\"l\":true,\"m\":true,\"n\":true,\"o\":false,\"p\":false,\"q\":true,\"r\":false,\"s\":false,\"t\":false,\"u\":false,\"v\":false,\"w\":false,\"x\":false,\"y\":false,\"z\":true,\"aa\":false,\"bb\":false,\"cc\":false,\"dd\":false,\"ee\":false,\"ff\":false,\"gg\":false,\"hh\":false,\"ii\":false,\"jj\":false,\"kk\":false,\"ll\":false,\"mm\":false,\"nn\":false,\"oo\":false,\"pp\":1}";
        String collectInfo = "{\"a\":\"live.kuaishou.com\",\"b\":\"" + url + "\",\"c\":\"null的主页-快手直播\",\"d\":\"\",\"e\":\"" + HttpUtils2.USER_AGENT + "\",\"f\":1920,\"g\":1080,\"h\":24,\"i\":\"zh-CN\"}";
        try {
            String securityUrl = "https://live.kuaishou.com/rest/wd/live/web/security?detectionPoint=" + URLEncoder.encode(detectionPoint, "UTF-8") + "&collectInfo=" + URLEncoder.encode(collectInfo, "UTF-8");
            String html2 = HttpUtils2.httpGetRequest(securityUrl);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Value("${jeecg.path.chrome-driver}")
    private String chromeDriver;

    @Override
    public void adkuaishouWebLogin(String phone, String password) throws IOException {
        ChromeDriverService service = new ChromeDriverService.Builder().usingDriverExecutable(new File(chromeDriver)).usingAnyFreePort().build();
        service.start();
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--user-agent=" + HttpUtils2.USER_AGENT);
        chromeOptions.setAcceptInsecureCerts(true);
        WebDriver webDriver = new RemoteWebDriver(service.getUrl(), chromeOptions);
        try {

            //全局隐式等待
            webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            //设定网址
            webDriver.get("https://b.e.kuaishou.com");
            //显示等待控制对象
            WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);
            webDriverWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".phone input"))).sendKeys(phone);
            webDriverWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".password input"))).sendKeys(password);
            //点击登录
            webDriver.findElement(By.className("foot")).click();
            //等待2秒用于页面加载，保证Cookie响应全部获取。
            Thread.sleep(10000);

            webDriver.get("https://b.e.kuaishou.com/#/home/profile");
            //获取Cookie并打印
            Set<org.openqa.selenium.Cookie> cookies = webDriver.manage().getCookies();
            Iterator iterator = cookies.iterator();
            CookieStore cookieStore = new BasicCookieStore();
            String infoUrl = "https://b.e.kuaishou.com/rest/business/commentInfo/photos";
            Map<String, String> parameterMap = new HashMap<String, String>();
            parameterMap.put("pcursorMap", new Gson().toJson(new HashMap<>()));
            parameterMap.put("count", "30");
            while (iterator.hasNext()) {
                String cookieStr = iterator.next().toString();
                String[] cookieArray = cookieStr.split(";");
                Map<String, String> cookieMap = new HashMap<String, String>();
                for (String cookie : cookieArray) {
                    String[] kv = cookie.split("=");
                    if (kv.length > 1) {
                        cookieMap.put(kv[0].trim(), kv[1].trim());
                    }
                }
                BasicClientCookie clientCookie = new BasicClientCookie(cookieArray[0].split("=")[0],
                        cookieArray[0].split("=")[1]);
                clientCookie.setDomain("b.e.kuaishou.com");
                clientCookie.setPath(cookieMap.get("path"));
                HttpUtils2.cookieStore.addCookie(clientCookie);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public static void main(String[] args) {
        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
        System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
        System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");
        KuaishouWebInterfaceServiceImpl k = new KuaishouWebInterfaceServiceImpl();
        try {
            k.adekuaishouWebLogin("19845004383", "a123456");
            k.sendPreview(106126205, "xuzuoyun");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendPreview(Integer creativeId, String kwid) {
        try {
            List<Cookie> list = HttpUtils2.cookieStore.getCookies();
            String ph = null;
            if (list != null && list.size() > 0) {
                for (Cookie ck : list) {
                    if ("kuaishou.ad.dsp_ph".equals(ck.getName())) {
                        ph = ck.getValue();
                        break;
                    }
                }
            }
            List<String> userList = new ArrayList<String>();
            userList.add("xuzuoyun");
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json;charset=utf-8");
            headers.put("Referer", "https://ad.e.kuaishou.com/");
            headers.put("Host", "ad.e.kuaishou.com");
            Map<String, Object> bodys = new HashMap<>();
            bodys.put("creativeId", creativeId);
            bodys.put("userIds", userList);
            String securityUrl = "https://ad.e.kuaishou.com/rest/dsp/control-panel/creative/preview?kuaishou.ad.dsp_ph=" + ph;
            String html2 = HttpUtils2.httpPostRequest(securityUrl, bodys, headers);
            System.out.println(html2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void adekuaishouWebLogin(String phone, String password) throws IOException {
        ChromeDriverService service = new ChromeDriverService.Builder().usingDriverExecutable(new File("D:/chromedriver.exe")).usingAnyFreePort().build();
        service.start();
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--user-agent=" + HttpUtils2.USER_AGENT);
        chromeOptions.setAcceptInsecureCerts(true);
        WebDriver webDriver = new RemoteWebDriver(service.getUrl(), chromeOptions);
        try {

            //全局隐式等待
            webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            //设定网址
            webDriver.get("https://ad.e.kuaishou.com");
            //显示等待控制对象
            WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);
            webDriverWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".phone input"))).sendKeys(phone);
            webDriverWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".password input"))).sendKeys(password);
            //点击登录
            webDriver.findElement(By.className("foot")).click();
            //等待2秒用于页面加载，保证Cookie响应全部获取。
            Thread.sleep(10000);


            webDriver.get("https://ad.e.kuaishou.com/#/index");
            System.out.println(webDriver.getPageSource());
            webDriver.get("https://ad.e.kuaishou.com/#/manage?campaignId=5012466&unitId=6577717&tab=creative");
            System.out.println(webDriver.getPageSource());
            //获取Cookie并打印
            Set<org.openqa.selenium.Cookie> cookies = webDriver.manage().getCookies();
            Iterator iterator = cookies.iterator();

            while (iterator.hasNext()) {
                String cookieStr = iterator.next().toString();
                String[] cookieArray = cookieStr.split(";");
                Map<String, String> cookieMap = new HashMap<String, String>();
                for (String cookie : cookieArray) {
                    String[] kv = cookie.split("=");
                    if (kv.length > 1) {
                        cookieMap.put(kv[0].trim(), kv[1].trim());
                    }
                }
                BasicClientCookie clientCookie = new BasicClientCookie(cookieArray[0].split("=")[0],
                        cookieArray[0].split("=")[1]);
                clientCookie.setDomain("ad.e.kuaishou.com");
                clientCookie.setPath(cookieMap.get("path"));
                HttpUtils2.cookieStore.addCookie(clientCookie);
            }
            String result = HttpUtils2.httpGetRequest("https://uc.e.kuaishou.com/rest/web/login?sid=kuaishou.ad.dsp&followUrl=https%3A%2F%2Fad.e.kuaishou.com%2F%23%2Findex");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    public File captureElement(WebElement element) throws Exception {
        // TODO Auto-generated method stub
        WrapsDriver wrapsDriver = (WrapsDriver) element;
        // 截图整个页面
        File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
//        ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.)
        String tempPath = "D:/temp.png";
        FileUtils.copyFile(screen, new File(tempPath));
        BufferedImage img = ImageIO.read(new File(tempPath));
        // 获得元素的高度和宽度
        int width = element.getSize().getWidth();
        int height = element.getSize().getHeight();
//        // 创建一个矩形使用上面的高度，和宽度
        Rectangle rect = new Rectangle(width, height);
//        // 得到元素的坐标
        Point p = element.getLocation();
        BufferedImage dest = img.getSubimage(p.x, p.y, rect.width, rect.height);
        // 存为png格式
        ImageIO.write(dest, "png", screen);
        return screen;
    }

    @Override
    public void getVideoList(String uid) throws IOException {
        ChromeDriverService service = new ChromeDriverService.Builder().usingDriverExecutable(new File(chromeDriver)).usingAnyFreePort().build();
        service.start();
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--window-size=1290,1080");
        chromeOptions.addArguments("--user-agent=" + HttpUtils2.USER_AGENT);
        chromeOptions.setAcceptInsecureCerts(true);
        WebDriver webDriver = new ChromeDriver(chromeOptions);
        try {

            webDriver.get("https://live.kuaishou.com/profile/" + uid);
            Thread.sleep(2000);
            webDriver.navigate().refresh();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (org.openqa.selenium.Cookie cookie : webDriver.manage().getCookies()) {
                BasicClientCookie ck = new BasicClientCookie(cookie.getName(), cookie.getValue());
                ck.setDomain("live.kuaishou.com");
                ck.setExpiryDate(cookie.getExpiry());
                ck.setPath(cookie.getPath());
                HttpUtils2.cookieStore.addCookie(ck);
            }
            String html = webDriver.getPageSource();
            Pattern p = Pattern.compile("fontscn\\w+\\.ttf");
            Matcher m = p.matcher(html);

            String ttf = "";
            while (m.find()) {
                ttf = m.group();
            }
            Map<String, String> map = HttpUtils2.fontsMap.get(ttf);
            if (map == null) {
                HttpUtils2.kuaishouTtf(ttf);
            }
            getVedioList(uid, "", ttf, 1);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //获得cookie
            Set<org.openqa.selenium.Cookie> coo = webDriver.manage().getCookies();
            //清除所有的缓存
            webDriver.manage().deleteAllCookies();
            webDriver.quit();
            service.stop();
        }
    }

    private void setCookies() {
        HttpUtils2.cookieStore.clear();
        KuaishouWebInterfaceServiceImpl i = new KuaishouWebInterfaceServiceImpl();
        BasicClientCookie cookie = new BasicClientCookie("clientid", "3");
        //设置范围
        cookie.setDomain("live.kuaishou.com");
        cookie.setPath("/");
        cookie.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));
        HttpUtils2.cookieStore.addCookie(cookie);

        BasicClientCookie cookie1 = new BasicClientCookie("did", "web_064a1df2953c429a9770308d73d42bdb");
        //设置范围web_a5735c4f9f02ad9ee48677499927341c
        cookie1.setDomain("live.kuaishou.com");
        cookie1.setPath("/");
        cookie1.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));
        HttpUtils2.cookieStore.addCookie(cookie1);

        BasicClientCookie cookie2 = new BasicClientCookie("client_key", "65890b29");
        //设置范围
        cookie2.setDomain("live.kuaishou.com");
        cookie2.setPath("/");
        cookie2.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));
        HttpUtils2.cookieStore.addCookie(cookie2);

        BasicClientCookie cookie3 = new BasicClientCookie("kuaishou.live.bfb1s", "3e261140b0cf7444a0ba411c6f227d88");
        //设置范围
        cookie3.setDomain("live.kuaishou.com");
        cookie3.setPath("/");
        cookie3.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));
        HttpUtils2.cookieStore.addCookie(cookie3);

        BasicClientCookie cookie4 = new BasicClientCookie("didv", "1566549687000");
        //设置范围web_a5735c4f9f02ad9ee48677499927341c
        cookie4.setDomain("live.kuaishou.com");
        cookie4.setPath("/");
        cookie4.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));
        HttpUtils2.cookieStore.addCookie(cookie4);

        BasicClientCookie cookie5 = new BasicClientCookie("Hm_lvt_86a27b7db2c5c0ae37fee4a8a35033ee", "1568871207,1569462190");
        //设置范围web_a5735c4f9f02ad9ee48677499927341c
        cookie5.setDomain("live.kuaishou.com");
        cookie5.setPath("/");
        cookie5.setExpiryDate(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 365));
        HttpUtils2.cookieStore.addCookie(cookie5);
    }

    @Override
    public String checkKuaishouUser(String videoUrl) {
        String html = HttpUtils2.httpGetRequest(videoUrl);
        HttpUtils2.cookieStore.clear();
        Pattern p = Pattern.compile("/profile/(\\w+)\"");
        Matcher m = p.matcher(html);
        String uid = "";

        while (m.find()) {
            uid = m.group().replace("/profile/", "").replace("\"", "");
            if (uid != null && !"".equals(uid) && !"null".equals(uid)) {
                return uid;
            }
        }
        return null;
    }

    public void deleteCommentById(Long photoId, Long commentId, Map<String, String> headers) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("photoId", photoId);
            params.put("commentId", commentId);
            params.put("principalUserId", 0);
            String str = HttpUtils2.httpPostRequest("https://b.e.kuaishou.com/rest/kd/ad/comment/deleteV2", params, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode node = mapper.readTree(str);
            Integer result = node.get("result").asInt();
            if (result == 1) {
                log.info("删除成功=>photoId:{},commentId:{}", photoId, commentId);
            } else {
                log.info("删除失败=>photoId:{},commentId:{}", photoId, commentId);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deletePhotoComment(Long photoId, String pcursor, Map<String, String> headers) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("photoId", photoId);
            params.put("pcursor", pcursor);
            String str = HttpUtils2.httpPostRequest("https://b.e.kuaishou.com/rest/kd/ad/comment/list", params, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode node = mapper.readTree(str);
            Integer result = node.get("result").asInt();
            pcursor = node.get("pcursor").asText();
            if (result == 1) {
                Iterator<JsonNode> nodes = node.get("rootComments").iterator();
                while (nodes.hasNext()) {
                    JsonNode commentNode = nodes.next();
                    Long commentId = commentNode.get("comment_id").asLong();
                    deleteCommentById(photoId, commentId, headers);
                }
                if (pcursor != null && !"no_more".equals(pcursor)) {
                    deletePhotoComment(photoId, pcursor, headers);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteAllComment(Map<String, String> pcursorMap) {
        try {
            Map<String, String> headers = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            headers.put("Origin", "https://b.e.kuaishou.com");
            headers.put("Referer", "https://b.e.kuaishou.com/");
            headers.put("Host", "b.e.kuaishou.com");
            headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
            params.put("pcursorMap", pcursorMap);
            params.put("count", 30);
            String str = HttpUtils2.httpPostRequest("https://b.e.kuaishou.com/rest/business/commentInfo/photos", params, headers);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode node = mapper.readTree(str);
            Integer result = node.get("result").asInt();
            String pcursor = node.get("pcursor").asText();
            if (result == 1) {
                Iterator<JsonNode> nodes = node.get("photos").iterator();
                while (nodes.hasNext()) {
                    JsonNode photoNode = nodes.next();
                    Long photoId = photoNode.get("photoId").asLong();
                    deletePhotoComment(photoId, "", headers);
                }
                if (pcursor != null && !"no_more".equals(pcursor)) {
                    pcursorMap = mapper.readValue(node.get("pcursorMap").toString(), new TypeReference<Map<String, String>>() {
                    });
                    deleteAllComment(pcursorMap);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0");
        headers.put("Accept", "application/json, text/plain, */*");
        headers.put("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2");
        headers.put("Accept-Encoding", "gzip, deflate, br");
        headers.put("Referer", "https://live.kuaishou.com/");
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Origin", "https://live.kuaishou.com");
        headers.put("Connection", "keep-alive");
        return headers;
    }

    public HttpClientEntity kuaishouQrCallback(HttpClientEntity httpClientEntity, String qrToken) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("qrToken", qrToken);
        params.put("sid", "kuaishou.live.web");
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(null));
        httpClientEntity.setUrl("https://id.kuaishou.com/pass/kuaishou/login/qr/callback");
        httpClientEntity.setResult("");
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(params);
        httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
        return httpClientEntity;
    }

    public HttpClientEntity kuaishouQrAcceptResult(HttpClientEntity httpClientEntity, String qrLoginToken, String qrLoginSignature, Long ksid) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("qrLoginSignature", qrLoginSignature);
        params.put("sid", "kuaishou.live.web");
        params.put("qrLoginToken", qrLoginToken);
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(null));
        httpClientEntity.setUrl("https://id.kuaishou.com/rest/c/infra/ks/qr/acceptResult");
        httpClientEntity.setResult("");
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(params);
        httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
        return httpClientEntity;
    }

    public HttpClientEntity kuaishouQrScanResult(HttpClientEntity httpClientEntity, String qrLoginToken, String qrLoginSignature) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("qrLoginSignature", qrLoginSignature);
        params.put("qrLoginToken", qrLoginToken);
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(null));
        httpClientEntity.setUrl("https://id.kuaishou.com/rest/c/infra/ks/qr/scanResult");
        httpClientEntity.setResult("");
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(params);
        httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
        return httpClientEntity;
    }

    public HttpClientEntity kuaishouQrStart(HttpClientEntity httpClientEntity) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sid", "kuaishou.live.web");
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(null));
        httpClientEntity.setUrl("https://id.kuaishou.com/rest/c/infra/ks/qr/start");
        httpClientEntity.setResult("");
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(params);
        httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
        return httpClientEntity;
    }

    public HttpClientEntity reLogin(HttpClientEntity httpClientEntity, KuaishouUserCookie kuaishouUserCookie) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();
        IpPool ipPool = iIpPoolService.getAvaliableIp();
        params.put("sid", "kuaishou.live.web");
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
        httpClientEntity.setUrl("https://id.kuaishou.com/pass/kuaishou/login/passToken");
        httpClientEntity.setResult("");
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(params);
        httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(httpClientEntity.getResult());
        String at = jsonNode.get("kuaishou.live.web.at").asText();
        httpClientEntity.setUrl("https://live.kuaishou.com/graphql");
        httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, userLogin(at));
        httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, userInfoQuery());
        JsonNode userNode = mapper.readTree(httpClientEntity.getResult());
        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", kuaishouUserCookie.getUserId());
        queryWrapper.eq("ksid", kuaishouUserCookie.getKsid());
        kuaishouUserCookie.setCookie(new Gson().toJson(httpClientEntity.getCookieStore()));
        kuaishouUserCookieService.update(kuaishouUserCookie, queryWrapper);
        return httpClientEntity;
    }

    public Date getCST(String strGMT) throws ParseException {
        if (strGMT == null) {
            return null;
        }
        DateFormat df = new SimpleDateFormat("MMM d, yyyy H:m:s aaa", Locale.ENGLISH);
        return df.parse(strGMT);

    }

    public HttpClientEntity kuaishouIndex() throws Exception {
        HttpClientEntity httpClientEntity = new HttpClientEntity();
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(null));
        httpClientEntity.setHeaders(getHeaders());
        httpClientEntity.setParams(new HashMap<>());
        httpClientEntity.setUrl("https://live.kuaishou.com/rest/wd/live/web/log");
        httpClientEntity = httpClientUtils.httpPostParamRequest(httpClientEntity);
        httpClientEntity.setUrl("https://live.kuaishou.com");
        httpClientEntity.setResult("");
        httpClientEntity = httpClientUtils.httpGetRequest(httpClientEntity);
        return httpClientEntity;
    }


    @Override
    public String qrLogin(String taskId) throws Exception {
        HttpClientEntity httpClientEntity = this.kuaishouIndex();
        httpClientEntity = this.kuaishouQrStart(httpClientEntity);
        HttpClientUtils httpClientUtils = new HttpClientUtils();
        String result = httpClientEntity.getResult();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        KuaishouQrStartVO kuaishouQrStartVO = mapper.readValue(result, KuaishouQrStartVO.class);
        final HttpClientEntity finalHttpClientEntity = httpClientEntity;
        if (kuaishouQrStartVO.getResult() == 1) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    HttpClientEntity threadHttpClientEntity = null;
                    KuaishouUserVO kuaishouUserVO = null;
                    KuaishouAcceptVO kuaishouAcceptVO = null;
                    try {
                        threadHttpClientEntity = kuaishouQrScanResult(finalHttpClientEntity, kuaishouQrStartVO.getQrLoginToken(), kuaishouQrStartVO.getQrLoginSignature());
                        String res = threadHttpClientEntity.getResult();
                        JsonNode jsonNode = mapper.readTree(res);
                        Integer resultCode = jsonNode.get("result").asInt();
                        if (resultCode == 1) {
                            Map<String, Object> loginStatusMap = new HashMap<String, Object>();
                            loginStatusMap.put("status", 2);
                            loginStatusMap.put("msg", "扫码成功，请在手机确认登陆");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                            kuaishouUserVO = mapper.readValue(jsonNode.get("user").toString(), KuaishouUserVO.class);
                        } else {
                            Map<String, Object> loginStatusMap = new HashMap<String, Object>();
                            loginStatusMap.put("status", -101);
                            loginStatusMap.put("msg", "二维码已过期，请重新获取");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Map<String, Object> loginStatusMap = new HashMap<String, Object>();
                        loginStatusMap.put("status", -100);
                        loginStatusMap.put("msg", "服务异常,请重新获取二维码");
                        redisUtil.set(taskId, loginStatusMap, 60000);
                        return;
                    }

                    try {
                        threadHttpClientEntity = kuaishouQrAcceptResult(threadHttpClientEntity, kuaishouQrStartVO.getQrLoginToken(), kuaishouQrStartVO.getQrLoginSignature(), kuaishouUserVO.getUserId());
                        kuaishouAcceptVO = mapper.readValue(threadHttpClientEntity.getResult(), KuaishouAcceptVO.class);
                        if (kuaishouAcceptVO.getResult() == 1) {
                            Map<String, Object> loginStatusMap = new HashMap<String, Object>();
                            loginStatusMap.put("status", 3);
                            loginStatusMap.put("msg", "授权登陆成功");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                        } else {
                            Map<String, Object> loginStatusMap = new HashMap<String, Object>();
                            loginStatusMap.put("status", -101);
                            loginStatusMap.put("msg", "二维码已过期，请重新获取");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Map<String, Object> loginStatusMap = new HashMap<String, Object>();
                        loginStatusMap.put("status", -100);
                        loginStatusMap.put("msg", "服务异常,请重新获取二维码");
                        redisUtil.set(taskId, loginStatusMap, 60000);
                        return;
                    }
                    try {
                        threadHttpClientEntity = kuaishouQrCallback(threadHttpClientEntity, kuaishouAcceptVO.getQrToken());
                        JsonNode jsonNode = mapper.readTree(threadHttpClientEntity.getResult());
                        String at = jsonNode.get("kuaishou.live.web.at").asText();
                        threadHttpClientEntity.setUrl("https://live.kuaishou.com/graphql");
                        threadHttpClientEntity = httpClientUtils.callingGraph(threadHttpClientEntity, userLogin(at));
                        threadHttpClientEntity = httpClientUtils.callingGraph(threadHttpClientEntity, userInfoQuery());
                        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("user_id", user.getId());
                        queryWrapper.eq("ksid", kuaishouUserVO.getUserId());
                        KuaishouUserCookie kuaishouUserCookie = kuaishouUserCookieService.getOne(queryWrapper);
                        if (kuaishouUserCookie == null) {
                            kuaishouUserCookie = new KuaishouUserCookie();
                            kuaishouUserCookie.setCookie(new Gson().toJson(threadHttpClientEntity.getCookieStore()));
                            kuaishouUserCookie.setKsid(String.valueOf(kuaishouUserVO.getUserId()));
                            kuaishouUserCookie.setEid(kuaishouUserVO.getEid());
                            kuaishouUserCookie.setUserName(kuaishouUserVO.getUserName());
                            kuaishouUserCookie.setUserId(user.getId());
                            kuaishouUserCookieService.save(kuaishouUserCookie);
                        } else {
                            kuaishouUserCookie.setCookie(new Gson().toJson(threadHttpClientEntity.getCookieStore()));
                            kuaishouUserCookie.setUserName(kuaishouUserVO.getUserName());
                            kuaishouUserCookieService.update(kuaishouUserCookie, queryWrapper);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            };
            thread.start();
            Map<String, Object> loginStatusMap = new HashMap<String, Object>();
            loginStatusMap.put("status", 1);
            loginStatusMap.put("msg", "请使用快手APP扫描二维码");
            redisUtil.set(taskId, loginStatusMap, 60000);
            return kuaishouQrStartVO.getImageData();
        } else {
            throw new Exception();
        }
    }

    @Override
    public Map<String, Object> loginStatus(String taskId) {
        Map<String, Object> loginStatusMap = (Map<String, Object>) redisUtil.get(taskId);
        return loginStatusMap;
    }
}
