package cn.com.ctop.toutiao.modules.material.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.*;
import cn.com.ctop.toutiao.modules.material.entity.ByteDanceCreative;
import cn.com.ctop.toutiao.modules.material.mapper.ByteDanceCreativeMapper;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCreativeService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
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
@Primary
public class ByteDanceCreativeServiceImpl extends ServiceImpl<ByteDanceCreativeMapper, ByteDanceCreative> implements IByteDanceCreativeService {
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private ByteDanceCreativeMapper creativeMapper;

    /**
     * 更改创意状态
     * @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;
        }
        resultMap.put("success", true);
        resultMap.put("code", 0);
        resultMap.put("message", "广告计划("+adId+"):"+"创意创建成功");
        return resultMap;
    }

    /**
     * 获取创意详细信息
     * @return
     */
    @Override
    public Map<String, Object> getCreativeDetail(Long accountId, Long adId){
        Map<String,Object>resultMap = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        // 请求地址
        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",adId);
        JSONObject result = HttpUtils.bytedanceGetRequest(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;
    }

    /**
     * TODO 后续需要拼接参数
     * @param accountId
     * @param data
     * @return
     */
    @Override
    public Map<String,Object> updateCreative(Long accountId,JSONObject data){
        Map<String,Object>resultMap = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_update");
        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> 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);
        }
        getAdvertiserCreative(token,null, DateUtils.formatDate());
        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"));
        //###############公共参数开始################################
        //优选广告位
        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&&!sceneInventory.trim().equals("")){
            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&&creativeDisplayMode.trim().equals("")){
            params.put("creative_display_mode",creativeDisplayMode);
        }
        String trackUrl = data.getString("trackUrl");
        if(null!=trackUrl&&trackUrl.trim().equals("")){
            params.put("track_url",trackUrl);
        }
        String actionTrackUrl = data.getString("actionTrackUrl");
        if(null!=actionTrackUrl&&actionTrackUrl.trim().equals("")){
            params.put("action_track_url",actionTrackUrl);
        }
        String videoPlayEffectiveTrackUrl = data.getString("videoPlayEffectiveTrackUrl");
        if(null!=videoPlayEffectiveTrackUrl&&videoPlayEffectiveTrackUrl.trim().equals("")){
            params.put("video_play_effective_track_url",videoPlayEffectiveTrackUrl);
        }
        String videoPlayDoneTrackUrl = data.getString("videoPlayDoneTrackUrl");
        if(null!=videoPlayDoneTrackUrl&&videoPlayDoneTrackUrl.trim().equals("")){
            params.put("video_play_done_track_url",videoPlayDoneTrackUrl);
        }
        String videoPlayTrackUrl = data.getString("videoPlayTrackUrl");
        if(null!=videoPlayTrackUrl&&videoPlayTrackUrl.trim().equals("")){
            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&&!source.trim().equals("")){
            params.put("source",source);
        }
        //###############公共参数结束################################

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

        if(null!=creativeWay&&creativeWay.trim().equals("proceduralCreativity")){
            //程序化
            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("text");
                    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;
    }
}
