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

import cn.com.ctop.common.module.utils.Base64Utils;
import cn.com.ctop.common.module.utils.ChaojiyingUtils;
import cn.com.ctop.common.module.utils.HttpUtils2;
import cn.com.ctop.kuaishou.modules.report.entity.KuaiShouDailyAgent;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouAgentAccount;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAgent;
import cn.com.ctop.kuaishou.modules.report.entity.KuaishouReportDailyAgentSum;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaiShouDailyAgentMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouAgentAccountMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyAgentMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportDailyAgentSumMapper;
import cn.com.ctop.kuaishou.modules.report.service.IKuaishouReportDailyAgentService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.jeecg.common.util.DateUtils;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 代理商日报
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-12-13
 */
@Slf4j
@Service
public class KuaishouReportDailyAgentServiceImpl extends ServiceImpl<KuaishouReportDailyAgentMapper, KuaishouReportDailyAgent> implements IKuaishouReportDailyAgentService {
    @Autowired
    private KuaiShouDailyAgentMapper kuaiShouDailyAgentMapper;
    @Autowired
    private KuaishouReportDailyAgentSumMapper kuaishouReportDailyAgentSumMapper;
    @Autowired
    private KuaishouReportDailyAgentMapper kuaishouReportDailyAgentMapper;
    @Autowired
    private KuaishouAgentAccountMapper kuaishouAgentAccountMapper;
    @Value("${jeecg.path.chrome-driver}")
    private String chromeDriver;
    @Value("${jeecg.path.kuaishou-agent-image}")
    private String kuaishouAgentImage;

    @Override
    public void replaceBatch(List<KuaiShouDailyAgent> list) {
        for (KuaiShouDailyAgent agent:list) {
            kuaiShouDailyAgentMapper.insert(agent);
        }
    }

    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 boolean loginAgent() {
        boolean loginStatus = false;
        System.getProperties().setProperty("webdriver.chrome.driver", chromeDriver);
        String url = "https://agent.e.kuaishou.com";
        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.addArguments("--headless");
//        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        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("//div[contains(@class,'component-input-container')]/input[@type='text']"));
            accountElement.sendKeys("17718376864");
            Thread.sleep(3000L);
            WebElement passwordElement = webDriver.findElement(By.xpath("//div[contains(@class,'component-input-container')]/input[@type='password']"));
            passwordElement.sendKeys("yehcbost85567");
            WebElement loginElement = webDriver.findElement(By.xpath("//div[@class='btn-container']/button[contains(@class,'submit')]"));
            Thread.sleep(3000L);
            //点击登录
            loginElement.click();
            Thread.sleep(3000L);
            if (null!=webDriverGetElement(webDriver,By.tagName("iframe"))) {
                log.error("【错误】快手登录出现验证码！");
                File scrFile = captureElement(webDriver.findElement(By.tagName("iframe")));
                //clickCharBg
                FileUtils.copyFile(scrFile, new File(kuaishouAgentImage));
                String result = ChaojiyingUtils.process(Base64Utils.imageToBase64(kuaishouAgentImage),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://agent.e.kuaishou.com/#/index");
            Thread.sleep(3000L);
            Set<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("agent.e.kuaishou.com");
                clientCookie.setPath(cookieMap.get("path"));
                HttpUtils2.cookieStore.addCookie(clientCookie);
            }
            loginStatus = true;
        } catch (Exception e) {
            e.printStackTrace();
            loginStatus = false;
        } finally {
            webDriver.manage().deleteAllCookies();
            webDriver.quit();
        }
        return loginStatus;
    }

    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(kuaishouAgentImage));
        BufferedImage img = ImageIO.read(new File(kuaishouAgentImage));
        // 获得元素的高度和宽度
        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 boolean getAccount(int currentPage) {
        boolean hasNextPage = false;
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Accept", "application/json");
            headerMap.put("Accept-Encoding", "gzip, deflate, br");
            headerMap.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");
            headerMap.put("Connection", "keep-alive");
            headerMap.put("Host", "agent.e.kuaishou.com");
            headerMap.put("Referer", "https://agent.e.kuaishou.com/");
            headerMap.put("Content-Type", "application/json;charset=utf-8");
            headerMap.put("User-Agent", HttpUtils2.USER_AGENT);
            String postData = "{\"pageInfo\":{\"currentPage\":" + currentPage + ",\"pageSize\":200,\"total\":1000},\"reviewStatus\":\"-1\",\"selectType\":1,\"selectValue\":\"\",\"createBeginTime\":0,\"createEndTime\":0}";
            String listUrl = "https://agent.e.kuaishou.com/rest/dsp/agent/account/list";
            String result = HttpUtils2.httpPostRequestTest(listUrl, postData, headerMap);
            System.out.println(result);
            ObjectMapper mapper = new ObjectMapper();
            mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            JsonNode resultNode = mapper.readTree(result);
            Integer code = resultNode.get("result").intValue();
            if (code == 1) {
                Iterator<JsonNode> iterator1 = resultNode.get("adDspAccountList").elements();
                int i = 0;
                List<KuaishouAgentAccount> accountList = new ArrayList<>();
                while (iterator1.hasNext()) {
                    hasNextPage = true;
                    JsonNode dataNode = iterator1.next();
                    KuaishouAgentAccount agentAccount = mapper.readValue(dataNode.toString(), KuaishouAgentAccount.class);
                    agentAccount.setBalance(agentAccount.getBalance().divide(new BigDecimal(1000)));
                    agentAccount.setContractRebate(agentAccount.getContractRebate().divide(new BigDecimal(1000)));
                    agentAccount.setCreditBalance(agentAccount.getCreditBalance().divide(new BigDecimal(1000)));
                    agentAccount.setDirectRebate(agentAccount.getDirectRebate().divide(new BigDecimal(1000)));
                    agentAccount.setExtendedBalance(agentAccount.getExtendedBalance().divide(new BigDecimal(1000)));
                    agentAccount.setKuaibiBalance(agentAccount.getKuaibiBalance().divide(new BigDecimal(1000)));
                    agentAccount.setPreRebate(agentAccount.getPreRebate().divide(new BigDecimal(1000)));
                    agentAccount.setPushBalance(agentAccount.getPushBalance().divide(new BigDecimal(1000)));
                    agentAccount.setRebate(agentAccount.getRebate().divide(new BigDecimal(1000)));
                    agentAccount.setTotalBalance(agentAccount.getTotalBalance().divide(new BigDecimal(1000)));
                    accountList.add(agentAccount);
                }
                if (!accountList.isEmpty()) {
                    kuaishouAgentAccountMapper.replaceBatch(accountList);
                }
            }

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

    @Override
    public void getReport(String startDate, String endDate) {
        try {
            String currentDate = startDate;
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("Accept", "application/json");
            headerMap.put("Accept-Encoding", "gzip, deflate, br");
            headerMap.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");
            headerMap.put("Connection", "keep-alive");
            headerMap.put("Host", "agent.e.kuaishou.com");
            headerMap.put("Referer", "https://agent.e.kuaishou.com/");
            headerMap.put("Content-Type", "application/json;charset=utf-8");
            headerMap.put("User-Agent", HttpUtils2.USER_AGENT);
            while (DateUtils.compareDate(currentDate, endDate) <= 0) {
                //{"agentId":403756224,"startDate":"2020-03-05","endDate":"2020-03-05","sortKey":"","isAscending":false,"pageInfo":{"pageSize":19,"currentPage":1,"totalCount":100}}
                String listUrl = "https://agent.e.kuaishou.com/rest/dsp/agent/account/data/list";
                String postData = "{\"agentId\":403756224,\"startDate\":\"" + currentDate + "\",\"endDate\":\"" + currentDate + "\",\"isAscending\":false,\"pageInfo\":{\"pageSize\":19,\"currentPage\":1,\"totalCount\":999999}}";
                String result = HttpUtils2.httpPostRequestTest(listUrl, postData, headerMap);
                ObjectMapper mapper = new ObjectMapper();
                JsonNode resultNode = mapper.readTree(result);
                Integer code = resultNode.get("result").intValue();
                if (code == 1) {
                    Iterator<JsonNode> iterator1 = resultNode.get("data").elements();
                    int i = 0;
                    List<KuaiShouDailyAgent> reportList = new ArrayList<>();
                    while (iterator1.hasNext()) {
                        JsonNode dataNode = iterator1.next();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        if (i == 0) {
                            KuaishouReportDailyAgentSum kuaishouReportDailyAgentSum = new KuaishouReportDailyAgentSum();
                            kuaishouReportDailyAgentSum.setBalance(dataNode.get("totalBalanceDouble").decimalValue());
                            kuaishouReportDailyAgentSum.setConvertClickRate(dataNode.get("actionbarClickRatio").decimalValue());
                            kuaishouReportDailyAgentSum.setConvertCount(dataNode.get("actionbarClick").asLong());
                            kuaishouReportDailyAgentSum.setCost(dataNode.get("totalChargedInYuan").decimalValue());
                            kuaishouReportDailyAgentSum.setCostCampaignCount(dataNode.get("chargedCampaignCount").asLong());
                            kuaishouReportDailyAgentSum.setDate(currentDate);
                            kuaishouReportDailyAgentSum.setFengmianClickCount(dataNode.get("adPhotoClick").asLong());
                            kuaishouReportDailyAgentSum.setFengmianClickRate(dataNode.get("clickRatio").decimalValue());
                            kuaishouReportDailyAgentSum.setFengmianShowCount(dataNode.get("impression").asLong());
                            kuaishouReportDailyAgentSum.setFandianCost(dataNode.get("rebateRealChargedInYuan").decimalValue());
                            kuaishouReportDailyAgentSum.setJiliCost(dataNode.get("directRebateRealChargedInYuan").decimalValue());
                            kuaishouReportDailyAgentSum.setKuangfanCost(dataNode.get("contractRebateRealChargedInYuan").decimalValue());
                            kuaishouReportDailyAgentSum.setSucaiShowCount(dataNode.get("click").asLong());
                            kuaishouReportDailyAgentSum.setXianjinCost(dataNode.get("realChargedInYuan").decimalValue());
                            kuaishouReportDailyAgentSum.setXinyongCost(dataNode.get("creditRealChargedInYuan").decimalValue());
                            QueryWrapper<KuaishouReportDailyAgentSum> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("date", currentDate);
                            kuaishouReportDailyAgentSumMapper.delete(queryWrapper);
                            kuaishouReportDailyAgentSumMapper.insert(kuaishouReportDailyAgentSum);
                        } else {
                            KuaiShouDailyAgent kuaishouReportDailyAgent = new KuaiShouDailyAgent();
                            kuaishouReportDailyAgent.setAccountId(dataNode.get("accountId").asLong());
//                            kuaishouReportDailyAgent.setAdvertiserCreateTime(new Date(dataNode.get("createTime").asLong()));
                            kuaishouReportDailyAgent.setAccountName(dataNode.get("accountName").asText());
                            kuaishouReportDailyAgent.setTotalBalanceInYuan(dataNode.get("totalBalanceDouble").decimalValue());
                            // kuaishouReportDailyAgent.setConvertClickRate(dataNode.get("actionbarClickRatio").decimalValue());
                            kuaishouReportDailyAgent.setAdItemClick(dataNode.get("actionbarClick").asLong());
                            kuaishouReportDailyAgent.setTotalChargedInYuan(dataNode.get("totalChargedInYuan").decimalValue());
                            kuaishouReportDailyAgent.setChargedCampaignCount(dataNode.get("chargedCampaignCount").asLong());
                            kuaishouReportDailyAgent.setDateTime(dataNode.get("dateTime").asText());
                            kuaishouReportDailyAgent.setAdPhotoClick(dataNode.get("adPhotoClick").asLong());
                            kuaishouReportDailyAgent.setPhotoClickRatio(dataNode.get("clickRatio").asText());
                            kuaishouReportDailyAgent.setAdPhotoImpression(dataNode.get("impression").asLong());
                            kuaishouReportDailyAgent.setTotalRebateRealChargedInYuan(dataNode.get("rebateRealChargedInYuan").decimalValue());
                            kuaishouReportDailyAgent.setDirectRebateRealChargedInYuan(dataNode.get("directRebateRealChargedInYuan").decimalValue());
                            //猜测可能是agentId
                            kuaishouReportDailyAgent.setAgentId(14L);
                            kuaishouReportDailyAgent.setContractRebateRealChargedInYuan(dataNode.get("contractRebateRealChargedInYuan").decimalValue());
                            kuaishouReportDailyAgent.setAdItemImpression(dataNode.get("click").asLong());
                            kuaishouReportDailyAgent.setRealChargedInYuan(dataNode.get("realChargedInYuan").decimalValue());
                            kuaishouReportDailyAgent.setCreditRealChargedInYuan(dataNode.get("creditRealChargedInYuan").decimalValue());
                            reportList.add(kuaishouReportDailyAgent);
                        }
                        i++;
                    }
                    if (!reportList.isEmpty()) {
                        replaceBatch(reportList);
                    }
                }

                log.info("代理商日报:{}入库完成", currentDate);
                currentDate = DateUtils.addDay(currentDate, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
