/**
 *
 */
package com.pcloud.common.utils.cookie;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.string.StringUtil;

/**
 * @描述：cooike内容解析工具类
 * @作者：songx
 * @创建时间：2016年9月6日,下午3:08:41
 * @版本：1.0
 */
public class Cookie {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(Cookie.class);

    /**
     * 渠道标识
     */
    public static final String _CHANNEL_ID = "channelId";

    /**
     * 公众号标识
     */
    public static final String _OFFICIAL_ACCOUNTS_ID = "officialAccountsId";

    /**
     * 微信用户标识
     */
    public static final String _WECHAT_USER_ID = "wechatUserId";

    /**
     * 当事人标识
     */
    public static final String _PARTY_ID = "partyId";

    /**
     * 编辑标识
     */
    public static final String _ADVISER_ID = "adviserId";

    /**
     * systemCode
     */
    public static final String _SYSTEM_CODE = "systemCode";

    /**
     * isSystem
     */
    public static final String _IS_SYSTEM = "isSystem";

    /**
     * 二维码标识
     */
    public static final String _SCENE_ID = "sceneId";

    /**
     * 用户标识
     */
    public static final String _USER_ID = "userId";

    /**
     * 商户成员账号标识
     */
    public static final String _MERCHANT_MEMBER_ID = "merchantMemberId";
    public static final String _AGENT_MEMBER_ID = "agentMemberId";

    /**
     * 预览类型
     */
    public static final String PREVIEW_TYPE = "previewType";

    /**
     * 二维码ID来源
     */
    public static final String SOURCE_TYPE = "sourceType";

    /**
     * 一级分享ID
     */
    public static final String FIRST_TD = "firstTd";
    /**
     * 二级分享ID
     */
    public static final String SECOND_TD = "secondTd";

    /**
     * cookie 信息處理
     * @param userInfo
     * @return
     * @throws BizException
     */
    public static Map<String, Object> getUserInfo(String userInfo) throws BizException {
        if (StringUtil.isEmpty(userInfo)) {
            LOGGER.warn("Cookie解析失败：userInfo==NULL");
            throw BizException.COOKIE_IS_ILLICIT;
        }
        try {
            userInfo = URLDecoder.decode(userInfo, "UTF-8");
            LOGGER.info("Cookie的内容如下：" + String.valueOf(userInfo));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Cookie解析失败：" + e.getMessage(), e);
            throw BizException.COOKIE_IS_ILLICIT;
        } catch (Exception e) {
            LOGGER.error("Cookie解析失败：" + e.getMessage(), e);
            throw BizException.COOKIE_IS_ILLICIT;
        }
        Map<String, Object> userInfos = new HashMap<>();
        String[] userInfoArry = userInfo.split("&");
        for (int i = 0; i < userInfoArry.length; i++) {
            if (userInfoArry[i].contains("channelId")) {
                String[] channel = userInfoArry[i].split("=");
                String channelId = channel[channel.length - 1];
                userInfos.put("channelId", StringUtil.isEmpty(channelId) || "undefined".equalsIgnoreCase(channelId)
                        || "null".equalsIgnoreCase(channelId) ? null : Long.valueOf(channelId));
            }
            if (userInfoArry[i].contains("officialAccountsId")) {
                String[] wechat = userInfoArry[i].split("=");
                String officialAccountsId = wechat[wechat.length - 1];
                userInfos.put("officialAccountsId", StringUtil.isEmpty(officialAccountsId) || "undefined".equalsIgnoreCase(officialAccountsId)
                        || "null".equalsIgnoreCase(officialAccountsId) ? null : Long.valueOf(officialAccountsId));
            }
            if (userInfoArry[i].contains("wechatUserId")) {
                String[] user = userInfoArry[i].split("=");
                String wechatUserId = user[user.length - 1];
                userInfos.put("wechatUserId", StringUtil.isEmpty(wechatUserId) || "undefined".equalsIgnoreCase(wechatUserId)
                        || "null".equalsIgnoreCase(wechatUserId) ? null : Long.valueOf(wechatUserId));
            }
            if (userInfoArry[i].contains("partyId")) {
                String[] party = userInfoArry[i].split("=");
                String partyId = party[party.length - 1];
                userInfos.put("partyId", StringUtil.isEmpty(partyId) || "undefined".equalsIgnoreCase(partyId) || "null".equalsIgnoreCase(partyId)
                        ? null : Long.valueOf(partyId));
            }
            // editBy TC cookie里面需要带上顾问,systemCode,是否系统,场景值
            // modify by songx at 2017-05-17 如果值为undefined或者null直接跳过
            if (userInfoArry[i].contains("adviserId")) {
                String[] adviser = userInfoArry[i].split("=");
                String adviserId = adviser[adviser.length - 1];
                userInfos.put("adviserId", StringUtil.isEmpty(adviserId) || "undefined".equalsIgnoreCase(adviserId) || "null".equalsIgnoreCase(adviserId)
                        ? null : Long.valueOf(adviserId));
            }
            if (userInfoArry[i].contains("systemCode")) {
                String[] systemCode = userInfoArry[i].split("=");
                String code = systemCode[systemCode.length - 1];
                userInfos.put("systemCode", code);
            }
            if (userInfoArry[i].contains("isSystem")) {
                String[] system = userInfoArry[i].split("=");
                String isSystem = system[system.length - 1];
                userInfos.put("isSystem", isSystem);
            }
            // modify by songx at 2017-05-17 如果值为undefined或者null直接跳过
            if (userInfoArry[i].contains("sceneId")) {
                String[] scene = userInfoArry[i].split("=");
                String sceneId = scene[scene.length - 1];
                userInfos.put("sceneId", StringUtil.isEmpty(sceneId) || "undefined".equalsIgnoreCase(sceneId) || "null".equalsIgnoreCase(sceneId) ? null
                        : Long.valueOf(sceneId));
            }
            if (userInfoArry[i].contains("userId")) {
                String[] userLogin = userInfoArry[i].split("=");
                String userId = userLogin[userLogin.length - 1];
                userInfos.put("userId", StringUtil.isEmpty(userId) || "undefined".equalsIgnoreCase(userId) || "null".equalsIgnoreCase(userId) ? null
                        : Long.valueOf(userId));
            }
            if (userInfoArry[i].contains("merchantMemberId")) {
                String[] merchant = userInfoArry[i].split("=");
                String merchantMemberId = merchant[merchant.length - 1];
                userInfos.put("merchantMemberId", StringUtil.isEmpty(merchantMemberId) || "undefined".equalsIgnoreCase(merchantMemberId)
                        || "null".equalsIgnoreCase(merchantMemberId) ? null : Long.valueOf(merchantMemberId));
            }
            if (userInfoArry[i].contains("agentMemberId")) {
                String[] merchant = userInfoArry[i].split("=");
                String agentMemberId = merchant[merchant.length - 1];
                userInfos.put("agentMemberId", StringUtil.isEmpty(agentMemberId) || "undefined".equalsIgnoreCase(agentMemberId)
                        || "null".equalsIgnoreCase(agentMemberId) ? null : Long.valueOf(agentMemberId));
            }
            // add by gaop
            if (userInfoArry[i].contains(PREVIEW_TYPE)) {
                String[] previewType = userInfoArry[i].split("=");
                String code = previewType[previewType.length - 1];
                userInfos.put(PREVIEW_TYPE, code);
            }
            if (userInfoArry[i].contains(SOURCE_TYPE)) {
                String[] sourceType = userInfoArry[i].split("=");
                String code = sourceType[sourceType.length - 1];
                userInfos.put(SOURCE_TYPE, code);
            }

            //add by tc
            if (userInfoArry[i].contains(FIRST_TD)) {
                String[] firstTD = userInfoArry[i].split("=");
                String code = firstTD[firstTD.length - 1];
                userInfos.put(FIRST_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null
                        : Long.valueOf(code));
            }
            if (userInfoArry[i].contains(SECOND_TD)) {
                String[] secondTD = userInfoArry[i].split("=");
                String code = secondTD[secondTD.length - 1];
                userInfos.put(SECOND_TD, StringUtil.isEmpty(code) || "undefined".equalsIgnoreCase(code) || "null".equalsIgnoreCase(code) ? null
                        : Long.valueOf(code));
            }
        }
        return userInfos;
    }

    /**
     * 获取对应的ID值
     * @param userInfo
     * @param type
     * @return
     * @throws BizException
     */
    public static Long getId(String userInfo, String type) throws BizException {
        String value = getString(userInfo, type);
        return StringUtil.isEmpty(value) || "undefined".equalsIgnoreCase(value) || "null".equalsIgnoreCase(value) ? null : Long.valueOf(value);
    }

    /**
     * 获取对应的值
     * @param userInfo
     * @param type
     * @return
     * @throws BizException
     */
    public static String getString(String userInfo, String type) throws BizException {
        if (StringUtil.isEmpty(userInfo)) {
            LOGGER.error("Cookie解析失败：userInfo==NULL");
            throw BizException.COOKIE_IS_ILLICIT;
        }
        try {
            userInfo = URLDecoder.decode(userInfo, "UTF-8");
            LOGGER.info("Cookie的内容如下：" + String.valueOf(userInfo));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Cookie解析失败：" + e.getMessage(), e);
            throw new BizException(BizException.COOKIE_IS_ILLICIT);
        } catch (Exception e) {
            LOGGER.error("Cookie解析失败：" + e.getMessage(), e);
            throw new BizException(BizException.COOKIE_IS_ILLICIT);
        }
        String[] userInfoArry = userInfo.split("&");
        for (int i = 0; i < userInfoArry.length; i++) {
            if (userInfoArry[i].contains(type)) {
                String[] ids = userInfoArry[i].split("=");
                String id = ids[ids.length - 1];
                return StringUtil.isEmpty(id) || "undefined".equalsIgnoreCase(id) || "null".equalsIgnoreCase(id) ? null : id;
            }
        }
        return null;
    }

}
