package ctop.bytedance.ad.advertise.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import ctop.bytedance.ad.advertise.entity.ByteDanceCampaign;
import ctop.bytedance.ad.advertise.mapper.ByteDanceCampaignMapper;
import ctop.bytedance.ad.advertise.service.IByteDanceCampaignService;
import ctop.bytedance.ad.advertise.vo.BytedanceCampaignEditVo;
import ctop.bytedance.ad.common.entity.CtopOauthToken;
import ctop.bytedance.ad.common.service.ICtopOauthTokenService;
import ctop.bytedance.ad.common.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
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 {
    @Resource
    private ByteDanceCampaignMapper campaignMapper;
    @Autowired
    private ICtopOauthTokenService tokenService;



    @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());
        return null;
    }

    @Override
    public ByteDanceCampaign getOneByParams(Long accountId, String campaignName) {
        QueryWrapper<ByteDanceCampaign> queryWrapper = new QueryWrapper<>();
        if(null!=accountId&&accountId!=0){
            queryWrapper.eq("account_id",accountId);
        }
        if(!Check.isNull(campaignName)){
            queryWrapper.like("name",campaignName);
        }
        queryWrapper.orderByDesc("create_time").last("limit 1");
        return this.getOne(queryWrapper);

    }

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



}
