package com.kmall.manager.manager.websocket;

import com.kmall.common.manager.websocket.Callback;
import com.kmall.common.manager.websocket.WsInvoker;
import com.kmall.common.manager.websocket.entity.WsData;
import com.kmall.common.manager.websocket.entity.WsInfo;
import com.kmall.common.utils.JacksonUtils;
import com.kmall.manager.manager.pay.data.open.websocket.WebsocketPropertiesBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * @author Scott Chen
 * @since 1.0
 * 2018-12-24
 */
@Component
public class WsClient {
    private static final Logger logger = LoggerFactory.getLogger(WsClient.class);

    public static void sign(String bizStr, String url, Callback onSuccess, Callback onError) {
        if (StringUtils.isBlank(bizStr)) {
            logger.error("加签数据串为空");
            return;
        }

        url = StringUtils.isBlank(url) ? WebsocketPropertiesBuilder.instance().getWsUrl() : url;

        String contents = getContentsStr(bizStr);

        WsInvoker.invoke(contents, url, onSuccess, onError);
    }

    public static String getContentsStr(String bizStr) {
        return JacksonUtils.toJson(getContents(bizStr));
    }

    public static WsInfo getContents(String bizStr) {
        WsInfo info = new WsInfo();

        WsData data = new WsData();
        data.setInData(bizStr);
        data.setPasswd(WebsocketPropertiesBuilder.instance().getOpCardPwd());

        info.set_id(Integer.valueOf(WebsocketPropertiesBuilder.instance().getId()));
        info.set_method(WebsocketPropertiesBuilder.instance().getCusSignMethod());

        info.setArgs(data);

        return info;
    }

}
