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

import cn.com.ctop.common.module.entity.CtopOauthToken;
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.toutiao.entity.ByteDanceCreative;
import cn.com.ctop.toutiao.mapper.ByteDanceCreativeMapper;
import cn.com.ctop.toutiao.service.IByteDanceCampaignTemplateService;
import cn.com.ctop.toutiao.service.IByteDanceCreativeService;
import cn.com.ctop.toutiao.service.IBytedanceAdvertisePlanTemplateService;
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.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
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 IFileInfoService fileInfoService;
    @Autowired
    private IByteDanceCampaignTemplateService campaignTemplateService;
    @Autowired
    private IBytedanceAdvertisePlanTemplateService planTemplateService;
    @Autowired
    private ICtopOauthTokenService tokenService;

    @Override
    public Map<String, Object> advertiserCreativeUpdateStatus(String accountId, String creativeIds, String optStatus) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONArray ids = new JSONArray();
        String[] getCreativeIds = creativeIds.split(StringUtils.COMMA);
        if (null != getCreativeIds && 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");

        if (null == code || !code.equals(0)) {
            log.info("修改创意状态接口异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改创意状态接口异常");
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("修改创意状态异常==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "修改创意状态异常");
            return resultMap;
        }
        JSONArray returnCreativeIds = data.getJSONArray("creative_ids");
        if (null != returnCreativeIds && returnCreativeIds.size() > 0) {
            getAdvertiserCreative(accountId, creativeIds, null);
        }
        resultMap.put("code", 0);
        resultMap.put("message", "广告创意状态修改成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> getAdvertiserCreative(String accountId, String ids, String date) {
        Map<String, Object> resultMap = new HashMap<>();
        getAdvertiserCreativeByPageNumber(accountId, 1, ids, date);
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告主广告创意信息完成");
        return resultMap;
    }

    public void getAdvertiserCreativeByPageNumber(String accountId, Integer pageNumber, String ids, String date) {
        CtopOauthToken cTopOauthToken = tokenService.getOauthTokenByAccountId(accountId);
        //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", cTopOauthToken.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", cTopOauthToken.getAccountId());
        params.put("page", pageNumber + "");
        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:{}", accountId, jsonObject.getString("message"));
            return;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.size() <= 0) {
            log.info("广告主广告创意信息不存在==》accountId:{},message:{}", accountId, jsonObject.getString("message"));
            return;
        }
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceCreative creative = new ByteDanceCreative(dataObject, accountId);
            this.saveOrUpdate(creative);
        }
        getAdvertiserCreativeByPageNumber(accountId, pageNumber + 1, ids, date);
    }

    @Override
    public Map<String, Object> creativeCreate(String accountId, Long adId, String dataString) {
        Map<String, Object> resultMap = new HashMap<>();
        //1：获取token
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId);
        JSONObject data = JSONObject.parseObject(dataString);
        data.put("advertiser_id", token.getAccountId());
        data.put("ad_id", adId);
        JSONObject result = createCreative(data, token.getAccessToken());
        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("success", true);
        resultMap.put("code", 0);
        resultMap.put("message", "广告创意创建成功");
        return resultMap;
    }


    @Override
    public Map<String, Object> insertBatch(JSONObject template) {
        Map<String, Object> resultMap = new HashMap<>();
        String getName = template.getString("name");
        String getAccountId = template.getLong("accountId") + "";
        Long campaignTemplateId = template.getLong("campaignId");
        String deliveryRange = template.getString("deliveryRange");
        Long userorentationId = template.getLong("userorentationId");
        Long budgetId = template.getLong("budgetId");
        Long deliverytargetId = template.getLong("deliverytargetId");
        Long convertId = template.getLong("convertId");
        Integer iteratorNum = template.getInteger("iteratorNum");
        //获取所有创意信息
        JSONArray groupImageArray = null;
        JSONArray horizonImageArray = null;
        String horizonVideoCoverImage = null;
        String horizonVideo = null;
        JSONArray verticalVideoCoverImageArray = null;
        String verticalVideoId = null;
        JSONArray smallImageArray = null;
        JSONArray verticalImageArray = null;
        //1:创建广告组
        Map<String, Object> campaignResult = campaignTemplateService.campaignCreate(getAccountId, campaignTemplateId, getName);
        Boolean createSuccess = (Boolean) campaignResult.get("success");
        if (null == createSuccess || !createSuccess) {
            return campaignResult;
        }
        Long campaignId = (Long) campaignResult.get("campaignId");
        if (null != iteratorNum && iteratorNum >= 1) {
            for (int i = 0; i < iteratorNum; i++) {
                //2:创建广告计划
                Map<String, Object> planResult = planTemplateService.planCreate(campaignId, getAccountId, deliveryRange, userorentationId, budgetId, deliverytargetId, getName, convertId + "");
                Integer code = (Integer) planResult.get("code");
                if (null == code || code != 0) {
                    return planResult;
                }
                Long planId = (Long) planResult.get("planId");
                //3:创建广告创意
                JSONObject data = new JSONObject();
                data.put("ad_id", planId);
                String advertiseLoaction = template.getString("advertiseLocation");
                //优选广告位
                if (null != advertiseLoaction && "great".equals(advertiseLoaction)) {
                    data.put("smart_inventory", 1);
                } else {
                    data.put("smart_inventory", 0);
                }
                //按媒体指定位置
                if (null != advertiseLoaction && "media".equals(advertiseLoaction)) {
                    JSONArray inventoryType = template.getJSONArray("inventoryType");
                    data.put("inventory_type", inventoryType);
                }
                //按场景指定位置
                if (null != advertiseLoaction && "sence".equals(advertiseLoaction)) {
                    data.put("scene_inventory", template.getString("sceneInventory"));
                }
                JSONArray creatives = new JSONArray();
                String horizonImageUrl = template.getString("horizonImageUrl");
                String horizonImageCreativeText = template.getString("horizonImageCreativeText");
                if (null != horizonImageUrl && !"".equals(horizonImageUrl) && null != horizonImageCreativeText && !"".equals(horizonImageCreativeText)) {
                    JSONObject creative = new JSONObject();
                    creative.put("image_mode", "CREATIVE_IMAGE_MODE_LARGE");
                    if (null == horizonImageArray) {
                        Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(getAccountId, horizonImageUrl);
                        horizonImageArray = (JSONArray) getImageResult.get("imageIds");
                    }
                    creative.put("image_ids", horizonImageArray);
                    creative.put("title", horizonImageCreativeText);
                    creatives.add(creative);
                }
                String horizonVideoUrl = template.getString("horizonVideoUrl");
                String horizonVideoCoverImageUrl = template.getString("horizonVideoCoverImageUrl");
                String horizonVideoCreativeText = template.getString("horizonVideoCreativeText");
                if (null != horizonVideoUrl && !"".equals(horizonVideoUrl) && null != horizonVideoCoverImageUrl && !"".equals(horizonVideoCoverImageUrl) && null != horizonVideoCreativeText && !"".equals(horizonVideoCreativeText)) {
                    JSONObject creative = new JSONObject();
                    creative.put("image_mode", "CREATIVE_IMAGE_MODE_VIDEO");
                    if (null == horizonVideoCoverImage) {
                        Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(getAccountId, horizonVideoCoverImageUrl);
                        JSONArray horizonVideoCoverImageArray = (JSONArray) getImageResult.get("imageIds");
                        horizonVideoCoverImage = horizonVideoCoverImageArray.getString(0);
                    }

                    if (null == horizonVideo) {
                        Map<String, Object> getVideoResult = fileInfoService.uploadVideoToBytedance(getAccountId, horizonVideoUrl);
                        horizonVideo = (String) getVideoResult.get("videoId");
                    }
                    creative.put("image_id", horizonVideoCoverImage);
                    creative.put("video_id", horizonVideo);
                    creative.put("title", horizonVideoCreativeText);
                    creatives.add(creative);
                }
                String verticalVideoUrl = template.getString("verticalVideoUrl");
                String verticalVideoCoverImageUrl = template.getString("verticalVideoCoverImageUrl");
                String verticalVideoCreativeText = template.getString("verticalVideoCreativeText");
                if (null != verticalVideoUrl && !"".equals(verticalVideoUrl) && null != verticalVideoCoverImageUrl && !"".equals(verticalVideoCoverImageUrl) && null != verticalVideoCreativeText && !"".equals(verticalVideoCreativeText)) {
                    JSONObject creative = new JSONObject();
                    creative.put("image_mode", "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL");
                    if (null == verticalImageArray) {
                        Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(getAccountId, verticalVideoCoverImageUrl);
                        verticalVideoCoverImageArray = (JSONArray) getImageResult.get("imageIds");
                    }
                    if (null == verticalVideoId || "".equals(verticalVideoId.trim())) {
                        Map<String, Object> getVideoResult = fileInfoService.uploadVideoToBytedance(getAccountId, verticalVideoUrl);
                        verticalVideoId = (String) getVideoResult.get("videoId");
                    }
                    creative.put("image_id", verticalVideoCoverImageArray.getString(0));
                    creative.put("video_id", verticalVideoId);
                    creative.put("title", verticalVideoCreativeText);
                    creatives.add(creative);
                }
                String groupImageUrl = template.getString("groupImageUrl");
                String groupImageCreativeText = template.getString("groupImageCreativeText");
                if (null != groupImageUrl && !"".equals(groupImageUrl) && null != groupImageCreativeText && !"".equals(groupImageCreativeText)) {
                    JSONObject creative = new JSONObject();
                    creative.put("image_mode", "CREATIVE_IMAGE_MODE_GROUP");
                    if (null == groupImageArray) {
                        Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(getAccountId, groupImageUrl);
                        groupImageArray = (JSONArray) getImageResult.get("imageIds");
                    }
                    creative.put("image_ids", groupImageArray);
                    creative.put("title", groupImageCreativeText);
                    creatives.add(creative);
                }
                String smallImageUrl = template.getString("smallImageUrl");
                String smallImageCreativeText = template.getString("smallImageCreativeText");
                if (null != smallImageUrl && !"".equals(smallImageUrl) && null != smallImageCreativeText && !"".equals(smallImageCreativeText)) {
                    JSONObject creative = new JSONObject();
                    creative.put("image_mode", "CREATIVE_IMAGE_MODE_SMALL");
                    if (null == smallImageArray) {
                        Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(getAccountId, smallImageUrl);
                        smallImageArray = (JSONArray) getImageResult.get("imageIds");
                    }
                    creative.put("image_ids", smallImageArray);
                    creative.put("title", smallImageCreativeText);
                    creatives.add(creative);
                }

                String verticalImageUrl = template.getString("verticalImageUrl");
                String verticalImageCreativeText = template.getString("verticalImageCreativeText");
                if (null != verticalImageUrl && !"".equals(verticalImageUrl) && null != verticalImageCreativeText && !"".equals(verticalImageCreativeText)) {
                    JSONObject creative = new JSONObject();
                    creative.put("image_mode", "CREATIVE_IMAGE_MODE_LARGE_VERTICAL");
                    if (null == verticalImageArray) {
                        Map<String, Object> getImageResult = fileInfoService.uploadImageToBytedance(getAccountId, verticalImageUrl);
                        verticalImageArray = (JSONArray) getImageResult.get("imageIds");
                    }
                    creative.put("image_ids", verticalImageArray);
                    creative.put("title", verticalImageCreativeText);
                    creatives.add(creative);
                }


                data.put("creatives", creatives);

                //应用下载详情页
                data.put("web_url", template.getString("webUrl"));
                //应用名
                data.put("app_name", template.getString("appName"));
                //广告评论
                data.put("is_comment_disable ", template.getIntValue("isCommentDisable"));
                //创意展现方式
                data.put("creative_display_mode ", template.getString("creativeDisplayMode"));
                //创意分类
                JSONArray categorys = template.getJSONArray("adCategory");
                String thirdIndustryId = categorys.getString(2);
                data.put("third_industry_id", Integer.parseInt(thirdIndustryId));
                //创意标签
                data.put("ad_keywords", template.getJSONArray("adKeywords"));
                String name = template.getString("name");
                //创意标题
                data.put("title", name + "_" + i + "_" + System.currentTimeMillis());

                resultMap = this.creativeCreate(getAccountId, planId, data.toJSONString());
                createSuccess = (Boolean) resultMap.get("success");
                if (null != createSuccess && !createSuccess) {
                    return resultMap;
                }
            }
        }
        ResultMapUtils.setResultMap(resultMap, StatusCode.COMMON_SUCCESS.getCode());
        return resultMap;
    }

    @Override
    public JSONObject createCreative(JSONObject data, String token) {
        // 构造请求
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_creative_create_v2");
        HttpPost httpEntity = new HttpPost(url);
        httpEntity.setHeader("Access-Token", token);
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            client = HttpClientBuilder.create().build();
            httpEntity.setEntity(new StringEntity(data.toJSONString(), ContentType.APPLICATION_JSON));
            response = client.execute(httpEntity);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                bufferedReader.close();
                return JSONObject.parseObject(result.toString());
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (null != client) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
