package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.mapper.BindAccountLoginMapper;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.crawler.modules.core.util.FateadmHttpUtil;
import cn.com.ctop.crawler.modules.core.util.FateadmUtil;
import cn.com.ctop.crawler.modules.pangolin.service.PangolinCrawlerService;
import cn.com.ctop.crawler.modules.pangolin.service.PangolinLoginService;
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.http.impl.cookie.BasicClientCookie;
import org.jeecg.modules.ctop.service.ICreateInternalService;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author jeecg-boot
 */
@Slf4j
@Service
public class CreateInternalServiceImpl implements ICreateInternalService {
    @Value("${jeecg.path.chrome-driver}")
    private String chromeDriver;
    @Autowired
    private BindAccountLoginMapper bindAccountLoginMapper;
    @Autowired
    private PangolinLoginService pangolinLoginService;
    @Autowired
    private PangolinCrawlerService pangolinCrawlerService;

    @Override
    public Map<String, Object> bindLogin(Long projectId,String advertiserId, String accountName, String password, String loginType, String userId, String advertiserName) {
        Map<String, Object> returnMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("advertiser_id", advertiserId);
        requestMap.put("account_name", accountName);
        requestMap.put("login_type", loginType);
        requestMap.put("user_id", userId);
        requestMap.put("project_id", projectId);
        bindAccountLoginMapper.deleteByMap(requestMap);
        String accountId = "";
        //头条登录
        if (null != loginType && loginType.equals(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_PY)) {
            Map<String, Object> result = this.checkAccountPassword(accountName, password);
            Boolean checkSuccess = (Boolean) result.get("success");
            if (Boolean.FALSE.equals(checkSuccess)) {
                returnMap.put("success", false);
                returnMap.put("message", "账号验证失败");
                return returnMap;
            }
            accountId = (String) result.get("id");
        }
        BindAccountLogin bindAccountLogin = new BindAccountLogin();
        bindAccountLogin.setAdvertiserId(advertiserId);
        bindAccountLogin.setAccountName(accountName);
        bindAccountLogin.setPassword(password);
        bindAccountLogin.setAccountId(accountId);
        bindAccountLogin.setLoginType(loginType);
        bindAccountLogin.setProjectId(projectId);
        bindAccountLogin.setUserId(userId);
        int i = bindAccountLoginMapper.insert(bindAccountLogin);
        if (i > 0) {
            log.info("登录账号绑定成功，广告主id:{}", bindAccountLogin.getAdvertiserId());
            if(null!=loginType&&loginType.equals(CtopAdConstant.PLATFORM_TYPE_PANGOLIN_PY)){
                //穿山甲账户绑定
                Thread thread = new Thread(){
                    @Override
                    public void run() {
                        //1:登录
                        pangolinLoginService.pangolinLogin(bindAccountLogin.getAccountName(), bindAccountLogin.getPassword());
                        //2:拉取数据
                        pangolinCrawlerService.getNowData(bindAccountLogin);
                    }
                };
                thread.start();
            }

            returnMap.put("success", true);
            returnMap.put("accountUd", password);
        }
        return returnMap;
    }

    @Override
    public Map<String, Object> checkAccountPassword(String account, String password) {
        Map<String, Object> resultMap = new HashMap<>();
        //selenium打开登录页面
        String url = "https://ad.oceanengine.com/pages/login/index.html";
        System.getProperties().setProperty("webdriver.chrome.driver", chromeDriver);
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--user-agent=" + HttpUtils2.USER_AGENT);
        chromeOptions.setAcceptInsecureCerts(true);
        WebDriver webDriver = new ChromeDriver(chromeOptions);
        //清除所有的缓存
        webDriver.manage().deleteAllCookies();
        try {
            //获取登录页面
            webDriver.get(url);
            for (Cookie cookie : webDriver.manage().getCookies()) {
                BasicClientCookie ck = new BasicClientCookie(cookie.getName(), cookie.getValue());
                ck.setDomain("ad.oceanengine.com");
                ck.setExpiryDate(cookie.getExpiry());
                ck.setPath(cookie.getPath());
                HttpUtils2.cookieStore.addCookie(ck);
            }
            Map<String, String> header = new HashMap<>();
            header.put("Accept", "*/*");
            header.put("Connection", "keep-alive");
            header.put("Host", "sso.toutiao.com");
            header.put("Content-Type", "application/x-www-form-urlencoded");
            header.put("Origin", "https://ad.oceanengine.com");
            header.put("Referer", "https://ad.oceanengine.com/pages/login/index.html");
            Map<String, Object> param = new HashMap<>();
            param.put("mobile", "");
            param.put("code", "");
            param.put("account", account);
            param.put("password", password);
            param.put("captcha", "hqde");
            param.put("is_30_days_no_login", "true");
            param.put("service", "https://ad.oceanengine.com");
            String res = HttpUtils2.httpPostParamRequest("https://sso.toutiao.com/account_login/", param, header);

            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            JsonNode jsonNode = mapper.readTree(res);
            //errorcode == 1102 验证码错误，请重新输入验证码
            //errorcode == 1101 验证码为空

            Integer errorCode = jsonNode.get("error_code").asInt();
            String orderId = null;
            while (errorCode != 0) {
                //用户名或者密码错误
                if (null != errorCode && errorCode == 1009) {
                    ResultMapUtils.setResultMap(resultMap, StatusCode.USERNAME_OR_PASSWORD_ERROR.getCode());
                    return resultMap;
                }
                FateadmUtil fateadmUtil = new FateadmUtil();
                fateadmUtil.init();
                if (orderId != null) {
                    fateadmUtil.justice(orderId);
                }
                String captcha = jsonNode.get("captcha").asText();
                Base64.Decoder decoder = Base64.getDecoder();
                FateadmHttpUtil.HttpResp resp = fateadmUtil.Predict("30400", decoder.decode(captcha));
                param.put("captcha", resp.predResl);
                orderId = resp.reqId;
                res = HttpUtils2.httpPostParamRequest("https://sso.toutiao.com/account_login/", param, header);
                jsonNode = mapper.readTree(res);
                errorCode = jsonNode.get("error_code").asInt();
            }
            if (errorCode == 0) {
                //表示登录成功
                List<org.apache.http.cookie.Cookie> cookies = HttpUtils2.cookieStore.getCookies();
                for (org.apache.http.cookie.Cookie ck : cookies) {
                    Cookie cookie = new Cookie(ck.getName(), ck.getValue(), "." + ck.getDomain(), ck.getPath(), ck.getExpiryDate());
                    webDriver.manage().addCookie(cookie);
                }
                //登录成功 进入推广页面
                webDriver.get("https://ad.oceanengine.com/pages/promotion.html#/ad");
                Thread.sleep(3000);
                WebElement element = webDriver.findElement(By.xpath("//div[contains(@class,'-user-account-id')] "));
                if (null != element) {
                    ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
                    String text = element.getText();
                    text = text.replace("ID：", "").trim();
                    resultMap.put("id", text);
                } else {
                    ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SERVER_ERROR.getCode());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SERVER_ERROR.getCode());
        } finally {
            //清除所有的缓存
            webDriver.manage().deleteAllCookies();
            webDriver.quit();
        }
        return resultMap;
    }
}
