package com.duiba.tuia.youtui.web.tool;

import cn.com.duiba.wolf.utils.SecurityUtils;
import cn.com.duiba.wolf.utils.UrlUtils;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.constant.Constants;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

import com.duiba.tuia.youtui.web.constant.DmCookieHolder;
import org.apache.commons.lang.StringUtils;

/**
 * 埋点工具类.
 */
public class EmbedUtil {

    /**
     * The Constant MEITUAN_URL.
     */
    private static final String MEITUAN_URL = "http://i.meituan.com/firework/";

    /**
     * The Constant MEITUAN_FROM.
     */
    private static final String MEITUAN_FROM = "duiba";

    /**
     * The Constant MEITUAN_SALT.
     */
    private static final String MEITUAN_SALT = "d442c590d699";

    /**
     * The Constant MEITUAN_END.
     */
    private static final String MEITUAN_END = "&utm_source=waputm_dbjfhd&utm_medium=wap";

    /**
     * The Constructor.
     */
    private EmbedUtil() {
    }

    /**
     * exposure:(这里用一句话描述这个方法的作用). <br/>
     *
     * @param appId the app id
     * @param consumerId the consumer id
     * @param ip the ip
     * @param os the os
     * @param buttonType the button type
     * @param infoType the info type
     * @param info the info
     * @return the JSON object
     * @since JDK 1.6
     */
    public static JSONObject exposure(Long appId, Long consumerId, String ip, String os, String buttonType,
                                      String infoType, Object info) {
        JSONObject json = new JSONObject();
        String clickUrl = DomainConstantUtil.getAppEmbedClickUrl();
        boolean isEmbed = true;
        if (clickUrl == null || clickUrl.length() == 0) {
            isEmbed = false;
        }
        json.put("domain", DomainConstantUtil.getAppEmbedClickUrl());
        // 应用id
        json.put("app_id", appId);
        // 用户id
        json.put("consumer_id", consumerId);
        // 登陆状态（未登录：0，登陆：1）
        json.put("login_type", 1);
        // 按钮埋点号码
        json.put("button_type", buttonType);
        // 细节类型
        json.put("info_type", infoType);
        // 细节
        json.put("info", info);
        // ip
        json.put("ip", ip);
        // os
        json.put("os", os);
        // 判断 是否埋点（true 埋点）
        json.put("isEmbed", isEmbed);
        return json;
    }

    /**
     * exposure4elastic:(这里用一句话描述这个方法的作用). <br/>
     *
     * @param appId the app id
     * @param consumerId the consumer id
     * @param ip the ip
     * @param os the os
     * @param buttonType the button type
     * @param infoType the info type
     * @param itemId the item id
     * @return the JSON object
     * @since JDK 1.6
     */
    public static JSONObject exposure4elastic(Long appId, Long consumerId, String ip, String os, String buttonType,
                                              String infoType, Long itemId) {
        JSONObject json = exposure(appId, consumerId, ip, os, buttonType, infoType, null);
        json.put("item_id", itemId);
        return json;
    }

    /**
     * exposure:(这里用一句话描述这个方法的作用). <br/>
     *
     * @param appId the app id
     * @param consumerId the consumer id
     * @param ip the ip
     * @param os the os
     * @param buttonType the button type
     * @param infoType the info type
     * @param info the info
     * @param duibaActivityId the duiba activity id
     * @param activityId the activity id
     * @return the JSON object
     * @since JDK 1.6
     */
    public static JSONObject exposure(Long appId, Long consumerId, String ip, String os, String buttonType,
                                      String infoType, Long info, Long duibaActivityId, Long activityId) {
        JSONObject json = new JSONObject();
        String clickUrl = DomainConstantUtil.getAppEmbedClickUrl();
        boolean isEmbed = true;
        if (clickUrl == null || clickUrl.length() == 0) {
            isEmbed = false;
        }
        json.put("domain", DomainConstantUtil.getAppEmbedClickUrl());
        // 应用id
        json.put("app_id", appId);
        // 用户id
        json.put("consumer_id", consumerId);
        // 登陆状态（未登录：0，登陆：1）
        json.put("login_type", 1);
        // 按钮埋点号码
        json.put("button_type", buttonType);
        // 按钮埋点号码
        json.put("activity_type", 11);
        // 细节类型
        json.put("info_type", infoType);
        // 细节
        json.put("info", info);
        // ip
        json.put("ip", ip);
        // os
        json.put("os", os);
        // os
        json.put("duiba_activity_id", duibaActivityId);
        // os
        json.put("activity_id ", activityId);
        // 判断 是否埋点（true 埋点）
        json.put("isEmbed", isEmbed);
        return json;
    }

    /**
     * emdExporForActivity:(这里用一句话描述这个方法的作用). <br/>
     *
     * @param map the map
     * @return the string
     * @since JDK 1.6
     */
    public static String emdExporForActivity(Map<String, Object> map) {
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            json.put(luckyToBiLogName(entry.getKey()), entry.getValue());
        }
        json.put("domain", DomainConstantUtil.getAppEmbedClickUrl());
        return json.toJSONString();
    }

    /**
     * 埋点json 数据组长.
     *
     * @param map 请求前的参数数组
     * @return 要请求的参数数组
     */
    public static JSONObject emdExporFromMap(Map<String, Object> map) {
        JSONObject json = new JSONObject();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            json.put(luckyToBiLogName(entry.getKey()), entry.getValue());
        }
        json.put("domain", DomainConstantUtil.getAppEmbedClickUrl());
        return json;
    }

    /**
     * luckyToBiLogName:福袋埋点名字转换. <br/>
     *
     * @param luckName the luck name
     * @return the string
     * @since JDK 1.6
     */
    public static String luckyToBiLogName(String luckName) {
        if ("appId".equals(luckName)) {
            return "app_id";
        } else if ("buttonType".equals(luckName)) {
            return "button_type";
        } else if ("consumerId".equals(luckName)) {
            return "consumer_id";
        } else if ("infoType".equals(luckName)) {
            return "info_type";
        } else if ("loginType".equals(luckName)) {
            return "login_type";
        } else {
            return luckName;
        }
    }

    /**
     * getEncryptUrl:(这里用一句话描述这个方法的作用). <br/>
     *
     * @param sellerUrl the seller URL
     * @param consunmerId the consunmer id
     * @return the encrypt URL
     * @since JDK 1.6
     */
    public static String getEncryptUrl(String sellerUrl, Long consunmerId) {
        // 美团特殊加密处理
        if (StringUtils.isNotBlank(sellerUrl) && sellerUrl.contains(MEITUAN_URL)) {
            // url参数键值对
            StringBuilder urlParam = new StringBuilder();

            Map<String, String> mapRequest = UrlUtils.uRLRequest(sellerUrl);
            // 循环商家URL自带的参数
            for (Map.Entry<String, String> entry : mapRequest.entrySet()) {
                String strRequestKey = entry.getKey();
                if (urlParam.length() == 0) {
                    urlParam.append(strRequestKey + "=" + mapRequest.get(strRequestKey));
                } else {
                    urlParam.append("&" + strRequestKey + "=" + mapRequest.get(strRequestKey));
                }
            }
            String sign = SecurityUtils.encode2StringByMd5(consunmerId + MEITUAN_FROM + MEITUAN_SALT).toLowerCase().substring(0,
                    32);
            sellerUrl = UrlUtils.urlPage(sellerUrl) + "?code=" + consunmerId + "&sign=" + sign + "&from="
                    + MEITUAN_FROM + "&" + urlParam.toString() + MEITUAN_END;
        }
        return sellerUrl;
    }

    /**
     * exposureUserInfo. <br/>
     * 会根据登录信息把用户相关信息塞进去
     *
     * @return the JSON object
     * @since JDK 1.6
     */
    public static JSONObject emdUserInfo() {
        JSONObject json = new JSONObject();
        RequestLocal current = RequestLocal.get();
        Long appId = current.getAppId();
        Long consumerId = current.getCid();
        String ip = current.getIp();
        String os = current.getOs();
        String sessionId = current.getCidCookie();

        json.put("domain", DomainConstantUtil.getAppEmbedClickUrl());
        json.put("app_id", appId);
        json.put("consumer_id", consumerId);
        json.put("login_type", 1);
        json.put("os", os);
        json.put("ip", ip);
        json.put("session_id", sessionId);

        return json;
    }

    /**
     * 记录cookie中的活动来源. sourceId=引导页id sourceType 1:主会场2：活动中心 dpm 流量入口
     *
     * @param request the request
     * @param map the map
     */
    public static void getSourceMap(HttpServletRequest request, Map<String, String> map, String couponSource, String id) {
        String sourceId = RequestTool.getCookie(request, Constants.COOKIEKEY.SOURCEID);
        String sourceType = RequestTool.getCookie(request, Constants.COOKIEKEY.SOURCETYPE);
        if(StringUtils.isBlank(couponSource)){
            return;
        }
        String type;
        switch(couponSource){
            case "plugin" : {
                type = Constants.COOKIEKEY.PLUGIN;
                break;
            }
            case "game" : {
                type = Constants.COOKIEKEY.GAME;
                break;
            }
            default: {
                type = Constants.COOKIEKEY.ACT;
            }
        }
        String ret = RequestTool.getCookie(request, Constants.COOKIEKEY.RET);
        DmCookieHolder dmCookie = CookieUtil.getDmCookie(type, id);
        if(dmCookie!=null){
            if (StringUtils.isNotEmpty(dmCookie.getDpm())) {
                map.put(Constants.KEY.DPM, dmCookie.getDpm());
            }
            if (StringUtils.isNotEmpty(dmCookie.getDcm())) {
                map.put(Constants.KEY.DCM, dmCookie.getDcm());
            }
            if (StringUtils.isNotBlank(dmCookie.getDsm())) {
                map.put(Constants.KEY.DSM, dmCookie.getDsm());
            }
        }
        if (StringUtils.isNotEmpty(sourceId)) {
            map.put("sourceId", sourceId);
        }
        if (StringUtils.isNotEmpty(sourceType)) {
            map.put("sourceType", sourceType);
        }

        if (StringUtils.isNotBlank(ret)) {
            map.put(Constants.COOKIEKEY.RET, ret);
        }

        String styleType = request.getParameter(Constants.VALUENAME.STYLETYPE);
        if (StringUtils.isNotBlank(styleType)) {
            map.put(Constants.VALUENAME.STYLETYPE, styleType);
        }
    }

    /**
     * 记录插件工具dcm ,dpm
     *
     * @param request the request
     * @param map the map
     */
    public static void getDcmAndDpmMap(HttpServletRequest request, Map<String, String> map, String id) {
        DmCookieHolder dmCookie = CookieUtil.getDmCookie(Constants.COOKIEKEY.PLUGIN, id);
        if (dmCookie != null) {
            if (StringUtils.isNotEmpty(dmCookie.getDcm())) {
                map.put(Constants.KEY.DCM, dmCookie.getDcm());
            }
            if (StringUtils.isNotEmpty(dmCookie.getDpm())) {
                map.put(Constants.KEY.DPM, dmCookie.getDpm());
            }
            if (StringUtils.isNotBlank(dmCookie.getDsm())) {
                map.put(Constants.KEY.DSM, dmCookie.getDsm());
            }
        }
    }

    public static void getGameDcmAndDpmMap(HttpServletRequest request, Map<String, String> map, String id) {
        DmCookieHolder dmCookie = CookieUtil.getDmCookie(Constants.COOKIEKEY.GAME, id);
        if (dmCookie != null) {
            if (StringUtils.isNotBlank(dmCookie.getDsm())) {
                map.put(Constants.KEY.DSM, dmCookie.getDsm());
            }
            if (StringUtils.isNotEmpty(dmCookie.getDcm())) {
                map.put(Constants.KEY.DCM, dmCookie.getDcm());
            }
            if (StringUtils.isNotEmpty(dmCookie.getDpm())) {
                map.put(Constants.KEY.DPM, dmCookie.getDpm());
            }
        }
    }

    /**
     * 记录活动新旧弹层. 1:新弹层2：旧弹层
     *
     * @param isNewLayer the is new layer
     * @param map the map
     */
    public static void getLayerMap(String isNewLayer, Map<String, String> map) {
        if (StringUtils.isNotEmpty(isNewLayer)) {
            map.put("isNewLayer", isNewLayer);
        }
    }

    /**
     * 从请求参数中获取dcm，dpm，dsm
     *
     * @param request
     * @param map
     */
    public static void setDcmAndDpmAndDsmFromParam(HttpServletRequest request, Map<String, String> map) {
        String dcm = request.getParameter(Constants.KEY.DCM);
        String dpm = request.getParameter(Constants.KEY.DPM);
        String dsm = request.getParameter(Constants.KEY.DSM);
        if (StringUtils.isNotBlank(dcm)) {
            map.put(Constants.KEY.DCM, dcm);
        }
        if (StringUtils.isNotBlank(dpm)) {
            map.put(Constants.KEY.DPM, dpm);
        }
        if (StringUtils.isNotBlank(dsm)) {
            map.put(Constants.KEY.DSM, dsm);
        }

    }

}
