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

import cn.com.ctop.common.module.utils.HttpUtils2;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.crawler.modules.appium.entity.*;
import cn.com.ctop.crawler.modules.appium.mapper.AppiumJobMapper;
import cn.com.ctop.crawler.modules.appium.mapper.AppiumTaskItemMapper;
import cn.com.ctop.crawler.modules.appium.mapper.AppiumTaskLogMapper;
import cn.com.ctop.crawler.modules.appium.mapper.AppiumTaskMapper;
import cn.com.ctop.crawler.modules.appium.service.IAppiumDeviceService;
import cn.com.ctop.crawler.modules.appium.service.IAppiumJobService;
import cn.com.ctop.crawler.modules.appium.service.IAppiumTaskService;
import cn.com.ctop.crawler.modules.core.util.AppiumUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.appium.java_client.android.AndroidDriver;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.BasicCookieStore;
import org.openqa.selenium.By;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 爬虫调度任务
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-11-14
 */
@Slf4j
@Service
public class AppiumJobServiceImpl extends ServiceImpl<AppiumJobMapper, AppiumJob> implements IAppiumJobService {
    @Autowired
    private AppiumTaskMapper taskMapper;
    @Autowired
    private AppiumTaskItemMapper taskItemMapper;
    @Value("${jeecg.path.chrome-driver}")
    private String chromeDriver;
    @Autowired
    private IAppiumDeviceService appiumDeviceService;
    @Autowired
    private AppiumTaskLogMapper appiumTaskLogMapper;

    @Override
    public String loginTask(Long taskId, AppiumDevice device) {
        String kuaishouId = null;
        try {
            AppiumTask task = taskMapper.selectById(taskId);
            AppiumUtil appiumUtil = new AppiumUtil();
            AndroidDriver androidDriver = appiumUtil.initAndroidDriver("http://39.106.184.70:4723/wd/hub", device.getIp() + ":" + device.getPort(), task.getAppPackage(), task.getAppActivity());
            Map<String, Object> result = new HashMap<>();
            ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_CRAWLER_APP_SUCCESS.getCode());
            boolean loop = true;
            while (loop) {
                Integer code = (Integer) result.get("code");
                if (null != code && code != StatusCode.KUAISHOU_CRAWLER_APP_SUCCESS.getCode()) {
                    kuaishouId = (String) result.get("kuaishouId");
                    androidDriver.quit();
                    break;
                }
                Thread.sleep(3000L);
                String packageName = androidDriver.getCurrentPackage();
                String activityName = androidDriver.currentActivity();
                System.out.println(packageName + ":" + activityName);
                List<AppiumTaskItem> taskItems = taskItemMapper.selectByParams(packageName, activityName, taskId);
                if (null != taskItems || taskItems.size() > 0) {
                    for (AppiumTaskItem item : taskItems) {
                        result = appiumUtil.runLoginTask(androidDriver, item, result);
                    }
                }
                result = appiumUtil.checkMethod(androidDriver, activityName, result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(kuaishouId);
        return kuaishouId;
    }

    @Override
    public boolean bindCreative(String account, String password, String creativeName, String ksId) {
        boolean isBind = false;
        String url = "https://ad.e.kuaishou.com/#/welcome?redirectUrl=https%3A%2F%2Fad.e.kuaishou.com%2F%23%2Findex";
        System.getProperties().setProperty("webdriver.chrome.driver", chromeDriver);
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--incognito");
        chromeOptions.addArguments("--disable-gpu");
//        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);
        try {
            Thread.sleep(3000L);
            HttpUtils2.cookieStore = new BasicCookieStore();
            webDriver.manage().deleteAllCookies();
            //获取登录页面
            webDriver.get(url);
            Thread.sleep(3000L);
            WebElement accountElement = webDriver.findElement(By.xpath("//div[@class='phone ']/input[@type='text']"));
            accountElement.sendKeys(account);
            Thread.sleep(3000L);
            WebElement passwordElement = webDriver.findElement(By.xpath("//div[@class='password ']/input[@type='password']"));
            passwordElement.sendKeys(password);
            WebElement loginElement = webDriver.findElement(By.xpath("//div[@class='foot']"));
            Thread.sleep(3000L);
            //点击登录
            loginElement.click();
            Thread.sleep(3000L);
            //获取推广按钮
            WebElement spreadElement = webDriver.findElement(By.linkText("推广"));
            spreadElement.click();
            Thread.sleep(3000L);
            //选择广告创意
            WebElement creativeElement = webDriver.findElement(By.xpath("//div[text()='广告创意']"));
            creativeElement.click();
            Thread.sleep(3000L);
            //输入创意名称，点击搜索
            WebElement searchElement = webDriver.findElement(By.xpath("//input[@type='text']"));
            searchElement.sendKeys(creativeName);
            Thread.sleep(3000L);
            WebElement searchButton = webDriver.findElement(By.xpath("//button[@class='ant-btn ant-input-search-button ant-btn-primary']"));
            searchButton.click();
            Thread.sleep(3000L);
            WebElement tiyanElement = webDriver.findElement(By.linkText("体验"));
            tiyanElement.click();
            Thread.sleep(2000L);
            WebElement inputKsIdElement = webDriver.findElement(By.xpath("//textarea[@placeholder='请输入快手账号…']"));
            inputKsIdElement.sendKeys(ksId);
            Thread.sleep(2000L);
            WebElement chufaElement = webDriver.findElement(By.xpath("//button[@class='creative-experience-btn-enable']"));
            chufaElement.click();
            isBind = true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("绑定体验快手账号失败");
            isBind = false;
        } finally {
            webDriver.manage().deleteAllCookies();
            webDriver.close();
        }
        return isBind;
    }

    @Autowired
    private IAppiumTaskService appiumTaskService;

    @Override
    public boolean refreshWebPhone() {
        boolean success = false;
        String url = "https://lcloud.longene.com.cn/";
        System.getProperties().setProperty("webdriver.chrome.driver", chromeDriver);
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("--incognito");
        chromeOptions.addArguments("--disable-gpu");
//        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);
        try {
            Thread.sleep(3000L);
            HttpUtils2.cookieStore = new BasicCookieStore();
            webDriver.manage().deleteAllCookies();
            //获取登录页面
            webDriver.get(url);
            Thread.sleep(3000L);
            WebElement accountElement = webDriver.findElement(By.id("username"));
            accountElement.sendKeys("18600471989");
            Thread.sleep(3000L);
            WebElement passwordElement = webDriver.findElement(By.id("userpwd"));
            passwordElement.sendKeys("0759125184xu");
            WebElement loginElement = webDriver.findElement(By.xpath("//input[@class='quc-submit quc-button quc-button-primary quc-button-sign-in']"));
            Thread.sleep(3000L);
            //点击登录
            loginElement.click();
            Thread.sleep(3000L);
            //选择华东二站
            WebElement spreadElement = webDriver.findElement(By.xpath("//a[@href='javascript:gotobranch(2)']"));
            spreadElement.click();
            Thread.sleep(3000L);
            //
            webDriver.get("https://ecsite.longene.com.cn/userWeb!batchipswitch?ids=4293&groupid=8729&mode=5&ipbind=0&region=0&ipareas=");
            Thread.sleep(5000L);
            webDriver.get("https://ecsite.longene.com.cn/userWeb!batchnewphone?groupid=8729&pkgnames=com.smile.gifmaker&ids=4293");
            Thread.sleep(5000L);
            success = true;
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
            log.error("一键新机操作失败");
        } finally {
            webDriver.manage().deleteAllCookies();
            webDriver.close();
        }
        return success;
    }

    @Override
    public void updateStatus(AppiumDevice appiumDevice, AppiumTaskLog log, Integer logStatus, Integer deviceStatus) {
        log.setStatus(logStatus + "");
        appiumTaskLogMapper.updateById(log);
        appiumDevice.setStatus(deviceStatus);
        appiumDeviceService.updateById(appiumDevice);
    }
}
