package cn.com.ctop.toutiao.modules.report.controller;


import cn.com.ctop.common.module.service.IBytedanceProjectService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.toutiao.modules.tool.callback.AuthTokenUtil;
import cn.com.ctop.toutiao.modules.tool.callback.BaseResponse;
import cn.com.ctop.toutiao.modules.tool.callback.CallbackResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@Slf4j
@RestController
@RequestMapping("/bytedance/push")
public class BytedancePushDataController {
    private static String secretKey = "156a5d76ad354b43865ef57e5e416ca7";
    private static ExecutorService projectExecutorService = Executors.newFixedThreadPool(5);

    @Autowired
    private IBytedanceProjectService bytedanceProjectService;


    @RequestMapping(value = "/bytedanceProjectData", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public CallbackResponse bytedanceProjectData(HttpServletRequest request, @RequestParam(value = "challenge", defaultValue = "0") int challenge, @RequestParam(value = "event", defaultValue = "") String event, @RequestParam(value = "appId", defaultValue = "") String appId) throws IOException {

        if (null != event && event.equals("verify_webhook")) {
            return new CallbackResponse(BaseResponse.ok(), challenge);
        }
        // 数据接收，验证消息
        AuthTokenUtil.InputStreamCacher cacher = new AuthTokenUtil.InputStreamCacher(request.getInputStream());
        boolean isValidToken = AuthTokenUtil.isValidToken(secretKey, cacher, request.getHeader("X-Open-Signature"));
        if (!isValidToken) {
            return new CallbackResponse(new BaseResponse(400, "invalid token"), 0);
        }
        JSONObject result = (JSONObject) JSONObject.parse(new String(AuthTokenUtil.readAsBytes(cacher)));
        log.info("---广告物料推送  task_id:{}\n转译结果：{}", result.getString("subscribe_task_id"), result);
        if (!Check.isNull(result)) {
            JSONArray advertiserIds = result.getJSONArray("advertiser_ids");
            Long advertiserId;
            if (!Check.isNull(advertiserIds)) {
                advertiserId = advertiserIds.getLong(0);
            } else {
                advertiserId = null;
            }
            JSONObject data = result.getJSONObject("data");
            if (!Check.isNull(data)) {
                JSONObject content = data.getJSONObject("content");
                if (!Check.isNull(content)) {
                    JSONArray idArr = content.getJSONArray("promotion_ids");
                    List<Long> idList = JSONArray.parseArray(idArr.toJSONString(), Long.class);
                    List<List<Long>> moreList = Lists.partition(idList, 20);
                    for (List<Long> ids : moreList) {
                        projectExecutorService.submit(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject tokenJson = bytedanceProjectService.getTokenByAccountId(advertiserId);
                                if (!Check.isNull(tokenJson)) {
                                    String accessToken = tokenJson.getString("accessToken");
                                    Integer accountStatus = tokenJson.getInteger("accountStatus");
                                    if (!Check.isNull(accountStatus)) {
                                        if (accountStatus == 0) {
                                            Map<Long, JSONObject> projectMap = new HashMap<>();
                                            bytedanceProjectService.getPromotionList(advertiserId, accessToken, ids, projectMap, 1);
                                        } else {
                                            log.error("此账户已暂停，跳过预警,accountId:{}", advertiserId);
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        return new CallbackResponse(BaseResponse.ok(), 0);
    }


    @RequestMapping(value = "/test", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public void test(HttpServletRequest request, @RequestParam(value = "challenge", defaultValue = "0") int challenge, @RequestParam(value = "event", defaultValue = "") String event, @RequestParam(value = "appId", defaultValue = "") String appId) throws IOException {

        //   bytedanceProjectService.sendAuthFailure(1847120413784843L);
        JSONObject token = bytedanceProjectService.getTokenByAccountId(1842948124549184L);

        List<Long> list = new ArrayList<>();
        list.add(7570918730826416178L);
        //  list.add(7566848458911367211L);


        Map<Long, JSONObject> projectMap = new HashMap<>();
        List<List<Long>> partitions = Lists.partition(list, 20);
        for (int i = 0; i < partitions.size(); i++) {
            List<Long> ids = partitions.get(i);
            bytedanceProjectService.getPromotionList(1842948124549184L, token.getString("accessToken"), ids, projectMap, 1);

        }
    }


}
