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

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.utils.ChaojiyingUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.HttpUtils2;
import cn.com.ctop.crawler.modules.taobao.service.TaobaoJhsbybtService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.*;

@Service
public class TaobaoJhsbybtServiceImpl implements TaobaoJhsbybtService {

    //

    public void taobaoLogin(String username, String password) {
        System.getProperties().setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");
        String url = "https://login.m.taobao.com/login.htm?redirectURL=https%3A%2F%2Fmarket.m.taobao.com%2Fapp%2Ftmall-def%2Fjhsbybt%2Fweb%2Findex.html%3FdisableNav%3DYES%26itemIds%3D612103514690%26spm%3D608.14027681%2F8.bubbles.d1";
        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--incognito");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--user-agent=" + HttpUtils2.USER_AGENT);
        chromeOptions.setAcceptInsecureCerts(true);
        WebDriver webDriver = new ChromeDriver(chromeOptions);
        try {
            Thread.sleep(3000L);
            HttpUtils2.cookieStore = new BasicCookieStore();
            webDriver.manage().deleteAllCookies();
            //获取登录页面
            webDriver.get(url);
            Thread.sleep(3000L);
            WebElement accountElement = webDriver.findElement(By.xpath("//input[@id='fm-login-id']"));
            accountElement.sendKeys(username);
            Thread.sleep(3000L);
            WebElement passwordElement = webDriver.findElement(By.xpath("//input[@id='fm-login-password']"));
            passwordElement.sendKeys(password);
            WebElement loginElement = webDriver.findElement(By.xpath("//button[contains(@class, 'password-login')]"));

            Thread.sleep(3000L);
            //点击登录
            loginElement.click();
            Thread.sleep(30000L);
//            webDriver.get("https://market.m.taobao.com/app/tmall-def/jhsbybt/web/index.html?disableNav=YES&itemIds=612103514690&spm=608.14027681/8.bubbles.d1");
//            Thread.sleep(3000L);

            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);
                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("h5api.m.taobao.com");
                clientCookie.setPath(cookieMap.get("path"));
                HttpUtils.COOKIESTORE.addCookie(clientCookie);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            webDriver.manage().deleteAllCookies();
            webDriver.quit();
        }
    }
    public String getGoodsList(int page) {
        String url = "https://h5api.m.taobao.com/h5/mtop.tmall.kangaroo.core.service.route.aldlampservicefixedres/1.0/";
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("jsv", "2.5.1");
        paramMap.put("appKey", "12574478");
        paramMap.put("t", new Date().getTime());
        paramMap.put("sign", "56b679fe3a6de0cd4ffa8ccb8680ff83");
        paramMap.put("timeout", 3000);
        paramMap.put("api", "mtop.tmall.kangaroo.core.service.route.AldLampServiceFixedRes");
        paramMap.put("params", "[object Object]");
        paramMap.put("dataType", "jsonp");
        paramMap.put("v", "1.0");
        paramMap.put("preventFallback", true);
        paramMap.put("type", "jsonp");
        paramMap.put("callback", "mtopjsonp8");
//        paramMap.put("data", "{\"curPageUrl\":\"https%3A%2F%2Fmarket.m.taobao.com%2Fapp%2Ftmall-def%2Fjhsbybt%2Fweb%2Findex.html%3FdisableNav%3DYES%26itemIds%3D617136337387%26spm%3D608.14027681%2F8.bubbles.d0\",\"resId\":\"8613423\",\"pageSize\":20,\"params\":\"{\\\"backupParams\\\":\\\"frontCatId,page\\\",\\\"bizId\\\":\\\"2022\\\",\\\"resId\\\":\\\"8613423\\\",\\\"pageSize\\\":20,\\\"frontCatId\\\":\\\"jingxuan\\\",\\\"page\\\":" + page + ",\\\"query\\\":\\\"\\\",\\\"itemIds\\\":\\\"613480362477,570133944073,622530871392,617136337387\\\"}\",\"appId\":\"8613423\",\"backupParams\":\"\",\"pvuuid\":\"v1-93bed822-738b-4e5e-95df-ad2790b8662c-1596698955217\",\"__pvuuid\":\"v1-93bed822-738b-4e5e-95df-ad2790b8662c-1596698955217\",\"_pvuuid\":\"v1-93bed822-738b-4e5e-95df-ad2790b8662c-1596698955217\"}");
        paramMap.put("data","{\"curPageUrl\":\"https%3A%2F%2Fmarket.m.taobao.com%2Fapp%2Ftmall-def%2Fjhsbybt%2Fweb%2Findex.html%3FdisableNav%3DYES%26itemIds%3D612103514690%26spm%3D608.14027681%2F8.bubbles.d1\",\"resId\":\"8613423\",\"page\":8,\"pageSize\":20,\"frontCatId\":\"jingxuan\",\"params\":\"{\\\"backupParams\\\":\\\"frontCatId,page\\\",\\\"bizId\\\":\\\"2022\\\",\\\"resId\\\":\\\"8613423\\\",\\\"pageSize\\\":20,\\\"frontCatId\\\":\\\"jingxuan\\\",\\\"page\\\":"+page+",\\\"query\\\":\\\"\\\",\\\"itemIds\\\":\\\"629862883564,614729874362,561776220152,612103514690\\\"}\",\"appId\":\"8613423\",\"backupParams\":\"frontCatId,page\",\"pvuuid\":\"v1-75c838ed-831a-46b8-bd23-209f3a3ffac7-1603178690614\",\"__pvuuid\":\"v1-75c838ed-831a-46b8-bd23-209f3a3ffac7-1603178690614\",\"_pvuuid\":\"v1-75c838ed-831a-46b8-bd23-209f3a3ffac7-1603178690614\"}");
        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("Accept-Encoding", "gzip, deflate, br");
        headerMap.put("Connection", "keep-alive");
        headerMap.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36");
        headerMap.put("Accept", "*/*");
        headerMap.put("Content-Type", "application/xml");
        headerMap.put("Referer", "https://market.m.taobao.com/app/tmall-def/jhsbybt/web/index.html?disableNav=YES&itemIds=617136337387&spm=608.14027681/8.bubbles.d0");
        String result = HttpUtils.httpGet(url, paramMap, headerMap);
//        System.out.println(result);
        List<Cookie> cookieList = HttpUtils.COOKIESTORE.getCookies();
        String token = "";
//        String cookie = "thw=cn; cna=2jRxF89E7RMCAW/OVs5+932u; isg=BJKSQfRQGaNpFmS_jB4l8pW64Fh0o5Y9f1i8aVzrvMQzbzJpRDOITZmB203TBA7V; l=eBNE6xhVQt2n4kW1BO5CEurza77O3IR48kPzaNbMiInca6tOTFmf8NQ42SQJ7dtfgt5xEetPOc4qydEWy5a38jkDBeYIi8nBhZ968e1..; tfstk=cd-cBFNuJE7bsM0PvmsXd492jUlRad0VGh-y43mdqLoFfJ8PUsA8zyo7GYfxE041.; sgcookie=E100un01dqE6Xqf7RmvaIBPTwbgJJ9z0gY%2B8KCl7ywFbgyNt4yt%2BPnZ21ch4hlR7ODNOdHex1mp%2Bd9THatgb3rg9fA%3D%3D; tracknick=%5Cu6D41%5Cu884C%5Cu4E4B%5Cu9053; _cc_=URm48syIZQ%3D%3D; enc=q6VFK5GjOoxL7swcMR7wex9p0yY%2ByNF510fwKJqaAcE5yQEz4xYB6enkQjYaTOaNrTWirRk8%2FsIT2a5p2mLSUg%3D%3D; hng=CN%7Czh-CN%7CCNY%7C156; miid=1872523487506667185; um=G9D5F5C791D277E12EEC1C2C0D47D9C6A12AAC8; UM_distinctid=173085824ce448-0ad778ac1a2557-4c302c7d-144000-173085824cf166; t=1a7debb83b628491430bd4377a57ccf5; _m_h5_tk=41f0856f968fa869b160f2278056e2f1_1603188360687; _m_h5_tk_enc=11cdc71625467ec734e33bc8c2c7f512; _tb_token_=30bd68e616368";
        String cookie = "";
        for (Cookie ck : cookieList) {
            if ("_m_h5_tk".equals(ck.getName())) {
                token = ck.getValue().split("_")[0];
            }
            cookie = cookie + ck.getName() + "=" + ck.getValue() + ";";
        }
        String sign = DigestUtils.md5Hex(token + "&" + paramMap.get("t") + "&" + paramMap.get("appKey") + "&" + paramMap.get("data"));
        paramMap.put("sign", sign);
        headerMap.put("Cookie", cookie);
//        System.out.println(cookie);
//        System.out.println(sign);
        result = HttpUtils.httpGet(url, paramMap, headerMap);
//        System.out.println(result);
        return result;
    }

    public static void main(String[] args) {
        try {
            PrintStream out = new PrintStream("D:/bybt1208.csv");
            System.setOut(out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        Boolean hasMore = true;
        System.out.println("商品id,商品名,销量,商品logo,设计图,商品图,商品链接,正常价,,,补贴价,补贴券");

        TaobaoJhsbybtServiceImpl tb = new TaobaoJhsbybtServiceImpl();
//        tb.taobaoLogin("流行之道","xzy19890417");
        tb.taobaoLogin("m228419161","cxq121119..");
        int i = 1;
        while (hasMore) {
            try {
                String result = tb.getGoodsList(i);
                result = result.replace("mtopjsonp8(", "");
                result = result.substring(0, result.length() - 1);
                ObjectMapper mapper = new ObjectMapper();
                JsonNode rootNode = mapper.readTree(result);
//                System.out.println(HttpUtils.COOKIESTORE.toString());
//                System.out.println(result);
                Boolean success = rootNode.get("data").get("resultValue").get("8613423").get("success").asBoolean();
                while (!success) {
                    Thread.sleep(3000L);
                    result = tb.getGoodsList(i);
                    result = result.replace("mtopjsonp2(", "");
                    result = result.substring(0, result.length() - 1);
                    mapper = new ObjectMapper();
                    rootNode = mapper.readTree(result);
                    success = rootNode.get("data").get("resultValue").get("8613423").get("success").asBoolean();
                }
                hasMore = rootNode.get("data").get("resultValue").get("8613423").get("data").get("hasMore").asBoolean();
                Iterator<JsonNode> items = rootNode.get("data").get("resultValue").get("8613423").get("data").get("items").iterator();
                while (items.hasNext()) {
                    JsonNode itemNode = items.next();
                    String cjmsItemName = itemNode.get("cjmsItemName").asText();
                    String itemSoldInfo = itemNode.get("itemSoldInfo").asText();
                    String picUrl = itemNode.get("picUrl").asText();
                    String cjmsTaobaoEntrance = itemNode.get("cjmsTaobaoEntrance").asText();
                    String couponAmount = itemNode.get("couponAmount").asText();
                    String orgPrice = itemNode.get("orgPrice").asText();
                    String brandLogo = itemNode.get("brandLogo").asText();
                    String couponPrice = itemNode.get("couponPrice").asText();
                    String actPrice = itemNode.get("actPrice").asText();
                    String cutPrice = itemNode.get("cutPrice").asText();
                    String itemUrl = itemNode.get("itemUrl").asText();
                    String itemId = itemNode.get("itemId").asText();
                    System.out.println(itemId+","+cjmsItemName+","+
                            itemSoldInfo+","+
                            brandLogo+","+
                            picUrl+","+
                            cjmsTaobaoEntrance+","+
                            itemUrl+","+
                            actPrice+","+
                            cutPrice+","+
                            orgPrice+","+
                            couponPrice+","+
                            couponAmount);
                }
                i++;

            } catch (Exception e) {
                e.printStackTrace();
            }
//            try {
//                Thread.sleep(10000L);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }

    }
}
