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.service.IFileInfoService;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.common.module.utils.StringUtils;
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.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.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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 IFileInfoService fileInfoService;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private ByteDanceCreativeMapper creativeMapper;

    @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 void replaceBatch(List<ByteDanceCreative> creatives) {
        creativeMapper.replaceBatch(creatives);
    }

    @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 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;
    }
}
