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

import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import cn.com.ctop.toutiao.entity.ByteDanceAdvertisePlan;
import cn.com.ctop.toutiao.entity.BytedanceDeliveryTargetTemplate;
import cn.com.ctop.toutiao.entity.BytedanceUrlInfo;
import cn.com.ctop.toutiao.mapper.ByteDanceAdvertisePlanMapper;
import cn.com.ctop.toutiao.mapper.BytedanceDeliveryTargetTemplateMapper;
import cn.com.ctop.toutiao.mapper.BytedanceUrlInfoMapper;
import cn.com.ctop.toutiao.service.IByteDanceAdvertisePlanService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import cn.com.ctop.common.module.entity.BindAccountLogin;
import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.BindAccountLoginMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Description: 今日头条广告计划信息
 * @Author: jeecg-boot
 * @Date: 2019-07-22
 * @Version: V1.0
 */
@Slf4j
@Service
public class ByteDanceAdvertisePlanServiceImpl extends ServiceImpl<ByteDanceAdvertisePlanMapper, ByteDanceAdvertisePlan> implements IByteDanceAdvertisePlanService {
    @Autowired
    private BytedanceUrlInfoMapper urlInfoMapper;
    @Autowired
    private BytedanceDeliveryTargetTemplateMapper deliveryTargetTemplateMapper;
    @Autowired
    private ICtopOauthTokenService tokenService;
    @Autowired
    private ByteDanceAdvertisePlanMapper planMapper;

    @Override
    public Map<String, Object> advertiserPlanCreate(CtopOauthToken token, Long campaignId, String dataString) {
        Map<String, Object> resultMap = new HashMap<>();
        JSONObject data = JSONObject.parseObject(dataString);
        data.put("advertiser_id", token.getAccountId());
        data.put("campaign_id", campaignId);
        JSONObject result = createAd(data, token.getAccessToken());
        Integer code = result.getInteger("code");
        String message = result.getString("message");
        if (null == code || code != 0) {
            log.info("广告计划创建失败,广告主id:{},message:{}", token.getAdvertiserId(), message);
            resultMap.put("code", -1);
            resultMap.put("message", message);
            return resultMap;
        }
        JSONObject dataObject = result.getJSONObject("data");
        Long adId = dataObject.getLong("ad_id");
        ByteDanceAdvertisePlan plan = new ByteDanceAdvertisePlan(token.getAdvertiserId(), adId, data);

        planMapper.insert(plan);
        resultMap.put("planId", adId);
        resultMap.put("code", 0);
        resultMap.put("message", "广告计划创建成功");
        return resultMap;
    }

    @Override
    public Map<String, Object> getAdConvertList(Long accountId, Long targetId) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        BytedanceDeliveryTargetTemplate targetTemplate = deliveryTargetTemplateMapper.selectById(targetId);
        return getAdConvert(token, targetTemplate);
    }

    @Override
    public Map<String, Object> getAdConvertListByUrlId(Long accountId, Long urlId) {
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountId + "");
        BytedanceUrlInfo urlInfo = urlInfoMapper.selectById(urlId);
        return getAdConvertByUrlInfo(token, urlInfo);
    }

    @Autowired
    private BindAccountLoginMapper bindAccountLoginMapper;

    @Override
    public Map<String, Object> getAdConvertListByUrlIdAndBindId(Long bindAccountId, Long urlId) {
        BindAccountLogin accountLogin = bindAccountLoginMapper.selectById(bindAccountId);
        CtopOauthToken token = tokenService.getOauthTokenByAccountId(accountLogin.getAccountId());
        BytedanceUrlInfo urlInfo = urlInfoMapper.selectById(urlId);
        return getAdConvertByUrlInfo(token, urlInfo);
    }

    private Map<String, Object> getAdConvertByUrlInfo(CtopOauthToken token, BytedanceUrlInfo urlInfo) {

        Long advertiserId = token.getAccountId();
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/tools/ad_convert/select/";
        // 请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", advertiserId);
        //落地页或IOS下载链接
        if ("page".equals(urlInfo.getType())) {
            params.put("external_url", urlInfo.getUrl());
        }
        //安卓下载链接
        if ("android".equals(urlInfo.getType())) {
            params.put("package_name", urlInfo.getPackageName());
        }
        if ("IOS".equals(urlInfo.getType())) {
            params.put("itunes_url", urlInfo.getUrl());
        }

        JSONObject result = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, params);
        JSONArray activeConvertList = result.getJSONObject("data").getJSONArray("active_convert_list");
        result.remove("data");
        JSONArray resultList = new JSONArray();
        if (null != activeConvertList && activeConvertList.size() > 0) {
            for (int i = 0; i < activeConvertList.size(); i++) {
                JSONObject covert = activeConvertList.getJSONObject(i);
                String name = covert.getString("name");
                if (!"下载完成".equals(name.trim()) && !"安装完成".equals(name)) {
                    resultList.add(covert);
                }
            }
        }
        JSONObject dataObject = new JSONObject();
        dataObject.put("active_convert_list", resultList);
        result.put("data", dataObject);
        return result;
    }

    public JSONObject getAdConvert(CtopOauthToken token, BytedanceDeliveryTargetTemplate targetTemplate) {
        final Long advertiserId = token.getAccountId();
        // 请求地址
        String url = "https://ad.toutiao.com/open_api/2/tools/ad_convert/select/";
        // 请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", advertiserId);
        //落地页
        if ("EXTERNAL_URL".equals(targetTemplate.getDownloadType())) {
            params.put("external_url", targetTemplate.getDownloadUrl());
        }
        //下载链接
        if ("DOWNLOAD_URL".equals(targetTemplate.getDownloadType())) {
            if ("ios".equals(targetTemplate.getDownloadMode())) {
                params.put("download_url", targetTemplate.getDownloadUrl());
            }
            if ("android".equals(targetTemplate.getDownloadMode())) {
                params.put("package_name", targetTemplate.getPackageName());
            }
        }
        JSONObject result = HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, params);
        result.remove("data");
        JSONArray activeConvertList = result.getJSONObject("data").getJSONArray("active_convert_list");
        JSONArray resultList = new JSONArray();
        if (null != activeConvertList && activeConvertList.size() > 0) {
            for (int i = 0; i < activeConvertList.size(); i++) {
                JSONObject covert = activeConvertList.getJSONObject(i);
                String name = covert.getString("name");
                if (!"下载完成".equals(name.trim()) && !"安装完成".equals(name)) {
                    resultList.add(covert);
                }
            }
        }
        JSONObject dataObject = new JSONObject();
        dataObject.put("active_convert_list", resultList);
        result.put("data", dataObject);
        return result;
    }


    public JSONObject createAd(JSONObject data, String token) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_ad_create");
        return HttpUtils.bytedancePostRequest(token, url, data);
    }
}
