package cn.com.ctop.track.controller;

import cn.com.ctop.track.service.ClickInfoService;
import cn.com.ctop.track.utils.Check;
import cn.com.ctop.track.utils.HttpUtils;
import com.alibaba.fastjson.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Controller
@RequestMapping("/convert")
public class TrackController {
    private static Logger logger = Logger.getLogger(TrackController.class);
    @Autowired
    private ClickInfoService clickInfoService;

    private static String url = "https://ugapi.alipay.com/monitor";
    static ExecutorService click1ExecutorService = Executors.newFixedThreadPool(15);
    static ExecutorService click2ExecutorService = Executors.newFixedThreadPool(15);
    static ExecutorService back1ExecutorService = Executors.newFixedThreadPool(15);
    static ExecutorService back2ExecutorService = Executors.newFixedThreadPool(15);


    // 老链接 屏蔽5
    @RequestMapping(value = "/click1")
    @ResponseBody
    public JSONObject click1(HttpServletRequest request,
                             HttpServletResponse response) {
//
        logger.info("快手点击监测回传1开始,回调值：" + request.getQueryString());
        JSONObject returnJson = new JSONObject();
        try {
            //test
            String action = "click";    // ⾏为类型 // 点击
            String accountid = request.getParameter("accountid");    //客户后台账户ID
            String partnerId = request.getParameter("partnerId");    //partnerId
            String pid = request.getParameter("pid");    //pid
            String requestFrom = request.getParameter("requestFrom");    //requestFrom
            String imei = request.getParameter("imei");
            String oaidmd5 = request.getParameter("oaidmd5");
            String adid = request.getParameter("adid");     //⼴告计划ID
            String campaignid = request.getParameter("campaignid");      // ⼴告组ID
            String cid = request.getParameter("cid"); // ⼴告创意ID
            String callback = request.getParameter("callback"); // ⼴告创意ID
            Map<String, String> headers = new HashMap<>();
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("action", action);
            params.put("requestFrom", requestFrom);
            params.put("pid", pid);
            params.put("partnerId", partnerId);
            if (!Check.isNull(imei)) {
                params.put("imei", imei);
            }
            if (!Check.isNull(oaidmd5)) {
                params.put("oaidmd5", oaidmd5);
            }
            if (!Check.isNull(accountid)) {
                params.put("accountid", accountid);
            }
            if (!Check.isNull(adid)) {
                params.put("adid", adid);
            }
            if (!Check.isNull(campaignid)) {
                params.put("campaignid", campaignid);
            }
            if (!Check.isNull(cid)) {
                params.put("cid", cid);
            }
            if (!Check.isNull(callback)) {
                String callbackUrl = "https://track.tjyourong.com.cn/convert/back1?kuaishouCallback=" + callback;
                params.put("callback", callbackUrl);
            }
            click1ExecutorService.submit(new Runnable() {
                @Override
                public void run() {
                    if (Check.isNull(oaidmd5) && Check.isNull(imei)) {
                        return;
                    }
                    JSONObject json = clickInfoService.getRtaInfo(oaidmd5, imei, null);
                    if (!Check.isNull(json)) {
                        Integer code = json.getInteger("code");
                        if (code == 10000) {
                            Boolean requiredFlow = json.getBoolean("requiredFlow");
                            if (requiredFlow) {
                                String s = HttpUtils.httpGetRequest(url, headers, params);
                                logger.info("快手点击监测1上报客户返回结果：" + s);
                            } else {
                                logger.info("客户rta返回结果为false，停止上报数据");
                            }
                        } else {
                            logger.info("调用rta返回结果错误:" + json);
                        }
                    }
                }
            });
            returnJson.put("code", 200);
            returnJson.put("success", true);
            returnJson.put("result", "success");
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("success", false);
            returnJson.put("result", e.getMessage());
        }
        return returnJson;
    }


    // 新链接 屏蔽8
    @RequestMapping(value = "/click2")
    @ResponseBody
    public JSONObject click2(HttpServletRequest request,
                             HttpServletResponse response) {

        logger.info("新沉流点击上报客户开始：：" + request.getQueryString());
        JSONObject returnJson = new JSONObject();
        try {
            String action = "click";    // ⾏为类型 // 点击
            String imei = request.getParameter("imei");
            String oaidmd5 = request.getParameter("oaidmd5");
            if (Check.isNull(oaidmd5) && Check.isNull(imei)) {
                returnJson.put("code", 500);
                returnJson.put("success", false);
                return returnJson;
            }
            String accountid = request.getParameter("accountid");    //客户后台账户ID
            String partnerId = request.getParameter("partnerId");    //partnerId
            String pid = request.getParameter("pid");    //pid
            String requestFrom = request.getParameter("requestFrom");    //requestFrom
            String adid = request.getParameter("adid");     //⼴告计划ID
            String campaignid = request.getParameter("campaignid");      // ⼴告组ID
            String cid = request.getParameter("cid"); // ⼴告创意ID
            String callback = request.getParameter("callback"); // ⼴告创意ID
            String timestamp = request.getParameter("timestamp"); // 编号
            Map<String, String> headers = new HashMap<>();
            TreeMap<String, Object> params = new TreeMap<>();
            params.put("action", action);
            params.put("requestFrom", requestFrom);
            params.put("pid", pid);
            params.put("partnerId", partnerId);

            if (!Check.isNull(oaidmd5)) {
                params.put("oaidmd5", oaidmd5);
            }
            if (!Check.isNull(imei)) {
                params.put("imei", imei);
            }
            if (!Check.isNull(adid)) {
                params.put("adid", adid);
            }
            if (!Check.isNull(campaignid)) {
                params.put("campaignid", campaignid);
            }
            if (!Check.isNull(cid)) {
                params.put("cid", cid);
            }
            if (!Check.isNull(timestamp)) {
                params.put("timestamp", timestamp);
            }
            params.put("accountid", accountid);

            if (!Check.isNull(callback)) {
                String callbackUrl = "https://track.tjyourong.com.cn/convert/back2?kuaishouCallback=" + callback;
                params.put("callback", callbackUrl);

            }
            click2ExecutorService.submit(new Runnable() {
                @Override
                public void run() {
                    if (Check.isNull(oaidmd5) && Check.isNull(imei)) {
                        return;
                    }
                    String s = HttpUtils.httpGetRequest(url, headers, params);
                    logger.info("新沉流快手点击监测上报客户返回结果：" + s);

                }
            });
            returnJson.put("code", 200);
            returnJson.put("success", true);
            returnJson.put("result", "success");
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("success", false);
            returnJson.put("result", e.getMessage());
        }
        return returnJson;
    }


    // 老链接 屏蔽5
    @RequestMapping(value = "/back1")
    @ResponseBody
    public JSONObject back1(HttpServletRequest request,
                            HttpServletResponse response) {

        logger.info("支付宝唤起回传1开始，回传值：" + request.getQueryString());
        JSONObject returnJson = new JSONObject();
        try {

            String url = request.getParameter("kuaishouCallback");
            String transformtype = request.getParameter("transformtype");
            if ("5".equals(transformtype)) {
                returnJson.put("code", 200);
                returnJson.put("success", true);
                returnJson.put("result", "success");
                returnJson.put("message", "回传事件为5，跳过");
                logger.info("回传媒体唤起结果返回结果为5，跳过");
            } else if ("8".equals(transformtype)) {
                Map<String, String> headers = new HashMap<>();
                String event_type = "84";
                back1ExecutorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        String s = HttpUtils.backHttpGetRequest(url, headers, event_type);
                        logger.info("回传媒体唤起结果1返回结果：" + s);
                    }
                });
                returnJson.put("code", 200);
                returnJson.put("success", true);
                returnJson.put("result", "success");
            }
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("success", false);
            returnJson.put("result", e.getMessage());
        }
        return returnJson;
    }


    // 新链接 屏蔽8
    @RequestMapping(value = "/back2")
    @ResponseBody
    public JSONObject back2(HttpServletRequest request,
                            HttpServletResponse response) {

        logger.info("新沉流客户唤起回传开始：" + request.getQueryString());
        JSONObject returnJson = new JSONObject();
        try {
            String url = request.getParameter("kuaishouCallback");
            String transformtype = request.getParameter("transformtype");
            if ("5".equals(transformtype)) {
                Map<String, String> headers = new HashMap<>();
                String event_type = "84";
                back2ExecutorService.submit(new Runnable() {
                    @Override
                    public void run() {
                        String s = HttpUtils.backHttpGetRequest(url, headers, event_type);
                        logger.info("新沉流回传媒体唤起结果返回结果：" + s);
                    }
                });
                returnJson.put("code", 200);
                returnJson.put("success", true);
                returnJson.put("result", "success");
            }
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("success", false);
            returnJson.put("result", e.getMessage());
        }
        return returnJson;
    }


}
