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

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.entity.HttpClientEntity;
import cn.com.ctop.common.module.entity.IpPool;
import cn.com.ctop.common.module.service.IBindAccountLoginService;
import cn.com.ctop.common.module.service.IIpPoolService;
import cn.com.ctop.common.module.utils.Base64Utils;
import cn.com.ctop.common.module.utils.ChaojiyingUtils;
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.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.alibaba.fastjson.JSONObject;
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.*;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeDriverService;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
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.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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 IKuaishouUserCookieService kuaishouUserCookieService;
    @Autowired
    private IIpPoolService iIpPoolService;
    @Autowired
    private IBindAccountLoginService  bindAccountLoginService;
    @Autowired
    private RedisUtil redisUtil;
    private static final String GRAPHQL_URL = "https://live.kuaishou.com/graphql";
    private static final String KUAISHOU_BE_DOMAIN_HTTPS= "https://b.e.kuaishou.com";
    private static final String KUAISHOU_BE_DOMAIN= "b.e.kuaishou.com";

    @Value("${jeecg.path.kuaishou-account-captcha-image}")
    private String kuaishouAccountCaptchaImage;


    private String userInfoQuery() {
        return  "{\"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\"}";
    }

    private String userLogin(String qrToken) {
        return  "{\"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\"}";
    }

    private String subCommentListQuery(String photoId, Long rootCommentId, String pcursor) {
        return  "{\"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\"}";
    }

    private String commentListQuery(String photoId, String pcursor) {
        return  "{\"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\"}";
    }

    private String videoFeeds(String principalId, String pcursor) {
        return "{\"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\"}";
    }

    @Override
    public Map<String, Object> subCommentList(String userId, String ksid, String photoId, Long rootCommentId, String pcursor) {
        QueryWrapper<KuaishouUserCookie> queryWrapper = new QueryWrapper<>();
        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<>();
            HttpClientEntity httpClientEntity = new HttpClientEntity();
            HttpClientUtils httpClientUtils = new HttpClientUtils();
            httpClientEntity.setCloseableHttpClient(httpClientUtils.createSSLClientDefault(ipPool));
            httpClientEntity.setUrl(GRAPHQL_URL);
            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<>();
        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<>();
            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(GRAPHQL_URL);
                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<>();
        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<>();
            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(GRAPHQL_URL);
            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<>();
        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<>();
        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<>();
            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<>();
        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<>();
            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() * 5000L + 10000);
                getVedioList(principalId, feeds.getPcursor(), ttf, ++times);
            }
        } catch (Exception 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(KUAISHOU_BE_DOMAIN_HTTPS);
            //显示等待控制对象
            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);

//            WebElement iframeElement = webDriver.findElement(By.tagName("iframe"));
//            if (iframeElement != null) {
//                log.error("【错误】快手登录出现验证码！");
//                File scrFile = captureElement(webDriver.findElement(By.tagName("iframe")));
//                //clickCharBg
//                String savePath = "D:/capter.png";
//                FileUtils.copyFile(scrFile, new File(savePath));
//                webDriver.switchTo().frame(webDriver.findElement(By.tagName("iframe")));
//                String result = ChaojiyingUtils.process(Base64Utils.imageToBase64(savePath));
//                ((JavascriptExecutor) webDriver).executeScript("arguments[0].click();", webDriver.findElement(By.className("aq_icon_refresh")));
//            }
            webDriver.get("https://b.e.kuaishou.com/#/home/profile");
            //获取Cookie并打印
            Set<org.openqa.selenium.Cookie> cookies = webDriver.manage().getCookies();
            Iterator iterator = cookies.iterator();
            Map<String, String> parameterMap = new HashMap<>();
            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<>();
                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 {
        }
    }

    private WebElement webDriverGetElement(WebDriver webDriver, By by){
        try {
            return webDriver.findElement(by);
        }catch (NoSuchElementException e){
            return null;
        }
    }

    public File captureElement(WebElement element) throws Exception {
        WrapsDriver wrapsDriver = (WrapsDriver) element;
        // 截图整个页面
        File screen = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screen, new File(kuaishouAccountCaptchaImage));
        BufferedImage img = ImageIO.read(new File(kuaishouAccountCaptchaImage));
        // 获得元素的高度和宽度
        int width = element.getSize().getWidth();
        int height = element.getSize().getHeight();
        // 得到元素的坐标
        Point p = element.getLocation();
        BufferedImage dest = img.getSubimage(p.x, p.y, width, height);
        // 存为png格式
        ImageIO.write(dest, "png", screen);
        return screen;
    }

    @Override
    public void getkuaishouWebLoginCookie(BindAccountLogin login){
        System.setProperty("webdriver.chrome.driver", chromeDriver);
        ChromeDriverService service = new ChromeDriverService.Builder().usingDriverExecutable(new File(chromeDriver)).usingAnyFreePort().build();
        try {
            service.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        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(KUAISHOU_BE_DOMAIN_HTTPS);
            //显示等待控制对象
            WebDriverWait webDriverWait = new WebDriverWait(webDriver, 10);
            webDriverWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".phone input"))).sendKeys(login.getAccountName());
            webDriverWait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".password input"))).sendKeys(login.getPassword());
            //点击登录
            webDriver.findElement(By.className("foot")).click();
            //等待2秒用于页面加载，保证Cookie响应全部获取。
            Thread.sleep(1000);
            if (null!=webDriverGetElement(webDriver,By.tagName("iframe"))) {
                log.error("【错误】快手登录出现验证码！");
                File scrFile = captureElement(webDriver.findElement(By.tagName("iframe")));
                //clickCharBg
                FileUtils.copyFile(scrFile, new File(kuaishouAccountCaptchaImage));
                String result = ChaojiyingUtils.process(Base64Utils.imageToBase64(kuaishouAccountCaptchaImage),9104);
                String pointString = JSONObject.parseObject(result).getString("pic_str");
                String[] split = pointString.split("\\|");
                if(split.length>0){
                    for(int i=0;i<split.length;i++){
                        String pointStr = split[i];
                        String [] taps = pointStr.split(",");
                        tapPoint(webDriver,Integer.parseInt(taps[0]),Integer.parseInt(taps[1]));
                    }
                }
                webDriver.switchTo().frame(webDriver.findElement(By.tagName("iframe")));
                webDriver.findElement(By.xpath("//div[@class='opArea']/span[@id='submit']")).click();
            }
            Thread.sleep(3000L);

            webDriver.get("https://b.e.kuaishou.com/#/home/profile");
            //获取Cookie并打印
            Set<org.openqa.selenium.Cookie> cookies = webDriver.manage().getCookies();
            List<String> cookieList = new ArrayList<>();
            Iterator iterator = cookies.iterator();
            while (iterator.hasNext()) {
                String cookieStr = iterator.next().toString();
                cookieList.add(cookieStr);
            }
            login.setCookie(new Gson().toJson(cookieList));
            login.setUpdateTime(new Date());
            bindAccountLoginService.updateById(login);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webDriver.close();
            webDriver.quit();
        }
    }

    private void tapPoint(WebDriver driver, Integer x, Integer y) {
        WebElement element = driver.findElement(By.tagName("iframe"));
        Actions actions = new Actions(driver);
        actions.moveToElement(element,x,y).click().perform();
        try {
            Thread.sleep(500L);
        } catch (InterruptedException 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.isEmpty()) {
                for (Cookie ck : list) {
                    if ("kuaishou.ad.dsp_ph".equals(ck.getName())) {
                        ph = ck.getValue();
                        break;
                    }
                }
            }
            List<String> userList = new ArrayList<>();
            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);
        } 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");
            webDriver.get("https://ad.e.kuaishou.com/#/manage?campaignId=5012466&unitId=6577717&tab=creative");
            //获取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<>();
                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);
            }
            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");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    @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();
            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 {
            //清除所有的缓存
            webDriver.manage().deleteAllCookies();
            webDriver.quit();
            service.stop();
        }
    }

    @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 deleteCommentById(Long photoId, Long commentId, Map<String, String> headers,CookieStore cookieStore) {
        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,cookieStore);
            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();
        }
    }

    public void deletePhotoComment(Long photoId, String pcursor, Map<String, String> headers,CookieStore cookieStore) {
        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,cookieStore);
            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,cookieStore);
                }
                if (pcursor != null && !"no_more".equals(pcursor)) {
                    deletePhotoComment(photoId, pcursor, headers,cookieStore);
                }
            }
        } 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", KUAISHOU_BE_DOMAIN_HTTPS);
            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();
            JsonNode pcursoNode = node.get("pcursor");
            if (null == pcursoNode) {
                log.info("异常数据：{}", str);
            }
            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();
        }
    }

    @Override
    public void deleteAllComment(Map<String,String>pcursorMap,BindAccountLogin login) {
        try {
            CookieStore cookieStore = bindAccountLoginService.setCookie(login,KUAISHOU_BE_DOMAIN);
            if(null == cookieStore){
                log.error("快手账号cookie异常=>account:{},loginId:{}",login.getAccountName(),login.getId());
                return;
            }
            Map<String, String> headers = new HashMap<>();
            Map<String, Object> params = new HashMap<>();
            headers.put("Origin", KUAISHOU_BE_DOMAIN_HTTPS);
            headers.put("Referer", "https://b.e.kuaishou.com/");
            headers.put("Host", KUAISHOU_BE_DOMAIN);
            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,cookieStore);
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode node = mapper.readTree(str);
            Integer result = node.get("result").asInt();
            JsonNode pcursoNode = node.get("pcursor");
            if(result == 109){
                login.setCookie("");
                bindAccountLoginService.updateById(login);
                log.info("cookie失效=>accountName:{},password:{}",login.getAccountName(),login.getPassword());
                return;
            }
            if (null == pcursoNode) {
                log.info("accountName:{},password:{}",login.getAccountName(),login.getPassword());
                log.info("异常数据：{}", str);
                return;
            }
            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,cookieStore);
                }
                if (pcursor != null && !"no_more".equals(pcursor)) {
                    pcursorMap = mapper.readValue(node.get("pcursorMap").toString(), new TypeReference<Map<String, String>>() {
                    });
                    deleteAllComment(pcursorMap,login);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, String> getHeaders() {
        Map<String, String> headers = new HashMap<>();
        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<>();
        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<>();
        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<>();
        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<>();
        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<>();
        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(GRAPHQL_URL);
        httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, userLogin(at));
        httpClientEntity = httpClientUtils.callingGraph(httpClientEntity, userInfoQuery());
        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<>();
                            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<>();
                            loginStatusMap.put("status", -101);
                            loginStatusMap.put("msg", "二维码已过期，请重新获取");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Map<String, Object> loginStatusMap = new HashMap<>();
                        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<>();
                            loginStatusMap.put("status", 3);
                            loginStatusMap.put("msg", "授权登陆成功");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                        } else {
                            Map<String, Object> loginStatusMap = new HashMap<>();
                            loginStatusMap.put("status", -101);
                            loginStatusMap.put("msg", "二维码已过期，请重新获取");
                            redisUtil.set(taskId, loginStatusMap, 60000);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Map<String, Object> loginStatusMap = new HashMap<>();
                        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(GRAPHQL_URL);
                        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<>();
            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) {
        return  (Map<String, Object>) redisUtil.get(taskId);
    }
}
