package com.xxl.job.executor.material.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.common.service.ICtopOauthTokenService;
import com.xxl.job.executor.material.entity.ByteDanceAdvertisePlan;
import com.xxl.job.executor.material.entity.ByteDanceCreative;
import com.xxl.job.executor.material.mapper.ByteDanceCreativeMapper;
import com.xxl.job.executor.material.service.IByteDanceAdvertisePlanService;
import com.xxl.job.executor.material.service.IByteDanceCreativeService;
import com.xxl.job.executor.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Description: 今日头条创意信息
 * @Author: jeecg-boot
 * @Date: 2019-07-22
 * @Version: V1.0
 */
@Slf4j
@Service
public class ByteDanceCreativeServiceImpl extends ServiceImpl<ByteDanceCreativeMapper, ByteDanceCreative> implements IByteDanceCreativeService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private ByteDanceCreativeMapper creativeMapper;
    @Autowired
    private IByteDanceAdvertisePlanService byteDanceAdvertisePlanService;

    /**
     * 更改创意状态
     * @param accountId
     * @param creativeIds
     * @param optStatus
     * @return
     */
    @Override
    public Map<String, Object> advertiserCreativeUpdateStatus(Long accountId, String creativeIds, String optStatus) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray ids = new JSONArray();
        String[] getCreativeIds = creativeIds.split(StringUtils.COMMA);
        if (getCreativeIds.length > 0) {
            for (int i = 0; i < getCreativeIds.length; i++) {
                ids.add(Long.parseLong(getCreativeIds[i]));
            }
        }
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId+"");
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_update_status");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", cTopOauthToken.getAccessToken());

        JSONObject params = new JSONObject();
        params.put("advertiser_id", cTopOauthToken.getAccountId());
        params.put("creative_ids", ids.toJSONString());
        params.put("opt_status", optStatus);
        String result = HttpUtils.httpPostRequest(url, params, headers);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");
        String message = jsonObject.getString("message");
        if (null == code || !code.equals(0)) {
            log.info("修改创意状态接口异常==》accountId:{},message:{}", accountId, message);
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", message);
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("修改创意状态异常==》accountId:{},message:{}", accountId, message);
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", message);
            return resultMap;
        }
        JSONArray returnCreativeIds = data.getJSONArray("creative_ids");
        if (null != returnCreativeIds && !returnCreativeIds.isEmpty()) {
            getAdvertiserCreative(cTopOauthToken, creativeIds, null);
        }
        resultMap.put("success", true);
        resultMap.put("code", 0);
        resultMap.put("message", "广告创意状态修改成功");
        return resultMap;
    }

    @Override
    public void replaceBatch(List<ByteDanceCreative> creatives) {
        creativeMapper.replaceBatch(creatives);
    }

    /**
     * 获取创意列表，入库
     * @param token
     * @param ids
     * @param date
     * @return
     */
    @Override
    public Map<String, Object> getAdvertiserCreative(CtopOauthToken token, String ids, String date) {
        Map<String, Object> resultMap = new HashMap<>();
        getAdvertiserCreativeByPageNumber(token, 1, ids, date);
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告主广告创意信息完成");
        return resultMap;
    }

    public void getAdvertiserCreativeByPageNumber(CtopOauthToken token, Integer pageNumber, String ids, String date) {
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_get");
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());

        TreeMap<String, Object> params = new TreeMap<>();
        JSONObject filtering = new JSONObject();
        if (null != ids && !"".equals(ids.trim())) {
            String[] idsArray = ids.split(StringUtils.COMMA);
            JSONArray filterIdsArray = new JSONArray();
            for (int i = 0; i < idsArray.length; i++) {
                Long id = Long.parseLong(idsArray[i]);
                filterIdsArray.add(id);
            }
            filtering.put("ids", filterIdsArray);
        }
        if (null != date && !"".equals(date)) {
            filtering.put("creative_create_time", date);
        }
        params.put("filtering", filtering.toJSONString());
        params.put("advertiser_id", token.getAccountId());
        params.put("page", pageNumber + "");
        params.put("page_size",100);
        String result = HttpUtils.httpGetRequest(url, headers, params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer code = jsonObject.getInteger("code");

        if (null == code || !code.equals(0)) {
            log.info("获取广告主广告创意信息接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            log.info("广告主广告创意信息不存在==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceCreative creative = new ByteDanceCreative(dataObject, token);
            this.saveOrUpdate(creative);
        }
        getAdvertiserCreativeByPageNumber(token, pageNumber + 1, ids, date);
    }

    /**
     * 创建创意
     * @param accountId
     * @param adId
     * @param data
     * @return
     */
    @Override
    public Map<String, Object> creativeCreate(String accountId, Long adId, JSONObject data) {
        Map<String, Object> resultMap = new HashMap<>();
        //1：获取token
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        data.put("advertiser_id", token.getAccountId());
        data.put("ad_id", adId);
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_create_v2");
        JSONObject result = HttpUtils.bytedancePostRequest(token.getAccessToken(),url,data);
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if (null == code || code != 0) {
            log.info("广告创意创建失败,accountId:{},message:{}", accountId, message);
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", "广告计划("+adId+"):"+message);
            return resultMap;
        }
        Thread thread = new Thread(()->getAdvertiserCreative(token, null, null));
        thread.start();

        resultMap.put("success", true);
        resultMap.put("code", 0);
        resultMap.put("message", "广告计划("+adId+"):"+"创意创建成功");
        return resultMap;
    }
    /**
     * 获取创意详细信息
     * @return
     */
    @Override
    public Map<String, Object> getCreativeDetail(CtopOauthToken token, Long planId){
        Map<String,Object>resultMap = new HashMap<>();
        if(null == planId||planId == 0||null == token){
            ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_PARAM_ERROR);
            resultMap.put("data",null);
            return resultMap;
        }

        ByteDanceAdvertisePlan plan = byteDanceAdvertisePlanService.getById(planId);
        if(null == plan|| "AD_STATUS_DELETE".equals(plan.getOptStatus())){
            ResultMapUtils.setResultMap(resultMap,StatusCode.BYTEDANCE_ACCOUNT_DATA_NOT_EXIST);
            resultMap.put("data",null);
            return resultMap;
        }
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_read");
        // 请求参数
        JSONObject data = new JSONObject();
        data.put("advertiser_id", token.getAccountId());
        data.put("ad_id",planId);
        JSONObject result = HttpUtils.bytedanceGetRequest(token.getAccessToken(),url,data);
        if(null == result){
            ResultMapUtils.setResultMap(resultMap,StatusCode.COMMON_INTERNET_ERROR);
            resultMap.put("data",null);
            return resultMap;
        }
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if (null ==  code) {
            log.info("广告创意获取详情失败,accountId:{},message:{}", token.getAccountId(), message);
            resultMap.put("success", false);
            resultMap.put("code", -1);
            result.put("data",null);
            resultMap.put("message", message);
            return resultMap;
        }
        if(code == 40001){
            //尚未创建创意
            resultMap.put("success", true);
            resultMap.put("code", 0);
            result.put("data",null);
            resultMap.put("message", message);
            return resultMap;
        }
        if(code!=0){
            log.info("广告创意获取详情失败,accountId:{},message:{}", token.getAccountId(), message);
            resultMap.put("success", false);
            resultMap.put("code", -1);
            result.put("data",null);
            resultMap.put("message", message);
            return resultMap;
        }
        JSONObject getData = result.getJSONObject("data");
        resultMap.put("data",formatData(getData));
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS);
        return resultMap;
    }

    private JSONObject formatData(JSONObject getData) {
        JSONObject data = new JSONObject();
        Long advertiserId = getData.getLong("advertiser_id");
        if(null!=advertiserId&&advertiserId!=0){
            data.put("advertiserId",advertiserId);
        }
        Long adId = getData.getLong("ad_id");
        if(null!=adId&&adId!=0){
            data.put("adId",adId);
        }
        String modifyTime = getData.getString("modify_time");
        if(null!=modifyTime&&!"".equals(modifyTime.trim())){
            data.put("modifyTime",modifyTime);
        }
        String trackUrl = getData.getString("track_url");
        if(null!=trackUrl&&!"".equals(trackUrl.trim())){
            data.put("trackUrl",trackUrl);
        }
        String actionTrackUrl = getData.getString("action_track_url");
        if(null!=actionTrackUrl&&!"".equals(actionTrackUrl.trim())){
            data.put("actionTrackUrl",actionTrackUrl);
        }
        String videoPlayEffectiveTrackUrl = getData.getString("video_play_effective_track_url");
        if(null!=videoPlayEffectiveTrackUrl&&!"".equals(videoPlayEffectiveTrackUrl.trim())){
            data.put("videoPlayEffectiveTrackUrl",videoPlayEffectiveTrackUrl);
        }
        String videoPlayDoneTrackUrl = getData.getString("video_play_done_track_url");
        if(null!=videoPlayDoneTrackUrl&&!"".equals(videoPlayDoneTrackUrl.trim())){
            data.put("videoPlayDoneTrackUrl",videoPlayDoneTrackUrl);
        }
        String videoPlayTrackUrl = getData.getString("video_play_track_url");
        if(null!=videoPlayTrackUrl&&!"".equals(videoPlayTrackUrl.trim())){
            data.put("videoPlayTrackUrl",videoPlayTrackUrl);
        }
        Integer isCommentDisable = getData.getInteger("is_comment_disable");
        if(null!=isCommentDisable){
            data.put("isCommentDisable",isCommentDisable);
        }
        Integer closeVideoDetail = getData.getInteger("close_video_detail");
        if(null!=closeVideoDetail){
            data.put("closeVideoDetail",closeVideoDetail);
        }
        String creativeDisplayMode = getData.getString("creative_display_mode");
        if(null!=creativeDisplayMode&&!"".equals(creativeDisplayMode.trim())){
            data.put("creativeDisplayMode",creativeDisplayMode);
        }
        Long smartInventory = getData.getLong("smart_inventory");
        if(null!=smartInventory&&smartInventory!=0){
            data.put("smartInventory",smartInventory);
        }
        String sceneInventory = getData.getString("scene_inventory");
        if(null!=sceneInventory&&!"".equals(sceneInventory.trim())){
            data.put("sceneInventory",sceneInventory);
        }
        Long generateDerivedAd = getData.getLong("generate_derived_ad");
        if(null!=generateDerivedAd&&generateDerivedAd!=0){
            data.put("generateDerivedAd",generateDerivedAd);
        }
        JSONArray inventoryType = getData.getJSONArray("inventory_type");
        if(null!=inventoryType&&!inventoryType.isEmpty()){
            data.put("inventoryType",inventoryType);
        }
        String source = getData.getString("source");
        if(null!=source&&!"".equals(source.trim())){
            data.put("source",source);
        }
        String appName = getData.getString("app_name");
        if(null!=appName&&!"".equals(appName.trim())){
            data.put("appName",appName);
        }
        String webUrl = getData.getString("web_url");
        if(null!=webUrl&&!"".equals(webUrl.trim())){
            data.put("webUrl",webUrl);
        }
        JSONArray adKeywords = getData.getJSONArray("ad_keywords");
        if(null!=adKeywords&&!adKeywords.isEmpty()){
            data.put("adKeywords",adKeywords);
        }
        Long thirdIndustryId = getData.getLong("third_industry_id");
        if(null!=thirdIndustryId&&thirdIndustryId!=0){
            data.put("thirdIndustryId",thirdIndustryId);
        }
        String advancedCreativeType = getData.getString("advanced_creative_type");
        if(null!=advancedCreativeType&&!"".equals(advancedCreativeType.trim())){
            data.put("advancedCreativeType",advancedCreativeType);
        }
        String advancedCreativeTitle = getData.getString("advanced_creative_title");
        if(null!=advancedCreativeTitle&&!"".equals(advancedCreativeTitle.trim())){
            data.put("advancedCreativeTitle",advancedCreativeTitle);
        }
        String phoneNumber = getData.getString("phone_number");
        if(null!=phoneNumber&&!"".equals(phoneNumber.trim())){
            data.put("phoneNumber",phoneNumber);
        }
        String buttonText = getData.getString("button_text");
        if(null!=buttonText&&!"".equals(buttonText.trim())){
            data.put("buttonText",buttonText);
        }
        String actionText = getData.getString("action_text");
        if(null!=actionText&&!"".equals(actionText.trim())){
            data.put("actionText",actionText);
        }
        String formUrl = getData.getString("form_url");
        if(null!=formUrl&&!"".equals(formUrl.trim())){
            data.put("formUrl",formUrl);
        }
        String creativeMaterialMode = getData.getString("creative_material_mode");
        if(null!=creativeMaterialMode&&!"".equals(creativeMaterialMode.trim())){
            data.put("creativeMaterialMode",creativeMaterialMode);
        }
        String iesCoreUserId = getData.getString("ies_core_user_id");
        if(null!=iesCoreUserId&&!"".equals(iesCoreUserId.trim())){
            data.put("iesCoreUserId",iesCoreUserId);
        }
        Long isFeedAndFavSee = getData.getLong("is_feed_and_fav_see");
        if(null!=isFeedAndFavSee){
            data.put("isFeedAndFavSee",isFeedAndFavSee);
        }
        JSONArray commerceCards = getData.getJSONArray("commerce_cards");
        if(null!=commerceCards&&!commerceCards.isEmpty()){
            data.put("commerceCards",commerceCards);
        }
        String playableUrl = getData.getString("playable_url");
        if(null!=playableUrl&&!"".equals(playableUrl.trim())){
            data.put("playableUrl",playableUrl);
        }
        Long proceduralPackageId = getData.getLong("procedural_package_id");
        if(null!=proceduralPackageId&&proceduralPackageId!=0){
            data.put("proceduralPackageId",proceduralPackageId);
        }
        Long proceduralPackageVersion = getData.getLong("procedural_package_version");
        if(null!=proceduralPackageVersion&&proceduralPackageVersion!=0){
            data.put("proceduralPackageVersion",proceduralPackageVersion);
        }
        Long isPresentedVideo = getData.getLong("is_presented_video");
        if(null!=isPresentedVideo){
            data.put("isPresentedVideo",isPresentedVideo);
        }
        String subTitle = getData.getString("sub_title");
        if(null!=subTitle&&!"".equals(subTitle.trim())){
            data.put("subTitle",subTitle);
        }
        Long creativeAutoGenerateSwitch = getData.getLong("creative_auto_generate_switch");
        if(null!=creativeAutoGenerateSwitch){
            data.put("creativeAutoGenerateSwitch",creativeAutoGenerateSwitch);
        }
        String trackUrlSendType = getData.getString("track_url_send_type");
        if(null!=trackUrlSendType&&!"".equals(trackUrlSendType.trim())){
            data.put("trackUrlSendType",trackUrlSendType);
        }
        JSONArray subLinkIdList = getData.getJSONArray("sub_link_id_list");
        if(null!=subLinkIdList&&!subLinkIdList.isEmpty()){
            data.put("subLinkIdList",subLinkIdList);
        }
        JSONArray titleList = getData.getJSONArray("title_list");
        if(null!=titleList&&!titleList.isEmpty()){
            JSONArray titleArray = new JSONArray();
            for (int i=0;i<titleList.size();i++){
                JSONObject title = titleList.getJSONObject(i);
                JSONArray creativeWordIds = title.getJSONArray("creative_word_ids");
                JSONArray dpaDictIds = title.getJSONArray("dpa_dict_ids");
                title.remove("creative_word_ids");
                title.remove("dpa_dict_ids");
                title.put("creativeWordIds",creativeWordIds);
                title.put("dpaDictIds",dpaDictIds);
                titleArray.add(title);
            }
            data.put("titleList",titleArray);
        }
        JSONArray imageList = getData.getJSONArray("image_list");
        if(null!=imageList&&!imageList.isEmpty()){
            JSONArray imageArray = new JSONArray();
            for (int i=0;i<imageList.size();i++){
                JSONObject getImage = imageList.getJSONObject(i);
                JSONObject setImage = new JSONObject();
                String imageMode = getImage.getString("image_mode");
                setImage.put("imageMode",imageMode);
                String imageId = getImage.getString("image_id");
                if(null!=imageId&&!"".equals(imageId.trim())){
                    setImage.put("imageId",imageId);
                    if(imageId.contains("web")){
                        setImage.put("imageUrl","https://sf6-ttcdn-tos.pstatp.com/obj/"+imageId);
                    }else{
                        setImage.put("imageUrl","https://sf6-ttcdn-tos.pstatp.com/obj/mosaic-legacy/"+imageId);
                    }
                }
                String videoId = getImage.getString("video_id");
                if(null!=videoId&&!"".equals(videoId.trim())){
                    setImage.put("videoId",videoId);
                    setImage.put("videoUrl","https://aweme.snssdk.com/aweme/v1/playwm/?video_id="+videoId+"&line=0");
                }
                JSONArray imageIds = getImage.getJSONArray("image_ids");
                if(null!=imageIds&&!imageIds.isEmpty()){
                    setImage.put("imageIds",imageIds);
                }
                String templateId = getImage.getString("template_id");
                if(null!=templateId&&!"".equals(templateId.trim())){
                    setImage.put("templateId",templateId);
                }
                imageArray.add(setImage);
            }
            data.put("imageList",imageArray);
        }
        JSONArray creativeList = getData.getJSONArray("creatives");
        if(null!=creativeList&&!creativeList.isEmpty()){
            JSONArray creativeArray = new JSONArray();
            for (int i=0;i<creativeList.size();i++){
                JSONObject getCreative = creativeList.getJSONObject(i);
                JSONObject setCreative = new JSONObject();
                String creative_id = getCreative.getString("creative_id");
                if(null!=creative_id&&!"".equals(creative_id.trim())){
                    setCreative.put("creative_id",creative_id);
                }
                String title = getCreative.getString("title");
                if(null!=title&&!"".equals(title.trim())){
                    setCreative.put("title",title);
                }
                JSONArray creativeWordIds = getCreative.getJSONArray("creative_word_ids");
                if(null!=creativeWordIds&&!creativeWordIds.isEmpty()){
                    setCreative.put("creativeWordIds",creativeWordIds);
                }
                JSONArray dpaDictIds = getCreative.getJSONArray("dpa_dict_ids");
                if(null!=dpaDictIds&&!dpaDictIds.isEmpty()){
                    setCreative.put("dpaDictIds",dpaDictIds);
                }
                String imageMode = getCreative.getString("image_mode");
                if(null!=imageMode&&!"".equals(imageMode.trim())){
                    setCreative.put("imageMode",imageMode);
                }
                JSONArray imageIds = getCreative.getJSONArray("imageIds");
                if(null!=imageIds&&!imageIds.isEmpty()){
                    setCreative.put("imageIds",imageIds);
                }
                String imageId = getCreative.getString("image_id");
                if(null!=imageId&&!"".equals(imageId.trim())){
                    setCreative.put("imageId",imageId);
                    setCreative.put("imageUrl","https://sf6-ttcdn-tos.pstatp.com/obj/mosaic-legacy/"+imageId);
                }
                String videoId = getCreative.getString("video_id");
                if(null!=videoId&&!"".equals(videoId.trim())){
                    setCreative.put("videoId",videoId);
                    setCreative.put("videoUrl","https://aweme.snssdk.com/aweme/v1/playwm/?video_id="+videoId+"&line=0");
                }
                String thirdPartyId = getCreative.getString("third_party_id");
                if(null!=thirdPartyId&&!"".equals(thirdPartyId.trim())){
                    setCreative.put("thirdPartyId",thirdPartyId);
                }
                Long derivePosterCid = getCreative.getLong("derive_poster_cid");
                if(null!=derivePosterCid){
                    setCreative.put("derivePosterCid",derivePosterCid);
                }
                Integer templateId = getCreative.getInteger("template_id");
                if(null!=templateId){
                    setCreative.put("templateId",templateId);
                }
                String templateImageId = getCreative.getString("template_image_id");
                if(null!=templateImageId&&!"".equals(templateImageId.trim())){
                    setCreative.put("templateImageId",templateImageId);
                }
                Long dpaTemplate = getCreative.getLong("dpa_template");
                if(null!=dpaTemplate){
                    setCreative.put("dpaTemplate",dpaTemplate);
                }
                String dpaVideoTemplateType = getCreative.getString("dpa_video_template_type");
                if(null!=dpaVideoTemplateType&&!"".equals(dpaVideoTemplateType.trim())){
                    setCreative.put("dpaVideoTemplateType",dpaVideoTemplateType);
                }
                JSONArray dpaVideoTaskIds = getCreative.getJSONArray("dpa_video_task_ids");
                if(null!=dpaVideoTaskIds&&!dpaVideoTaskIds.isEmpty()){
                    setCreative.put("dpaVideoTaskIds",dpaVideoTaskIds);
                }
                creativeArray.add(setCreative);
            }
            data.put("creatives",creativeArray);
        }

        return data;
    }

    /**
     * @param data
     * @return
     */
    @Override
    public Map<String,Object> updateCreative(JSONObject data){
        log.info(data.toJSONString());
        Map<String,Object>result = new HashMap<>();
        Long accountId = data.getLong("accountId");
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        if(null == token){
            ResultMapUtils.setResultMap(result,StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        JSONArray planIdArray = data.getJSONArray("adIds");
        if(null == planIdArray||planIdArray.isEmpty()){
            ResultMapUtils.setResultMap(result,StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        data.remove("adIds");
        data.put("adId",planIdArray.getLong(0));
        JSONObject detail = (JSONObject) this.getCreativeDetail(token,planIdArray.getLong(0)).get("data");
        String modifyTime = detail.getString("modifyTime");
        data.put("modifyTime",modifyTime);
        JSONObject params = initParams(data);
        JSONArray array = new JSONArray();
        Map<String,Object> getData = updateCreative(token,params,planIdArray.getLong(0));
        array.add(getData);
        result.put("data",array);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS);
        return result;
    }

    public Map<String,Object>updateCreative(CtopOauthToken token,JSONObject params,Long adId){
        Map<String, Object> result = new HashMap<>();
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_update");
        JSONObject dataObject = HttpUtils.bytedancePostRequest(token.getAccessToken(),url,params);
        Integer code = dataObject.getInteger("code");
        String message = dataObject.getString("message");
        if (null == code || code != 0) {
            log.info("广告创意更新失败,accountId:{},message:{}", token.getAccountId(), message);
            result.put("success", false);
            result.put("code", -1);
            result.put("message", message);
            return result;
        }
        Thread thread = new Thread(()->getAdvertiserCreative(token,null, DateUtils.formatDate()));
        thread.start();
        result.put("success", true);
        result.put("code", 0);
        result.put("message", "广告计划("+adId+"):"+"创意更新成功");
        return result;
    }

    @Override
    public Map<String,Object> getCreativeRejectReason(Long accountId, Long creativeId){
        Map<String,Object>resultMap = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        JSONArray creativeIds = new JSONArray();
        creativeIds.add(creativeId);
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_reject_reason");
        // 请求参数
        JSONObject data = new JSONObject();
        data.put("advertiser_id", accountId);
        data.put("creative_ids", creativeIds);
        JSONObject result = HttpUtils.bytedancePostRequest(token.getAccessToken(),url,data);
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if (null == code || code != 0) {
            log.info("广告创意创意审核建议获取失败,accountId:{},message:{}", accountId, message);
            resultMap.put("success", false);
            resultMap.put("code", -1);
            resultMap.put("message", message);
            return resultMap;
        }
        resultMap.put("data",result.getJSONObject("data"));
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS);
        return resultMap;
    }

    @Override
    public Map<String, Object> batchCreate(JSONObject data) {
        log.info(data.toJSONString());
        Map<String,Object>result = new HashMap<>();
        Long accountId = data.getLong("accountId");
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        if(null == token){
            ResultMapUtils.setResultMap(result,StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        JSONArray planIds = data.getJSONArray("adIds");
        if(null == planIds||planIds.isEmpty()){
            ResultMapUtils.setResultMap(result,StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        //拼接参数
        JSONObject params  = initParams(data);
        JSONArray array = new JSONArray();
        for(int i=0;i<planIds.size();i++){
            Map<String,Object> getData = creativeCreate(accountId+"",planIds.getLong(i),params);
            array.add(getData);
        }
        Thread thread = new Thread(()->getAdvertiserCreative(token,null, DateUtils.formatDate()));
        thread.start();
        result.put("data",array);
        ResultMapUtils.setResultMap(result,StatusCode.COMMON_SUCCESS);
        return result;
    }


    private JSONObject initParams(JSONObject data) {
        JSONObject params = new JSONObject();
        String creativeWay = data.getString("creativeWay");
        params.put("advertiser_id",data.getLong("accountId"));
        Long adId = data.getLong("adId");
        if(null!=adId&&adId!=0){
            params.put("ad_id",adId);
        }
        String modifyTime = data.getString("modifyTime");
        params.put("modify_time",modifyTime);
        //###############公共参数开始################################
        //优选广告位
        Integer smartInventory = data.getInteger("smartInventory");
        if(null!=smartInventory){
            params.put("smart_inventory",smartInventory);
        }
        //媒体指定位置
        JSONArray inventoryType = data.getJSONArray("inventoryType");
        if(null!=inventoryType){
            params.put("inventory_type",inventoryType);
        }
        //场景指定位置
        String sceneInventory = data.getString("sceneInventory");
        if(null!=sceneInventory&&!"".equals(sceneInventory.trim())){
            params.put("scene_inventory",sceneInventory);
        }
        JSONArray adKeywords = data.getJSONArray("adKeywords");
        if(null!=adKeywords&&!adKeywords.isEmpty()){
            params.put("ad_keywords",adKeywords);
        }
        Long thirdIndustryId = data.getLong("thirdIndustryId");
        if(null!=thirdIndustryId&&thirdIndustryId!=0){
            params.put("third_industry_id",thirdIndustryId);
        }

        /**
         * 创意展现方式
         */
        String creativeDisplayMode = data.getString("creativeDisplayMode");
        if(null!=creativeDisplayMode&& "".equals(creativeDisplayMode.trim())){
            params.put("creative_display_mode",creativeDisplayMode);
        }
        String trackUrl = data.getString("trackUrl");
        if(null!=trackUrl&& "".equals(trackUrl.trim())){
            params.put("track_url",trackUrl);
        }
        String actionTrackUrl = data.getString("actionTrackUrl");
        if(null!=actionTrackUrl&& "".equals(actionTrackUrl.trim())){
            params.put("action_track_url",actionTrackUrl);
        }
        String videoPlayEffectiveTrackUrl = data.getString("videoPlayEffectiveTrackUrl");
        if(null!=videoPlayEffectiveTrackUrl&& "".equals(videoPlayEffectiveTrackUrl.trim())){
            params.put("video_play_effective_track_url",videoPlayEffectiveTrackUrl);
        }
        String videoPlayDoneTrackUrl = data.getString("videoPlayDoneTrackUrl");
        if(null!=videoPlayDoneTrackUrl&& "".equals(videoPlayDoneTrackUrl.trim())){
            params.put("video_play_done_track_url",videoPlayDoneTrackUrl);
        }
        String videoPlayTrackUrl = data.getString("videoPlayTrackUrl");
        if(null!=videoPlayTrackUrl&& "".equals(videoPlayTrackUrl.trim())){
            params.put("video_play_track_url",videoPlayTrackUrl);
        }
        Long isCommentDisable = data.getLong("isCommentDisable");
        if(null!=isCommentDisable&&isCommentDisable!=0){
            params.put("is_comment_disable",isCommentDisable);
        }
        Long closeVideoDetail = data.getLong("closeVideoDetail");
        if(null!=closeVideoDetail){
            params.put("close_video_detail",closeVideoDetail);
        }
        Long generateDerivedAd = data.getLong("generateDerivedAd");
        if(null!=generateDerivedAd&&generateDerivedAd!=0){
            params.put("generate_derived_ad",generateDerivedAd);
        }
        String playableUrl = data.getString("playableUrl");
        if(null!=playableUrl&&!"".equals(playableUrl.trim())){
            params.put("playable_url",playableUrl);
        }
        Long isPresentedVideo = data.getLong("isPresentedVideo");
        if(null!=isPresentedVideo&&isPresentedVideo!=0){
            params.put("is_presented_video",isPresentedVideo);
        }
        Long creativeAutoGenerateSwitch = data.getLong("creativeAutoGenerateSwitch");
        if(null!=creativeAutoGenerateSwitch&&creativeAutoGenerateSwitch!=0){
            params.put("creative_auto_generate_switch",creativeAutoGenerateSwitch);
        }
        String trackUrlSendType = data.getString("trackUrlSendType");
        if(null!=trackUrlSendType&&!"".equals(trackUrlSendType.trim())){
            params.put("track_url_send_type",trackUrlSendType);
        }
        String iesCoreUserId = data.getString("iesCoreUserId");
        if(null!=iesCoreUserId&&!"".equals(iesCoreUserId)){
            params.put("ies_core_user_id",iesCoreUserId);
        }
        Long isFeedAndFavSee = data.getLong("isFeedAndFavSee");
        if(null!=isFeedAndFavSee&&isFeedAndFavSee!=0){
            params.put("is_feed_and_fav_see",isFeedAndFavSee);
        }
        JSONArray subLinkIdList = data.getJSONArray("subLinkIdList");
        if(null!=subLinkIdList&&!subLinkIdList.isEmpty()){
            params.put("sub_link_id_list",subLinkIdList);
        }

        String source = data.getString("source");
        if(null!=source&&!"".equals(source.trim())){
            params.put("source",source);
        }
        //###############公共参数结束################################

        //#######推广目的为APP######################################
        String appName = data.getString("appName");
        if(null!=appName&&!"".equals(appName.trim())){
            params.put("app_name",appName);
        }
        String webUrl = data.getString("webUrl");
        if(null!=webUrl&&!"".equals(webUrl.trim())){
            params.put("web_url",webUrl);
        }
        String actionText = data.getString("actionText");
        if(null!=actionText&&!"".equals(actionText.trim())){
            params.put("action_text",actionText);
        }
        String subTitle = data.getString("subTitle");
        if(null!=subTitle&&!"".equals(subTitle.trim())){
            params.put("sub_title",subTitle);
        }
        //###############################################
        //############创意推广目的为link的时候###################
        String advancedCreativeType = data.getString("advancedCreativeType");
        if(null!=advancedCreativeType&&!"".equals(advancedCreativeType.trim())){
            params.put("advanced_creative_type",advancedCreativeType);
        }
        String advancedCreativeTitle = data.getString("advancedCreativeTitle");
        if(null!=advancedCreativeTitle&&!"".equals(advancedCreativeTitle.trim())){
            params.put("advanced_creative_title",advancedCreativeTitle);
        }
        String phoneNumber = data.getString("phoneNumber");
        if(null!=phoneNumber&&!"".equals(phoneNumber.trim())){
            params.put("phone_number",phoneNumber);
        }
        String buttonText = data.getString("buttonText");
        if(null!=buttonText&&!"".equals(buttonText.trim())){
            params.put("button_text",buttonText);
        }
        String formUrl = data.getString("formUrl");
        if(null!=formUrl&&!"".equals(formUrl.trim())){
            params.put("form_url",formUrl);
        }

        if(null!=creativeWay&& "proceduralCreativity".equals(creativeWay.trim())){
            //程序化
            params.put("creative_material_mode","STATIC_ASSEMBLE");
            JSONArray titleList = data.getJSONArray("titleList");
            if(null!=titleList&&!titleList.isEmpty()){
                JSONArray setTitleList = new JSONArray();
                for (int i=0;i<titleList.size();i++){
                    JSONObject titleObject = titleList.getJSONObject(i);
                    JSONArray creativeWordIds = titleObject.getJSONArray("creativeWordIds");
                    titleObject.remove("creativeWordIds");
                    if(null!=creativeWordIds&&!creativeWordIds.isEmpty()){
                        titleObject.put("creative_word_ids",creativeWordIds);
                    }
                    setTitleList.add(titleObject);
                }
                params.put("title_list",setTitleList);
            }
            JSONArray imageList = data.getJSONArray("imageList");
            if(null!=imageList&&!imageList.isEmpty()){
                JSONArray setImageList = new JSONArray();
                for (int i=0;i<imageList.size();i++){
                    JSONObject imageObject = imageList.getJSONObject(i);
                    String imageMode = imageObject.getString("imageMode");
                    JSONArray imageIds = imageObject.getJSONArray("imageIds");
                    String imageId = imageObject.getString("imageId");
                    String videoId = imageObject.getString("videoId");
                    Integer templateId = imageObject.getInteger("templateId");
                    imageObject.remove("imageMode");
                    imageObject.remove("imageIds");
                    imageObject.remove("imageId");
                    imageObject.remove("videoId");
                    imageObject.remove("templateId");
                    imageObject.put("image_mode",imageMode);
                    if(null!=imageIds&&!imageIds.isEmpty()){
                        imageObject.put("image_ids",imageIds);
                    }
                    if(null!=imageId&&!"".equals(imageId.trim())){
                        imageObject.put("image_id",imageId);
                    }
                    if(null!=videoId&&!"".equals(videoId.trim())){
                        imageObject.put("video_id",videoId);
                    }
                    if(null!=templateId&&templateId!=0){
                        imageObject.put("template_id",templateId);
                    }

                    setImageList.add(imageObject);
                }
                params.put("image_list",setImageList);
            }
        }else{
            //自定义创意
            JSONArray creatives = data.getJSONArray("creatives");
            if(null!=creatives&&!creatives.isEmpty()){
                JSONArray setCreatives = new JSONArray();
                for(int i=0;i<creatives.size();i++){
                    JSONObject creativeObject = creatives.getJSONObject(i);
                    JSONArray creativeWordIds = creativeObject.getJSONArray("creativeWordIds");
                    creativeObject.remove("creativeWordIds");
                    if(null!=creativeWordIds&&!creativeWordIds.isEmpty()){
                        creativeObject.put("creative_word_ids",creativeWordIds);
                    }
                    String imageMode = creativeObject.getString("imageMode");
                    creativeObject.remove("imageMode");
                    creativeObject.put("image_mode",imageMode);
                    JSONArray imageIds = creativeObject.getJSONArray("imageIds");
                    creativeObject.remove("imageIds");
                    if(null!=imageIds&&!imageIds.isEmpty()){
                        creativeObject.put("image_ids",imageIds);
                    }
                    String imageId = creativeObject.getString("imageId");
                    creativeObject.remove("imageId");
                    if(null!=imageId&&!"".equals(imageId.trim())){
                        creativeObject.put("image_id",imageId);
                    }
                    String videoId = creativeObject.getString("videoId");
                    creativeObject.remove("videoId");
                    if(null!=videoId&&!"".equals(videoId.trim())){
                        creativeObject.put("video_id",videoId);
                    }
                    Integer templateId = creativeObject.getInteger("templateId");
                    creativeObject.remove("templateId");
                    if(null!=templateId&&templateId!=0){
                        creativeObject.put("template_id",templateId);
                    }
                    JSONArray dpaDictIds = creativeObject.getJSONArray("dpaDictIds");
                    creativeObject.remove("dpaDictIds");
                    if(null!=dpaDictIds&&!dpaDictIds.isEmpty()){
                        creativeObject.put("dpa_dict_ids",dpaDictIds);
                    }
//                    String text = creativeObject.getString("title");
//                    creativeObject.remove("text");
//                    if(null!=text&&!"".equals(text.trim())){
//                        creativeObject.put("title",text);
//                    }
                    Integer derivePosterCid = creativeObject.getInteger("derivePosterCid");
                    creativeObject.remove("derivePosterCid");
                    if(null!=derivePosterCid&&derivePosterCid!=0){
                        creativeObject.put("derive_poster_cid",derivePosterCid);
                    }
                    setCreatives.add(creativeObject);
                }
                params.put("creatives",setCreatives);
            }
        }
        return params;
    }
}
