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

import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.BindAccountLoginMapper;
import cn.com.ctop.common.module.service.IBindAccountLoginService;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.service.IFileInfoService;
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.toutiao.entity.ByteDanceUserOrientationTemplate;
import cn.com.ctop.toutiao.entity.BytedanceCreativeLaunchTemplate;
import cn.com.ctop.toutiao.entity.BytedanceUrlInfo;
import cn.com.ctop.toutiao.mapper.ByteDanceUserOrientationTemplateMapper;
import cn.com.ctop.toutiao.mapper.BytedanceCreativeLaunchTemplateMapper;
import cn.com.ctop.toutiao.mapper.BytedanceUrlInfoMapper;
import cn.com.ctop.toutiao.service.IByteDanceAdvertiserDataService;
import cn.com.ctop.toutiao.service.IByteDanceCreativeService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.client.BasicCookieStore;
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 IBindAccountLoginService bindAccountLoginService;
    @Autowired
    private BindAccountLoginMapper bindAccountLoginMapper;

    @Autowired
    private BytedanceUrlInfoMapper urlInfoMapper;

    @Override
    public Map<String, Object> bindLogin(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);
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("advertiser_id", advertiserId);
        deleteMap.put("account_name", accountName);
        deleteMap.put("login_type", loginType);
        deleteMap.put("user_id", userId);
        bindAccountLoginMapper.deleteByMap(deleteMap);
        List<BindAccountLogin> bindAccounts = bindAccountLoginMapper.selectByMap(requestMap);
        if (!Check.isNull(bindAccounts)) {
            returnMap.put("success", false);
            returnMap.put("message", "账号已存在");
            return returnMap;
        }
        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 (!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.setUserId(userId);
        int i = bindAccountLoginMapper.insert(bindAccountLogin);
        if (i > 0) {
            log.info("登录账号绑定成功，广告主id:{}", bindAccountLogin.getAdvertiserId());
            returnMap.put("success", true);
            returnMap.put("accountUd", password);
            return returnMap;
        }
        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.pred_resl);
                orderId = resp.req_id;
                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) {
            e.printStackTrace();
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SERVER_ERROR.getCode());
        } finally {
            //获得cookie
            Set<Cookie> coo = webDriver.manage().getCookies();
            //清除所有的缓存
            webDriver.manage().deleteAllCookies();
            webDriver.quit();
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> createInternal(JSONObject requestJson) {
        Map<String, Object> resultMap = new HashMap<>();
        //1:获取用户名密码
        Long accountId = requestJson.getLong("accountId");
        Long userOrientationId = requestJson.getLong("userOrientationId");
        String campaignId = requestJson.getString("campaignId");
        BindAccountLogin bindAccountLogin = bindAccountLoginService.selectByAccountId(accountId + "");
        if (null == bindAccountLogin) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.ACCOUNT_HAS_NOT_EXIST.getCode());
            return resultMap;
        }
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        if (null == token) {
            ResultMapUtils.setResultMap(resultMap, StatusCode.ACCOUNT_HAS_NOT_EXIST.getCode());
            return resultMap;
        }
        JSONObject wordsObject = fileInfoService.getCreativeWord(token, token.getAccountId());
        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);
        try {
            HttpUtils2.cookieStore = new BasicCookieStore();
            webDriver.manage().deleteAllCookies();
            //获取登录页面
            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<String, String>();
            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", bindAccountLogin.getAccountName());
            param.put("password", bindAccountLogin.getPassword());
            param.put("captcha", "hqde");
            param.put("is_30_days_no_login", "false");
            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);
            Integer errorCode = jsonNode.get("error_code").asInt();
            //用户名或者密码错误
            if (null != errorCode && errorCode == 1009) {
                ResultMapUtils.setResultMap(resultMap, StatusCode.USERNAME_OR_PASSWORD_ERROR.getCode());
                return resultMap;
            }
            String orderId = null;
            while (errorCode != 0) {
                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.pred_resl);
                orderId = resp.req_id;
                res = HttpUtils2.httpPostParamRequest("https://sso.toutiao.com/account_login/", param, header);
                jsonNode = mapper.readTree(res);
                errorCode = jsonNode.get("error_code").asInt();
            }
            if (errorCode == 0) {
                String csrftoken = "";
                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);
                String templateName = requestJson.getString("templateName");
                String uuid = UUID.randomUUID().toString();

                //创建广告组页面
                webDriver.get("https://ad.oceanengine.com/pages/campaign/create.html");
                Map<String, Object> campaignParam = new HashMap<>();
                campaignParam.put("campaign_id", "");
                campaignParam.put("campaign_name", templateName + "-广告组-" + uuid.substring(1, 7));
                campaignParam.put("landing_type", 3);
                campaignParam.put("campaign_type", 1);
                Map<String, Object> budgetMap = new HashMap<>();
                budgetMap.put("budget", 0);
                budgetMap.put("budget_mode", -1);
                campaignParam.put("budget", budgetMap);
                for (Cookie cookie : webDriver.manage().getCookies()) {
                    if ("csrftoken".equals(cookie.getName())) {
                        csrftoken = cookie.getValue();
                    }
                    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);
                }

                header.put("Accept", "application/json, text/javascript, */*; q=0.01");
                header.put("Connection", "keep-alive");
                header.put("Host", "ad.oceanengine.com");
                header.put("Content-Type", "application/json");
                header.put("Origin", "https://ad.oceanengine.com");
                header.put("X-CSRFToken", csrftoken);
                header.put("X-Requested-With", "XMLHttpRequest");
                header.put("Referer", "https://ad.oceanengine.com/pages/promotion.html");
                    // 创建广告组返回信息
                if (null == campaignId || "".equals(campaignId.trim())) {
                    res = HttpUtils2.httpPostRequest("https://ad.oceanengine.com/overture/campaign/create/", campaignParam, header);
                    JsonNode node = mapper.readTree(res);
                    campaignId = node.get("data").get("campaign_id").asText();
                }

                Integer itratorNum = requestJson.getInteger("itratorNum");
                JSONObject data = new JSONObject();
                if (null != itratorNum && itratorNum > 0) {
                    //循环创建广告计划
                    for (int i = 0; i < itratorNum; i++) {
                        //广告组id
                        String url2 = "https://ad.oceanengine.com/pages/ad/create.html?campaign_id=" + campaignId + "&landing_type=3&temp_id=ADvQb";
                        webDriver.get(url2);

                        header.put("Referer", url2);
                        for (Cookie cookie : webDriver.manage().getCookies()) {
                            if ("csrftoken".equals(cookie.getName())) {
                                csrftoken = cookie.getValue();
                            }
                            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);
                        }
                        header.put("X-CSRFToken", csrftoken);
                        Map<String, Object> audienceParam = new HashMap<>();
                        audienceParam.put("location_type", 4);
                        audienceParam.put("aweme_account_fans", 0);
                        String tokenStr = HttpUtils2.httpPostRequest("https://ad.oceanengine.com/api/v1/hl/ad/audience/estimate/", audienceParam, header);
                        JsonNode tokenNode = mapper.readTree(tokenStr);
                        Map<String, Object> planParam = new HashMap<>();
                        //模板名称
                        planParam.put("name", templateName + "-广告计划-" + uuid.substring(1, 7) + i);
                        Integer deliveryRange = requestJson.getInteger("deliveryRange");
                        //投放形式
                        planParam.put("delivery_range", deliveryRange);
                        if (deliveryRange == 2) {
                            //投放形式 1：激励视频 2：原生
                            planParam.put("union_video_type", requestJson.getInteger("deliveryForm"));
                        }
                        planParam.put("projectid", "");
                        Integer downloadType = requestJson.getInteger("downloadType");
                        //下载方式  1：下载包 2：h5
                        planParam.put("download_type", downloadType);
                        Long urlId = requestJson.getLong("urlId");
                        BytedanceUrlInfo urlInfo = urlInfoMapper.selectById(urlId);
                        if (downloadType == 1) {
                            planParam.put("download_url", urlInfo.getUrl());
                            planParam.put("package", urlInfo.getPackageName());
                        }
                        if (downloadType == 2) {
                            // 落地页链接
                            planParam.put("external_url", urlInfo.getUrl());
                        }
                        //广告类别  5 内广
                        planParam.put("classify", 5);
                        planParam.put("projectid", "");
                        planParam.put("localGeolocation", new ArrayList<String>());
                        //应用直达链接
                        planParam.put("open_url", "");
                        planParam.put("style_type", 0);
                        //受众位置类型
                        planParam.put("location_type", 4);
                        // 过滤已安装，当推广目标为安卓应用下载时可填，0表示不过滤，1表示过滤，默认为不过滤
                        planParam.put("hide_if_exists", 0);
                        //兴趣分类
                        planParam.put("interest_tag_mode", 0);
                        planParam.put("token", tokenNode.get("data").get("token").asText());
                        //头条预估数据
                        planParam.put("toutiao", 100000005);
                        //抖音预估数据
                        planParam.put("aweme", 150000005);
                        //西瓜预估数据
                        planParam.put("video_app", 40000005);
                        //火山预估数据
                        planParam.put("hotsoon", 40000005);
                        //账号粉丝相似人群
                        planParam.put("aweme_account_fans", 0);
                        // 智能放量？？？？
                        planParam.put("auto_extend_enabled", 0);
                        // 广告预算类型  0 日预算  1 总预算
                        planParam.put("budget_mode", requestJson.getIntValue("budgetPriceMode"));
                        //广告预算
                        planParam.put("budget", requestJson.getIntValue("budgetPrice"));
                        int scheduleType = requestJson.getIntValue("dateQuantum");
                        //广告投放时间类型   默认1 1：不限  2：按时间？？？
                        planParam.put("schedule_type", scheduleType);
                        if (scheduleType == 2) {
                            //广告投放起始时间
                            planParam.put("start_time", requestJson.getString("startDate"));
                            //广告投放结束时间
                            planParam.put("end_time", requestJson.getString("endDate"));
                        }
                        //投放时段
                        planParam.put("week_schedule", new ArrayList<String>());
                        //投放时段
                        planParam.put("week_time", new ArrayList<ArrayList<Integer>>());
                        int pricing = requestJson.getIntValue("pricing");
                        //计划出价类型  9 按展示付费  7 按点击付费 8 按转化付费
                        planParam.put("pricing", pricing);
                        //出价为OCPC时，计划处于哪个阶段??
                        planParam.put("cpa_phrase", 2);
                        planParam.put("is_union_slot", "");
                        //过滤已转化用户类型字段，只有转化为目标时可填 优化目标为转化才展示
                        planParam.put("hide_if_converted", 1);
                        //投放速度/投放方式使用字段
                        planParam.put("flow_control_mode", requestJson.getIntValue("flowControlMode"));
                        if (pricing == 9) {
                            planParam.put("cpa_bid", requestJson.getIntValue("convertPrice"));
                        } else {
                            planParam.put("bid", requestJson.getIntValue("convertPrice"));
                        }
                        //自动出价类型，OCPM支持
                        planParam.put("smart_bid_type", requestJson.getIntValue("bidType"));
                        //是否调整自动出价   允许值: "0", "1"  默认值: 0
                        planParam.put("adjust_cpa", 0);
                        planParam.put("app_bid_ratio", new Object());
                        planParam.put("campaign_id", campaignId);
                        if ("IOS".equals(urlInfo.getType())) {
                            //app 类型 201 应用推广 安卓 201 应用推广 ios
                            planParam.put("app_type", 202);
                        } else if ("android".equals(urlInfo.getType())) {
                            planParam.put("app_type", 201);
                        }
                        String convertType = requestJson.getString("convertType");
                        if (null != convertType && "SIMPLE".equals(convertType)) {
                            //普通应用下载
                            planParam.put("external_action", requestJson.getLong("simpleDeliverytarget"));
                        }
                        if (null != convertType && "API".equals(convertType)) {
                            Long convertId = requestJson.getLong("convertId");
                            if (null != convertId && convertId != 0) {
                                planParam.put("convert_id", convertId);
                            }
                        }
                        String createResult = HttpUtils2.httpPostRequest("https://ad.oceanengine.com/overture/ad/create/", planParam, header);
                        JSONObject result = JSONObject.parseObject(createResult);
                        String status = result.getString("status");
                        String msg = result.getString("msg");
                        if (null != status && !"success".equals(status)) {
                            resultMap.put("code", -1);
                            resultMap.put("message", msg);
                            resultMap.put("success", false);
                            return resultMap;
                        }
                        //广告计划id
                        Long adId = result.getJSONObject("data").getLong("ad_id");
                        //修改用户定向
                        ByteDanceUserOrientationTemplate template = userOrientationTemplateMapper.selectById(userOrientationId);
                        if (null != template) {
                            //获取modify_time
                            Thread.sleep(5000L);
                            advertiserDataService.getAdvertiserPlan(bindAccountLogin.getAccountId(), adId + "", null);
                            advertiserDataService.updateAd(token, adId, template, requestJson);
                        }
                        Long creativeTemplateId = requestJson.getLong("creativeTemplateId");

                        //创建广告创意
                        String name = requestJson.getString("name");
                        data.put("title", name + "_" + System.currentTimeMillis() + "_" + "汇创广告创意");
                        if (i == 0) {
                            BytedanceCreativeLaunchTemplate launchTemplate = launchTemplateMapper.selectById(creativeTemplateId);
                            data.put("ad_id", adId);
                            String advertiseLoaction = launchTemplate.getAdvertiseLocation();
                            if (deliveryRange == 2) {
                                //按媒体指定位置
                                JSONArray inventoryType = new JSONArray();
                                inventoryType.add("INVENTORY_UNION_SLOT");
                                data.put("inventory_type", inventoryType);
                            } else {
                                //穿山甲
                                //按媒体指定位置
                                if (null != advertiseLoaction && "media".equals(advertiseLoaction)) {
                                    String inventoryTypeStr = launchTemplate.getInventoryType();
                                    JSONArray inventoryType = JSONArray.parseArray(inventoryTypeStr);
                                    data.put("inventory_type", inventoryType);
                                }
                                //按场景指定位置
                                if (null != advertiseLoaction && "sence".equals(advertiseLoaction)) {
                                    data.put("scene_inventory", launchTemplate.getSceneInventory());
                                }
                            }
                            //创意展现方式
                            data.put("creative_display_mode", launchTemplate.getCreativeDisplayMode());
                            //优选广告位
                            if (null != advertiseLoaction && "great".equals(advertiseLoaction) && null != launchTemplate.getSmartInventory() && !"".equals(launchTemplate.getSmartInventory())) {
                                data.put("smart_inventory", launchTemplate.getSmartInventory());
                            }

                            //广告评论
                            data.put("is_comment_disable", launchTemplate.getCommentDisable());
                            //创意分类
                            JSONArray categorys = JSONArray.parseArray(launchTemplate.getThirdIndustryId());
                            String thirdIndustryId = categorys.getString(2);
                            data.put("third_industry_id", thirdIndustryId);
                            //创意标签
                            data.put("ad_keywords", JSONArray.parseArray(launchTemplate.getAdKeywords()));

                            //创意标题
                            data.put("title", name + "_" + System.currentTimeMillis() + "_" + "汇创广告创意");

                            //创意方式
                            String creativeType = requestJson.getString("creativeType");
                            if (null != creativeType && "customize".equals(creativeType)) {
                                //自定义创意
                                //拼装creative参数
                                JSONArray creatives = new JSONArray();
                                JSONArray getCreatives = requestJson.getJSONArray("creatives");
                                if (null != getCreatives && getCreatives.size() > 0) {
                                    getCreatives.forEach(k -> {
                                        JSONObject createtive = JSONObject.parseObject(JSONObject.toJSONString(k));
                                        JSONObject setCreatetive = new JSONObject();
                                        String imageMode = createtive.getString("typeCode");
                                        setCreatetive.put("image_mode", imageMode);
                                        String title = createtive.getString("text");
                                        setCreatetive.put("title", title);
                                        JSONArray ids = getCreativeWordIds(title, wordsObject);
                                        setCreatetive.put("creative_word_ids", ids);
                                        String videoUrl = createtive.getString("vadioUrl");
                                        String imageUrl = createtive.getString("imageUrl");
                                        if ("CREATIVE_IMAGE_MODE_VIDEO".equals(imageMode) || "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL".equals(imageMode)) {
                                            //视频创意
                                            if (null != videoUrl) {
                                                Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(token.getAccountId() + "", imageUrl);
                                                JSONArray horizonVideoCoverImageArray = (JSONArray) getImageResult.get("imageIds");
                                                String imageId = horizonVideoCoverImageArray.getString(0);
                                                Map<String, Object> getVideoResult = fileInfoService.uploadVideoToBytedance(token.getAccountId() + "", videoUrl);
                                                String videoId = (String) getVideoResult.get("videoId");
                                                setCreatetive.put("image_id", imageId);
                                                setCreatetive.put("video_id", videoId);
                                                creatives.add(setCreatetive);
                                            }
                                        } else {
                                            //图片创意
                                            if (null != videoUrl && !"".equals(videoUrl.trim())) {
                                                Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(token.getAccountId() + "", videoUrl);
                                                JSONArray imageArray = (JSONArray) getImageResult.get("imageIds");
                                                setCreatetive.put("image_ids", imageArray);
                                                creatives.add(setCreatetive);
                                            }
                                        }
                                    });
                                    data.put("creatives", creatives);
                                }
                            } else {
                                data.put("creative_material_mode", "STATIC_ASSEMBLE");
                                //程序化创意
                                JSONArray titleArray = requestJson.getJSONArray("titles");
                                if (null != titleArray && titleArray.size() > 0) {
                                    JSONArray titleList = new JSONArray();
                                    titleArray.forEach(v -> {
                                        JSONObject getTitleObject = JSONObject.parseObject(JSONObject.toJSONString(v));
                                        JSONObject titleObject = new JSONObject();
                                        String getTitle = getTitleObject.getString("text");
                                        titleObject.put("title", getTitle);
                                        JSONArray ids = getCreativeWordIds(getTitle, wordsObject);
                                        titleObject.put("creative_word_ids", ids);
                                        titleList.add(titleObject);
                                    });
                                    data.put("title_list", titleList);
                                }

                                JSONArray getCreatives = requestJson.getJSONArray("creatives");
                                if (null != getCreatives && getCreatives.size() > 0) {
                                    JSONArray imageList = new JSONArray();
                                    getCreatives.forEach(v -> {
                                        JSONObject createtive = JSONObject.parseObject(JSONObject.toJSONString(v));
                                        JSONObject setCreatetive = new JSONObject();
                                        String imageMode = createtive.getString("typeCode");
                                        setCreatetive.put("image_mode", imageMode);
                                        String videoUrl = createtive.getString("vadioUrl");
                                        String imageUrl = createtive.getString("imageUrl");
                                        if ("CREATIVE_IMAGE_MODE_VIDEO".equals(imageMode) || "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL".equals(imageMode)) {
                                            if (null != videoUrl) {
                                                Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(token.getAccountId() + "", imageUrl);
                                                JSONArray horizonVideoCoverImageArray = (JSONArray) getImageResult.get("imageIds");
                                                String imageId = horizonVideoCoverImageArray.getString(0);
                                                Map<String, Object> getVideoResult = fileInfoService.uploadVideoToBytedance(token.getAccountId() + "", videoUrl);
                                                String videoId = (String) getVideoResult.get("videoId");
                                                setCreatetive.put("image_id", imageId);
                                                setCreatetive.put("video_id", videoId);
                                                imageList.add(setCreatetive);
                                            }
                                        } else {
                                            if (null != videoUrl && !"".equals(videoUrl.trim())) {
                                                Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(token.getAccountId() + "", videoUrl);
                                                JSONArray imageArray = (JSONArray) getImageResult.get("imageIds");
                                                setCreatetive.put("image_ids", imageArray);
                                                imageList.add(setCreatetive);
                                            }
                                        }
                                    });
                                    data.put("image_list", imageList);
                                }
                            }
                            //应用下载详情页
                            data.put("web_url", requestJson.getString("webUrl"));
                            //应用名
                            data.put("app_name", requestJson.getString("appName"));
                        }
                        resultMap = byteDanceCreativeService.creativeCreate(token.getAccountId() + "", adId, data.toJSONString());
                        Boolean createSuccess = (Boolean) resultMap.get("success");
                        if (null != createSuccess && !createSuccess) {
                            return resultMap;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //清除所有的缓存
            webDriver.manage().deleteAllCookies();
            webDriver.close();
            HttpUtils2.cookieStore = new BasicCookieStore();
        }
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        return resultMap;
    }

    public JSONArray getCreativeWordIds(String getTitle, JSONObject wordsObject) {
        ArrayList<String> wordsString = StringUtils.stringCutFromBrace(getTitle);
        JSONArray creativeWords = wordsObject.getJSONArray("creative_word");
        JSONArray ids = new JSONArray();
        wordsString.forEach(v -> {
            creativeWords.forEach(word -> {
                JSONObject wordObject = (JSONObject) word;
                String name = wordObject.getString("name");
                Integer id = wordObject.getInteger("creative_word_id");
                if (v.equals(name)) {
                    ids.add(id);
                }
            });
        });
        return ids;
    }


    @Autowired
    private BytedanceCreativeLaunchTemplateMapper launchTemplateMapper;
    @Autowired
    private IByteDanceCreativeService byteDanceCreativeService;
    @Autowired
    private IFileInfoService fileInfoService;
    @Autowired
    private ByteDanceUserOrientationTemplateMapper userOrientationTemplateMapper;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private IByteDanceAdvertiserDataService advertiserDataService;
}
