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.IByteDanceGetAccountFundService;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.SystemDateConstant;
import org.jeecg.common.util.DateUtils;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class ByteDanceGetAccountFundServiceImpl implements IByteDanceGetAccountFundService {

    @Override
    public JSONObject getAccountFundBy(CtopOauthToken token, Long advertiserId) {

        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",advertiserId);

        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.httpGetRequest(QueryToolUrlConstant.GET_ADVERTISER_FUND, headers,params));
        if(jsonObject.getInteger("code")!=0){
            XxlJobHelper.log("查询账户余额失败==》accountId:{},message:{}", token.getAccountId(), jsonObject.getString("message"));
            return null;
        }
        return jsonObject.getJSONObject("data");
    }

    @Override
    public JSONObject getAccountReportBy(CtopOauthToken token, Long advertiserId) {

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

        String now = DateUtils.getNowDate(SystemDateConstant.yyyy_MM_dd);
        JSONObject params=new JSONObject();
        params.put("advertiser_id",advertiserId);
        params.put("start_date",now);
        params.put("end_date",now);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.httpGetRequest(QueryToolUrlConstant.GET_ADVERTISER_REPORT, headers,params));
        if(jsonObject.getInteger("code")!=0){
            XxlJobHelper.log("账户{}获取实时数据失败---{}",advertiserId,jsonObject.getString("message"));
        }else {
            result= (JSONObject) jsonObject.getJSONObject("data").getJSONArray("list").get(0);
        }
        return result;
    }
}
