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.ByteDanceCampaign;
import cn.com.ctop.toutiao.modules.material.mapper.ByteDanceCampaignMapper;
import cn.com.ctop.toutiao.modules.material.service.IByteDanceCampaignService;
import cn.com.ctop.toutiao.modules.material.vo.BytedanceCampaignEditVo;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 今日头条广告组信息
 * @Author: jeecg-boot
 * @Date: 2019-07-22
 * @Version: V1.0
 */

@Service
@Slf4j
public class ByteDanceCampaignServiceImpl extends ServiceImpl<ByteDanceCampaignMapper, ByteDanceCampaign> implements IByteDanceCampaignService {
    @Autowired
    private ByteDanceCampaignMapper campaignMapper;
    @Autowired
    private ICtopOauthTokenService tokenService;
    /**
     * 每个广告主账号下最多可允许创建500个广告组，如超出需要先删除一部分广告组后才可继续创建。
     * @param accountId
     * @param campaignName
     * @param operation
     * @param budgetMode
     * @param budget
     * @param landingType
     * @param uniqueFk
     * @return
     */
    @Override
    public Map<String, Object> createCampaign(Long accountId, String campaignName, String operation, String budgetMode, String budget, String landingType, String uniqueFk) {
        Map<String,Object>result = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_create");
        // 请求参数
        JSONObject param = new JSONObject();
        param.put("advertiser_id",token.getAccountId());
        param.put("campaign_name",campaignName);
        if(null!=operation&&!"".equals(operation.trim())){
            param.put("operation",operation);
        }
        param.put("budget_mode", budgetMode);
        if(null != budget&&!"".equals(budget.trim())){
            param.put("budget",budget);
        }
        param.put("landing_type", landingType);
        if(null != uniqueFk&&!"".equals(uniqueFk.trim())){
            param.put("unique_fk",uniqueFk);
        }
        JSONObject data = HttpUtils.bytedancePostRequest(token.getAccessToken(),url,param);
        if(data == null){
            log.error("创建广告组异常=>param:{}",param.toJSONString());
            ResultMapUtils.setResultMap(result, StatusCode.BYTEDACNE_API_GROUP_CREATE_ERROR);
            return result;
        }
        Integer code = data.getInteger("code");
        String message = data.getString("message");
        if(null == code||!code.equals(0)){
            log.error("获取广告组数据异常=>{},parmas:{}",message,param.toJSONString());
            ResultMapUtils.setResultMap(result,-1,message,false);
            return result;
        }
        Long campaignId = data.getJSONObject("data").getLong("campaign_id");
        this.getAdvertiserCampaign(token,null,null);
        ResultMapUtils.setResultMap(result,StatusCode.COMMON_SUCCESS);
        result.put("campaign_id",campaignId);
        return result;
    }

    @Override
    public Map<String, Object> updateCampaign(CtopOauthToken token, Long campaignId, String campaignName,String budgetMode, Integer budget) {
        Map<String, Object> resultMap = new HashMap<>();
        ByteDanceCampaign campaign = this.getById(campaignId);
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_update");
        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", token.getAccountId());
        params.put("campaign_id", campaignId);
        params.put("modify_time", campaign.getModifyTime());
        if (null != campaignName && !"".equals(campaignName.trim())) {
            params.put("campaign_name", campaignName);
        }
        if (null != budgetMode && !"".equals(budgetMode.trim())) {
            params.put("budget_mode", budgetMode);
        }
        if (null != budget) {
            params.put("budget", budget);
        }
        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:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", jsonObject.getString("message"));
            resultMap.put("success",false);
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告组更新异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", jsonObject.getString("message"));
            resultMap.put("success",false);
            return resultMap;
        }
        this.getAdvertiserCampaign(token,campaignId+"",null);
        resultMap.put("code", 0);
        resultMap.put("message", "广告组信息修改成功");
        resultMap.put("success",true);
        return resultMap;
    }

    @Override
    public Map<String, Object> getAdvertiserCampaign(CtopOauthToken token, String ids, String date) {
        getAdvertiserCampaignByPageNumber(token, 1, ids, date);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("message", "获取广告組信息成功");
        return resultMap;
    }

    @Override
    public Map<String, Object>  updateCampaign(BytedanceCampaignEditVo editVo) {
        Map<String,Object>result = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(editVo.getAccountId());
        if(null == token){
            ResultMapUtils.setResultMap(result,StatusCode.COMMON_PARAM_ERROR);
            return result;
        }
        this.getAdvertiserCampaign(token,editVo.getId()+"",null);
        return this.updateCampaign(token,editVo.getId(),editVo.getCampaignName(),editVo.getBudgetMode(),editVo.getBudget());
    }

    private void getAdvertiserCampaignByPageNumber(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_campaign_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();
        filtering.put("status","CAMPAIGN_STATUS_ALL");
        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("campaign_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.error("获取广告组信息接口异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return;
        }
        JSONArray data = jsonObject.getJSONObject("data").getJSONArray("list");
        if (null == data || data.isEmpty()) {
            return;
        }
        List<ByteDanceCampaign> campaigns = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            JSONObject dataObject = data.getJSONObject(i);
            ByteDanceCampaign campaign = new ByteDanceCampaign(dataObject,token.getAccountId());
            campaigns.add(campaign);
        }
        campaignMapper.replaceBatch(campaigns);
        getAdvertiserCampaignByPageNumber(token, pageNumber + 1, ids, date);
    }

    @Override
    public Map<String, Object> updateCampaignStatus(Long accountId, String campaignIds, String optStatus) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken token = tokenService.getTokenByAccountId(accountId);
        this.getAdvertiserCampaign(token,null,null);
        JSONArray ids = new JSONArray();
        String[] getIds = campaignIds.split(StringUtils.COMMA);
        if (null != getIds && getIds.length > 0) {
            for (int i = 0; i < getIds.length; i++) {
                ids.add(Long.parseLong(getIds[i]));
            }
        }
        //2: 根据token以及用户id获取用户信息数据
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_campaign_update_status");
        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", token.getAccountId());
        params.put("campaign_ids", ids);
        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:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组更新0状态接口异常");
            resultMap.put("success", false);
            return resultMap;
        }
        JSONObject data = jsonObject.getJSONObject("data");
        if (null == data) {
            log.info("广告组更新状态异常==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            resultMap.put("code", -1);
            resultMap.put("message", "广告组操作异常");
            resultMap.put("success", false);
            return resultMap;
        }
        this.getAdvertiserCampaign(token,null,null);
        resultMap.put("code", 0);
        resultMap.put("message", "操作成功");
        resultMap.put("success", true);
        return resultMap;
    }
}
