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

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.toutiao.modules.tool.constants.QueryToolUrlConstant;
import cn.com.ctop.toutiao.modules.tool.service.IByteDanceConvertToolService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ByteDanceConvertToolServiceImpl implements IByteDanceConvertToolService {

    @Override
    public Map<String, Object> queryAdConvert(CtopOauthToken token, Long accountId, String landingType, String appType,
                                              String downloadType,String externalUrl,String toutiaoPackage,
                                              String itunesUrl) {

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Access-Token", token.getAccessToken());

        JSONObject params=new JSONObject();
        params.put("advertiser_id",accountId);
        params.put("landing_type",landingType);
        if("LINK".equals(landingType)){
            params.put("promotion_content","EXTERNAL_URL");
            params.put("external_url",externalUrl);
        }else if("APP".equals(landingType)){
            if("DOWNLOAD_URL".equals(downloadType)){
                params.put("promotion_content","DOWNLOAD_URL");
                if("APP_ANDROID".equals(appType)){
                    params.put("package_name",toutiaoPackage);
                    params.put("app_type",appType);
                }else if("APP_IOS".equals(appType)){
                    params.put("itunes_url",itunesUrl);
                    params.put("app_type",appType);
                }
            }else if("EXTERNAL_URL".equals(downloadType)){
                params.put("promotion_content","EXTERNAL_URL");
                params.put("external_url",externalUrl);
            }

        }
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.httpGet(QueryToolUrlConstant.AD_CONVERT_QUERY, params, headers));
        Map<String,Object> resultMap=new HashMap<>();
        if(jsonObject.getInteger("code")!=0){
            log.error("查询计划可用转化id失败==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", jsonObject.getString("message"));
            return resultMap;
        }
        resultMap.put("code", 0);
        resultMap.put("data",jsonObject.getJSONObject("data"));
        //.getJSONArray("list").getJSONArray(3).getLong(1)
        return resultMap;
    }

}
