package cn.com.ctop.track.controller;

import cn.com.ctop.track.util.RedisUtil;
import cn.com.ctop.track.utils.Check;
import cn.com.ctop.track.utils.HttpUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Controller
@Slf4j
@RequestMapping("/jdCallback")
public class JingDongCpaController {
    private static Logger logger = Logger.getLogger(JingDongCpaController.class);
    @Autowired
    private RedisUtil redisUtil;


    // 老链接 屏蔽5
    @RequestMapping(value = "/click")
    @ResponseBody
    public JSONObject click(HttpServletRequest request,
                            HttpServletResponse response) {
        logger.info("点击回调数据：" + request.getQueryString());
        JSONObject returnJson = new JSONObject();
        String queryString = request.getQueryString();
        if (Check.isNull(queryString)) {
            returnJson.put("code", 200);
            returnJson.put("message", "SUCCESS");
            return returnJson;
        }
        try {
            String requestId = request.getParameter("requestId");    //客户后台账户ID
            if (Check.isNull(requestId)) {
                returnJson.put("code", 200);
                returnJson.put("message", "SUCCESS");
                return returnJson;
            }
            JSONObject paramJson = new JSONObject();
            String callback = request.getParameter("callback");
            paramJson.put("callback", callback);
            String accountId = request.getParameter("p1");
            paramJson.put("accountId", accountId);
            redisUtil.add(requestId, paramJson, 3, TimeUnit.DAYS);
            returnJson.put("code", 200);
            returnJson.put("message", "SUCCESS");
        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("success", false);
            returnJson.put("result", e.getMessage());
        }
        return returnJson;
    }


    @RequestMapping(value = "/action")
    @ResponseBody
    public JSONObject action(HttpServletRequest request,
                             HttpServletResponse response) {
        logger.info("行为回调数据：" + request.getQueryString());
        JSONObject returnJson = new JSONObject();
        String queryString = request.getQueryString();
        if (Check.isNull(queryString)) {
            returnJson.put("code", 200);
            returnJson.put("message", "SUCCESS");
            return returnJson;
        }
        try {
            String requestId = request.getParameter("cid");    //客户后台账户ID
            String jd_event_type = request.getParameter("event_type");    //1 激活 4 表单提交
            String event_time = request.getParameter("event_time");    //时间
            if (jd_event_type.equals("1") || jd_event_type.equals("4")) {
                String s = redisUtil.get(requestId);
                if (!Check.isNull(s)) {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    Long accountId = jsonObject.getLong("accountId");
                    String callback = jsonObject.getString("callback");
                    if (Check.isNull(accountId) || Check.isNull(callback)) {
                        returnJson.put("code", 200);
                        returnJson.put("message", "SUCCESS");
                        return returnJson;
                    }
                    TreeMap<String, Object> params = new TreeMap<>();
                    String eventAccountKey = "event_" + accountId;
                    String eventType = redisUtil.get(eventAccountKey);
                    if (eventType.equals("1")) { // 转化类型为订单提交  订单提交回传订单提交 其他不关注
                        if (jd_event_type.equals("4")) {
                            String returnedKey = "returned_" + 14 + "_" + requestId;
                            String isReturned = redisUtil.get(returnedKey);
                            if (!Check.isNull(isReturned)) {
                                log.info("此点击链接已回传，clickId:{}", requestId);
                                returnJson.put("code", 200);
                                returnJson.put("message", "SUCCESS");
                                return returnJson;
                            }
                            params.put("event_type", 14);
                            params.put("event_time", event_time);
                            String eventAccountCountKey = "event_count_" + jd_event_type + accountId;
                            String countStr = redisUtil.get(eventAccountCountKey);
                            if (Check.isNull(countStr)) {
                                redisUtil.add(eventAccountCountKey, 1);
                            } else {
                                Integer postCount = Integer.valueOf(countStr);
                                if (postCount < 9) {
                                    redisUtil.add(eventAccountCountKey, postCount + 1);
                                } else {
                                    redisUtil.add(eventAccountCountKey, 0);
                                    log.info("扣量不回传，clickId:{}", requestId);
                                    returnJson.put("code", 200);
                                    returnJson.put("message", "SUCCESS");
                                    return returnJson;
                                }
                            }
                            redisUtil.add(returnedKey, 1, 2, TimeUnit.DAYS);
                        } else {
                            returnJson.put("code", 200);
                            returnJson.put("message", "SUCCESS");
                            return returnJson;
                        }

                    } else if (eventType.equals("2")) {
                        if (jd_event_type.equals("1")) {
                            String returnedKey = "returned_" + 2 + "_" + requestId;
                            String isReturned = redisUtil.get(returnedKey);
                            if (!Check.isNull(isReturned)) {
                                log.info("此点击链接已回传，clickId:{}", requestId);
                                returnJson.put("code", 200);
                                returnJson.put("message", "SUCCESS");
                                return returnJson;
                            }
                            params.put("event_type", 2);
                            params.put("event_time", event_time);
                            String eventAccountCountKey = "event_count_" + jd_event_type + accountId;
                            String countStr = redisUtil.get(eventAccountCountKey);
                            if (Check.isNull(countStr)) {
                                redisUtil.add(eventAccountCountKey, 1);
                            } else {
                                Integer postCount = Integer.valueOf(countStr);
                                if (postCount < 9) {
                                    redisUtil.add(eventAccountCountKey, postCount + 1);
                                } else {
                                    redisUtil.add(eventAccountCountKey, 0);
                                    log.info("扣量不回传，clickId:{}", requestId);
                                    returnJson.put("code", 200);
                                    returnJson.put("message", "SUCCESS");
                                    return returnJson;
                                }
                            }

                            redisUtil.add(returnedKey, 1, 2, TimeUnit.DAYS);
                        } else if (jd_event_type.equals("4")) {
                            String returnedKey = "returned_" + 1 + "_" + requestId;
                            String isReturned = redisUtil.get(returnedKey);
                            if (!Check.isNull(isReturned)) {
                                log.info("此点击链接已回传，clickId:{}", requestId);
                                returnJson.put("code", 200);
                                returnJson.put("message", "SUCCESS");
                                return returnJson;
                            }
                            params.put("event_type", 1);
                            params.put("event_time", event_time);
                            String eventAccountCountKey = "event_count_" + jd_event_type + accountId;
                            String countStr = redisUtil.get(eventAccountCountKey);
                            if (Check.isNull(countStr)) {
                                redisUtil.add(eventAccountCountKey, 1);
                            } else {
                                Integer postCount = Integer.valueOf(countStr);
                                if (postCount < 9) {
                                    redisUtil.add(eventAccountCountKey, postCount + 1);
                                } else {
                                    redisUtil.add(eventAccountCountKey, 0);
                                    log.info("扣量不回传，clickId:{}", requestId);
                                    returnJson.put("code", 200);
                                    returnJson.put("message", "SUCCESS");
                                    return returnJson;
                                }

                            }
                            redisUtil.add(returnedKey, 1, 2, TimeUnit.DAYS);
                        } else {
                            returnJson.put("code", 200);
                            returnJson.put("message", "SUCCESS");
                            return returnJson;
                        }
                    }
                    StringBuffer stringBuffer = new StringBuffer();
                    params.forEach((k, v) -> {
                        stringBuffer.append("&").append(k).append("=").append(v);

                    });
                    callback += stringBuffer.toString();
                    String result = HttpUtils.KuaiShouttpGetRequestNew(callback, null);
                    log.info("信息上报媒体返回结果：{}", result.toString());
                }
            }


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


    @GetMapping(value = "/addAccountEvent")
    @ResponseBody
    public JSONObject addAccountEvent(String accountId, String type) {
        JSONObject returnJson = new JSONObject();

        try {
            if (Check.isNull(accountId)) {
                throw new Exception("账户ID不能为空");
            }

            if (Check.isNull(type)) {
                throw new Exception("type不能为空");
            }
            Integer typeInt = Integer.valueOf(type);
            if (typeInt == 0 || typeInt > 2) {
                throw new Exception("type值只能是1或2");
            }
            String key = "event_" + accountId;
            redisUtil.add(key, typeInt);
            returnJson.put("code", 200);
            returnJson.put("message", "添加成功");
            returnJson.put("accountId", accountId);
            returnJson.put("type", type);

        } catch (Exception e) {
            returnJson.put("code", 500);
            returnJson.put("message", e.getMessage());
        }
        return returnJson;
    }


    public static void main(String[] args) {
        Integer i = 0;
        i = i + 1;
        System.err.println(i);
    }

}
