package cn.com.ctop.kuaishou.modules.clean.controller;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.kuaishou.modules.clean.mapper.KuaishouAccountCleanTemplateMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 快手-账户清理
 * @Author: zzy
 * @Date: 2021-07-20
 * @Version: V1.0
 */
@RestController
@RequestMapping("/estimatePeopleNumber")
@Slf4j
public class EstimatePepoleNumberController {

    private final String OPEN_API_URL_PREFIX = "https://ad.e.kuaishou.com/rest/openapi/v1/";
    private final String ACCOUNT_LIST_URL = "tool/audience/prediction";

    @Resource
    CtopOauthTokenMapper ctopOauthTokenMapper;

    @Resource
    KuaishouAccountCleanTemplateMapper kuaishouAccountCleanTemplateMapper;


    /**
     * 获取人群预估数量
     *
     * @param map
     * @return
     */
    @PostMapping("/getCount")
    public JSONObject getCount(@RequestBody HashMap map) {
        return sendHttpRequest(map, ACCOUNT_LIST_URL, String.valueOf(map.get("advertiser_id")));
    }

    /**
     * 根据账户ID获取项目ID
     *
     * @param accountId
     * @return
     */
    @GetMapping("/getProjectId")
    public Result getProjectId(@Param("accountId") String accountId) {
        Result result=new Result();
        String projectId = kuaishouAccountCleanTemplateMapper.getProjectId(accountId);
        result.setSuccess(true);
        result.setResult(projectId);
        return result;
    }
    /**
     * 根据地址请求巨量殷勤，返回响应结果
     *
     * @author zzy
     * @Param data 请求参数    apiUrl请求路径
     * @create: 2021-07-14
     */
    public JSONObject sendHttpRequest(Map data, String apiUrl, String accountId) {
        String access_token = getToken(accountId);
        // 构造请求
        HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
            @Override
            public String getMethod() {
                return "POST";
            }
        };

        httpEntity.setHeader("Access-Token", access_token);

        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;

        try {
            client = HttpClientBuilder.create().build();
            httpEntity.setURI(URI.create(OPEN_API_URL_PREFIX + apiUrl));
            httpEntity.setEntity(new StringEntity(JSONObject.toJSONString(data), ContentType.APPLICATION_JSON));

            response = client.execute(httpEntity);
            if (response != null && response.getStatusLine().getStatusCode() == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer result = new StringBuffer();
                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                bufferedReader.close();
                return JSONObject.parseObject(result.toString());
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 获取token
     *
     * @author zzy
     * @create: 2021-07-14
     */
    public String getToken(String accountId) {
        CtopOauthToken ctopOauthToken = ctopOauthTokenMapper.selectByAccountId(Long.parseLong(accountId));
        if (ctopOauthToken != null) {
            return ctopOauthToken.getAccessToken();
        } else {
            log.info("未查询到Token");
            return null;
        }
    }
}
