package cn.com.ctop.track.controller;

import cn.com.ctop.track.entity.TrackRta;
import cn.com.ctop.track.service.ClickInfoService;
import cn.com.ctop.track.service.ConvertInfoService;
import cn.com.ctop.track.service.TaobaoNoticeService;
import cn.com.ctop.track.utils.Check;
import cn.com.ctop.track.utils.HttpUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

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

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
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;
    @Autowired
    private TaobaoNoticeService taobaoNoticeService;
    @Autowired
    private ConvertInfoService convertInfoService;
    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);
    @Autowired
    private MongoTemplate mongoTemplate;

    // 老链接 屏蔽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 imei = request.getParameter("imei");
            String oaidmd5 = request.getParameter("oaidmd5");
            String accountid = request.getParameter("accountid");    //⼴告账户ID
            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", "huichuang");
            params.put("pid", "2088821582878450");
            params.put("partnerId", "tab3huichuangapkhuichuang");
            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 {
            //test
            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 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", "huichuang");
            params.put("pid", "2088821582878450");
            params.put("partnerId", "tab3huichuangapkhuichuang");
            if (!Check.isNull(oaidmd5)) {
                params.put("oaidmd5", oaidmd5);
            }
            if (!Check.isNull(imei)) {
                params.put("imei", imei);
            }

            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/back2?kuaishouCallback=" + callback;
                params.put("callback", callbackUrl);

            }


            click2ExecutorService.submit(new Runnable() {
                @Override
                public void run() {
                    if (Check.isNull(oaidmd5) && Check.isNull(imei)) {
                        return;
                    }
                    /*   JSONObject json = clickInfoService.getRtaInfo(oaidmd5, imei, "tab3xcl");
                    if (!Check.isNull(json)) {
                        Integer code = json.getInteger("code");
                        if (code == 10000) {
                            Boolean requiredFlow = json.getBoolean("requiredFlow");
                            if (requiredFlow) {
                                JSONArray rtaInfoList = json.getJSONArray("rtaInfoList");
                                if (Check.isNull(rtaInfoList)) {
                                    logger.info("rta返回策略列表为空，跳过上传");
                                    return;
                                }
                                Boolean isRtaAccount = false;
                                for (int i = 0; i < rtaInfoList.size(); i++) {
                                    JSONObject jsonObject = rtaInfoList.getJSONObject(i);
                                    String accountId = jsonObject.getString("account_id");
                                    if ("tab3xcl".equals(accountId)) {
                                        isRtaAccount = true;
                                        break;
                                    }
                                }
                                if (isRtaAccount) {
                                    String s = HttpUtils.httpGetRequest(url, headers, params);
                                    logger.info("新沉流快手点击监测上报客户返回结果：" + s);
                                    JSONObject mongoVo = new JSONObject();
                                    if (!Check.isNull(oaidmd5)) {
                                        mongoVo.put("_id", oaidmd5);
                                    } else if (!Check.isNull(imei)) {
                                        mongoVo.put("_id", imei);
                                    }
                                    long timestamp = System.currentTimeMillis() / 1000;
                                    mongoVo.put("timestamp", timestamp);
                                    mongoTemplate.save(mongoVo, "trackRta");
                                } else {
                                    logger.info("新沉流客户rta返回策略列表未命中：tab3xcl，停止上报数据，返回数据：" + json);
                                }
                            } else {
                                logger.info("新沉流客户rta返回结果为false，停止上报数据");
                            }
                        } else {
                            logger.info("新沉流调用rta返回结果错误:" + json);
                        }
                    }*/

                    System.err.println("入参:" + params);
                    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 ("8".equals(transformtype)) {
                returnJson.put("code", 200);
                returnJson.put("success", true);
                returnJson.put("result", "success");
                returnJson.put("message", "回传事件为8，跳过");
                logger.info("新沉流回传媒体唤起结果返回结果为8，跳过");
            } else 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);

                     /*   Criteria criteria = new Criteria();
                        criteria = Criteria.where("_id").is(id);
                        Query query = new Query(criteria);
                        TrackRta one = mongoTemplate.findOne(query, TrackRta.class);
                        if (Check.isNull(one)) {
                            logger.error("客户回传信息未在mongodb中查到，跳过此回传");
                            return;
                        }
                        Long timestamp = one.getTimestamp();
                        long nowTamp = System.currentTimeMillis() / 1000;
                        if (nowTamp - timestamp <= 1800) {
                            String s = HttpUtils.backHttpGetRequest(url, headers, event_type);
                            logger.info("新沉流回传媒体唤起结果返回结果：" + s);
                        } else {
                            logger.error("客户回传信息超过30分钟时限，跳过此回传,返回id:" + id);
                        }*/
                    }
                });
                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;
    }


}
