/**
 * Project Name:tuia-youtui-web<br>
 * File Name:PathUtil.java<br>
 * Package Name:com.duiba.tuia.youtui.web.tool<br>
 * Date:2017年2月20日下午7:17:47<br>
 * Copyright (c) 2017, duiba.com.cn All Rights Reserved.<br>
 */

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

import cn.com.duiba.credits.sdk.CreditTool;
import cn.com.duiba.tuia.activity.center.api.constant.LoginType;
import cn.com.duiba.tuia.activity.center.api.constant.PageType;
import cn.com.duiba.tuia.activity.center.api.dto.consumer.ConsumerCache;
import cn.com.duiba.wolf.utils.UrlUtils;
import com.duiba.tuia.youtui.web.constant.Constants;
import com.duiba.tuia.youtui.web.constant.Tenter;
import com.duiba.tuia.youtui.web.model.req.IndexReq;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * ClassName: PathUtil <br/>
 * date: 2017年2月20日 下午7:17:47 <br/>
 *
 * @author youhaijun
 * @since JDK 1.6
 */
public class PathUtil {

    private static final Logger logger = LoggerFactory.getLogger(PathUtil.class);

    private PathUtil() {
    }

    /**
     * 获取跳转中间页的重定向链接.
     *
     * @param promoteUrl the promote URL
     * @param orderId    the order id
     * @param dcm        the dcm
     * @param dpm        the dpm
     * @param activityId the activity id
     * @return the button URL
     */
    public static String getButtonUrl(String host, String promoteUrl, String orderId, String dcm, String dpm,
                                      Long activityId, String couponSource,String styleType) {
        StringBuilder builder = new StringBuilder();
        builder.append(host).append(Constants.PATH.ACTIVITY).append(Constants.PATH.REDIRECT).append("?url=").append(promoteUrl).append("&orderId=").append(Constants.THE_PREFIX_ORDERID).append(orderId).append("&dcm=").append(dcm).append("&dpm=").append(dpm).append("&activityId=").append(activityId).append("&device_type=tuia");
        if (StringUtils.isNotBlank(couponSource)) {
            builder.append("&couponSource=").append(couponSource);
        }
        if (StringUtils.isNotBlank(styleType)) {
            builder.append("&styleType=").append(styleType);
        }
        return builder.toString();
    }


    public static String getActivityUrl(Long id, IndexReq req, Long sourceId, Integer sourceType) {
        if (null == id || id == 0L) {
            return null;
        }
        StringBuilder url = new StringBuilder();
        url.append("//" + req.getHost());
        url.append(Constants.PATH.ACTIVITY);

        url.append(Constants.PATH.INDEX);
        url.append(Constants.PARAM.ID).append(id);
        if (LoginType.NORMAL.equalsCode(req.getLogin())) {
            url.append(Constants.PARAM.SLOTID).append(req.getSlotId());
            url.append(Constants.PARAM.DEVICEID).append(req.getDeviceId());
        }
        url.append(Constants.PARAM.LOGIN).append(req.getLogin());
        url.append(Constants.PARAM.APPKEY).append(req.getAppKey());
        if (null != sourceId && 0 != sourceId) {
            url.append(Constants.PARAM.SOURCEID).append(sourceId);
        }
        if (null != sourceType && 0 != sourceType) {
            url.append(Constants.PARAM.SOURCETYPE).append(sourceType);
        }
        if (!StringUtils.isEmpty(req.getDpm())) {
            url.append(Constants.PARAM.DPM).append(req.getDpm());
        }
        if (!StringUtils.isEmpty(req.getDcm())) {
            url.append(Constants.PARAM.DCM).append(req.getDcm());
        }
        if (!StringUtils.isEmpty(req.getDsm())) {
            url.append(Constants.PARAM.DSM).append(req.getDsm());
        }
        return url.toString();
    }

    public static String getGameUrl(IndexReq req) {
        Long id = req.getId();
        if (null == id || id == 0L) {
            return null;
        }
        StringBuilder url = new StringBuilder();
        url.append("//" + req.getHost());
        url.append(Constants.PATH.GAME);

        url.append(Constants.PATH.INDEX);
        url.append(Constants.PARAM.ID).append(id);
        if (LoginType.NORMAL.equalsCode(req.getLogin())) {
            url.append(Constants.PARAM.SLOTID).append(req.getSlotId());
            url.append(Constants.PARAM.DEVICEID).append(req.getDeviceId());
        }
        url.append(Constants.PARAM.LOGIN).append(req.getLogin());
        url.append(Constants.PARAM.PAGEID).append(req.getPageId());
        url.append(Constants.PARAM.APPKEY).append(req.getAppKey());
        if (!StringUtils.isEmpty(req.getDpm())) {
            url.append(Constants.PARAM.DPM).append(req.getDpm());
        }
        if (!StringUtils.isEmpty(req.getDcm())) {
            url.append(Constants.PARAM.DCM).append(req.getDcm());
        }
        if (!StringUtils.isEmpty(req.getDsm())) {
            url.append(Constants.PARAM.DSM).append(req.getDsm());
        }
        return url.toString();
    }


    public static String getActivityUrlFroDestPage(Long id, IndexReq req, Long sourceId, Integer sourceType) {
        StringBuilder url = new StringBuilder();
        url.append("//" + req.getHost());
        url.append(Constants.PATH.ACTIVITY);

        url.append(Constants.PATH.INDEX);
        url.append(Constants.PARAM.ID).append(id);
        if (LoginType.NORMAL.equalsCode(req.getLogin())) {
            url.append(Constants.PARAM.SLOTID).append(req.getSlotId());
            url.append(Constants.PARAM.DEVICEID).append(req.getDeviceId());
        }
        url.append(Constants.PARAM.LOGIN).append(req.getLogin());
        url.append(Constants.PARAM.APPKEY).append(req.getAppKey());
        if (null != sourceId && 0 != sourceId) {
            url.append(Constants.PARAM.SOURCEID).append(sourceId);
        }
        if (null != sourceType && 0 != sourceType) {
            url.append(Constants.PARAM.SOURCETYPE).append(sourceType);
        }
        if (!StringUtils.isEmpty(req.getDpm())) {
            url.append(Constants.PARAM.DPM).append(req.getDpm());
        }
        if (!StringUtils.isEmpty(req.getDcm())) {
            url.append(Constants.PARAM.DCM).append(req.getDcm());
        }
        if (!StringUtils.isEmpty(req.getDsm())) {
            url.append(Constants.PARAM.DSM).append(req.getDsm());
        }
        return url.toString();
    }

    public static String getGuidePageUrl(Long id, IndexReq req, Integer pageType) {
        StringBuilder url = new StringBuilder();
        url.append("//" + req.getHost());
        if (PageType.MAINMEET.equalsCode(pageType)) {
            url.append(Constants.PATH.MAINMEET);
        } else if (PageType.ACTCENTER.equalsCode(pageType)) {
            url.append(Constants.PATH.ACTCENTER);
        } else if (PageType.DIRECT.equalsCode(pageType)) {
            url.append(Constants.PATH.DIRECTPAGE);
        }
        url.append(Constants.PATH.INDEX);
        url.append(Constants.PARAM.ID).append(id);
        String login = req.getLogin();
        if (LoginType.NORMAL.equalsCode(login)) {
            url.append(Constants.PARAM.SLOTID).append(req.getSlotId());
            url.append(Constants.PARAM.DEVICEID).append(req.getDeviceId());
        }
        url.append(Constants.PARAM.LOGIN).append(login);
        url.append(Constants.PARAM.APPKEY).append(req.getAppKey());
        if (!StringUtils.isEmpty(req.getDpm())) {
            url.append(Constants.PARAM.DPM).append(req.getDpm());
        }
        if (!StringUtils.isEmpty(req.getDcm())) {
            req.setDcm(StringUtils.replace(req.getDcm(), String.valueOf(Constants.DCM.DCM_DEFAULT), id.toString()));
            url.append(Constants.PARAM.DCM).append(req.getDcm());
        }
        if (!StringUtils.isEmpty(req.getDsm())) {
            url.append(Constants.PARAM.DSM).append(req.getDsm());
        }
        if (req.getActivityId() != null) {
            url.append(Constants.PARAM.ACTIVITY_ID).append(req.getActivityId());
        }
        if (PageType.DIRECT.equalsCode(pageType)) {
            url.append("&").append(Constants.TOW_ID).append("=").append(UUID.randomUUID().toString());
        }

        url.append("&wu=bo");//该参数用于防止 url被拼接的乱码影响dsm
        return url.toString();
    }

    public static String getRedirctUrl(String host, String destUrl, String dsm) throws UnsupportedEncodingException {
        StringBuilder url = new StringBuilder();
        url.append("//" + host);
        url.append("/log" + "/redirect?");
        url.append("url=").append(URLEncoder.encode(destUrl, "UTF-8"));
        url.append("&dsm=").append(dsm);
        return url.toString();
    }

    /**
     * 为推荐列表拼接通往活动中心的url
     *
     * @param id
     * @param req
     * @param pageType
     * @param dpm
     * @return
     * @author zhouwb
     * @date 20170730
     * version 1.0
     */

    public static String getGuidePageUrlforRecommendPage(Long id, IndexReq req, int pageType, String dpm) {
        StringBuilder url = new StringBuilder();
        url.append("//" + req.getHost());
        if (PageType.MAINMEET.equalsCode(pageType)) {
            url.append(Constants.PATH.MAINMEET);
        } else if (PageType.ACTCENTER.equalsCode(pageType)) {
            url.append(Constants.PATH.ACTCENTER);
        }
        url.append(Constants.PATH.INDEX);
        url.append(Constants.PARAM.ID).append(id);
        String login = req.getLogin();
        if (LoginType.NORMAL.equalsCode(login)) {
            url.append(Constants.PARAM.SLOTID).append(req.getSlotId());
            url.append(Constants.PARAM.DEVICEID).append(req.getDeviceId());
        }
        url.append(Constants.PARAM.LOGIN).append(login);
        url.append(Constants.PARAM.APPKEY).append(req.getAppKey());
        url.append(Constants.PARAM.DPM).append(dpm);
        if (StringUtils.isNotBlank(req.getDsm())) {
            url.append(Constants.PARAM.DSM).append(req.getDsm());
        }
        //设置tenter
        url.append("&").append(Constants.TENTER).append(Tenter.SNR.getCode());
        return url.toString();
    }

    public static String getDirectAdvert(String host, String promoteUrl, Map<String, String> params) {
        String rs = null;
        StringBuilder url = new StringBuilder();
        try {
            url.append("//").append(host).append(Constants.PATH.DIRECTPAGE).append(Constants.PATH.REDIRECT);
            params.put("url", URLEncoder.encode(promoteUrl, "UTF-8"));
            rs = UrlUtils.appendParams(url.toString(), params);
        } catch (UnsupportedEncodingException e) {
            logger.error("getDirectAdvert Exception:", e);
        }
        return rs;
    }


    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String strURL) {
        String strAllParam = null;
        String[] arrSplit = null;

        strURL = strURL.trim().toLowerCase();

        arrSplit = strURL.split("[?]");
        if (strURL.length() > 1 && arrSplit.length > 1 && arrSplit[1] != null) {
            strAllParam = arrSplit[1];
        }

        return strAllParam;
    }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     *
     * @param url url地址
     * @return url请求参数部分
     */
    public static Map<String, String> analysisURLRequest(String url) {
        Map<String, String> mapRequest = new HashMap<>();

        String[] arrSplit = null;

        String strUrlParam = truncateUrlPage(url);
        if (strUrlParam == null) {
            return mapRequest;
        }
        //每个键值为一组 www.2cto.com
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");

            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    public static Integer pageTypeToDSMc(Integer pageType) {
        if (PageType.ACTIVITY.getCode().equals(pageType)) {
            return Constants.DSM.DSM_C_1;
        }
        if (PageType.DIRECT.getCode().equals(pageType)) {
            return Constants.DSM.DSM_C_3;
        }
        if (PageType.ACTCENTER.getCode().equals(pageType)) {
            return Constants.DSM.DSM_C_4;
        }
        if (PageType.MAINMEET.getCode().equals(pageType)) {
            return Constants.DSM.DSM_C_5;
        }
        return Constants.DSM.DSM_DEFAULT1;
    }

    /***
     * @Description: processUrl 处理url，拼接http头和//
     *
     * @Return: java.lang.String
     * @throws:
     * @author: youhaijun
     * @Date: 2017/9/5
     */
    public static String processUrl(String url, HttpServletRequest request) {
        String urlNew = url;
        if (url.contains(DomainConstantUtil.getYoutuiDomain())) {
            urlNew = urlNew.replaceFirst(DomainConstantUtil.getYoutuiDomain(), request.getHeader("host"));
        }

        urlNew = removeProtocolUrl(urlNew);
        urlNew = appendProtocalUrl(urlNew, request);

        return urlNew;
    }

    public static String processActivityUrl(String url, HttpServletRequest request) {
        if (url.contains(DomainConstantUtil.getYoutuiDomain())) {
            url = url.replaceFirst(DomainConstantUtil.getYoutuiDomain(), request.getHeader("host"));
            url = removeProtocolUrl(url);
            url = appendProtocalUrl(url, request);
        }
        return url;
    }

    private static String removeProtocolUrl(String url) {

        if (url.startsWith("https://")) {
            url = url.replaceFirst("https://", "//");
        } else if (url.startsWith("http://")) {
            url = url.replaceFirst("http://", "//");
        } else if (!url.startsWith("//")) {
            url = "//" + url;
        }
        return url;
    }

    private static String appendProtocalUrl(String url, HttpServletRequest request) {
        String referer = request.getHeader("Referer");
        if (StringUtils.isNotEmpty(referer)) {
            if (referer.startsWith("https")) {
                url = "https:" + url;
            } else if (referer.startsWith("http")) {
                url = "http:" + url;
            }
        }
        return url;
    }

    public static PageType getPageType(String path) {
        switch (path) {
            case "/activity/index": {
                return PageType.ACTIVITY;
            }
            case "/direct/index": {
                return PageType.DIRECT;
            }
            case "/actCenter/index": {
                return PageType.ACTCENTER;
            }
            case "/mainmeet/index": {
                return PageType.MAINMEET;
            }
            case "/game/index": {
                return PageType.GAME;
            }
            default: {
                return PageType.DIRECT;
            }
        }
    }

    /**
     * 为url增加参数
     * @param url url
     * @param key 参数名
     * @param value 参数值
     * @return url
     */
    public static String addParam(String url,String key,String value){
        if(StringUtils.isBlank(url)){
            return url;
        }
        return UrlUtils.appendParams(url, ImmutableMap.of(key,value));
    }

    /**
     * 为url增加参数
     * @param url url
     * @param params 参数
     * @return url
     */
    public static String addParam(String url,Map<String,String> params) {
        if (StringUtils.isBlank(url)) {
            return url;
        }
        return UrlUtils.appendParams(url, params);
    }

    /**
     *  构建在兑吧商城自动登录的url地址
     * @param uid 用户id
     * @param transfer 免登陆接口扩展参数，在扣积分核通知时候回传
     * @param credits 用户积分余额
     * @return 自动登录的url地址
     */
    public static String buildAutoLoginRequest(String uid, Long credits, String transfer, String redirect, ConsumerCache consumerCache) throws UnsupportedEncodingException {
        CreditTool tool = new CreditTool(Constants.TUIA_IN_DUIBA_APP_KEY, Constants.TUIA_IN_DUIBA_APP_SECRET);
        String url="https://www.duiba.com.cn/autoLogin/autologin?";
        Map<String, String> params=new HashMap<>();
        params.put("uid", uid);
        params.put("credits", credits+"");
        if(transfer!=null){
            params.put("transfer", transfer);
        }
        if(redirect!=null){
            params.put("redirect", redirect);
        }
        if (StringUtils.isNotBlank(consumerCache.getNickName())) {
            StringBuilder dcustom = new StringBuilder("avatar=");
            dcustom.append(consumerCache.getImg()).append("&nickname=").append(consumerCache.getNickName()).append("&sex=").append(consumerCache.getSex());
            params.put("dcustom", URLEncoder.encode(dcustom.toString(), "utf-8"));
        }
        String autologinUrl= tool.buildUrlWithSign(url,params);
        return autologinUrl;
    }
}
