package com.xxl.job.executor.report.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxl.job.executor.common.entity.CtopOauthToken;
import com.xxl.job.executor.report.entity.BytedanceFundDaily;
import com.xxl.job.executor.report.mapper.BytedanceFundDailyMapper;
import com.xxl.job.executor.report.service.IBytedanceFundDailyService;
import com.xxl.job.executor.utils.HttpUtils;
import com.xxl.job.executor.utils.PropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

/**
 * 账号日流水信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2020-04-08
 */
@Slf4j
@Service
@Primary

public class BytedanceFundDailyServiceImpl extends ServiceImpl<BytedanceFundDailyMapper, BytedanceFundDaily> implements IBytedanceFundDailyService {
    @Override
    public void loadFundDataByPage(CtopOauthToken token, String startDate, String endDate, Integer pageNum) {
        Integer pageSize = 100;
        JSONObject result = getAdvertiserFundDailyStat(token, startDate, endDate, pageNum, pageSize);
        if(null == result||result.isEmpty()){
            return;
        }
        var code = result.getInteger("code");
        var message = result.getString("message");
        if (null == code || code != 0) {
            log.error("账号日流水数据获取异常：{};accountId:{}", message, token.getAccountId());
            return;
        }
        JSONArray dataArray = result.getJSONObject("data").getJSONArray("list");
        if (null == dataArray || dataArray.isEmpty()) {
            return;
        }
        for (var i = 0; i < dataArray.size(); i++) {
            var data = dataArray.getJSONObject(i);
            var fundDaily = new BytedanceFundDaily(data, token);
            this.saveOrUpdate(fundDaily);
        }
        loadFundDataByPage(token, startDate, endDate, pageNum + 1);
    }

    public static JSONObject getAdvertiserFundDailyStat(CtopOauthToken token, String startDate, String endDate, Integer pageNum, Integer pageSize) {
        // 请求地址
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + PropertiesUtils.getValue("bytedance_config", "bytedance_v2_advertiser_fund_daily_stat");
        // 请求参数
        JSONObject params = new JSONObject();
        params.put("advertiser_id", token.getAccountId());
        params.put("start_date", startDate);
        params.put("end_date", endDate);
        params.put("page", pageNum);
        params.put("page_size", pageSize);
        return HttpUtils.bytedanceGetRequest(token.getAccessToken(), url, params);
    }
}
