package cn.quantgroup.xyqb.util;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.UserRegisterMqMessage;
import cn.quantgroup.xyqb.model.UserRet;
import cn.quantgroup.xyqb.model.UserStatistics;
import cn.quantgroup.xyqb.service.mq.IRegisterMqService;
import cn.quantgroup.xyqb.service.mq.IVestService;

/**
 * Created by xuran on 2017/6/23.
 */
@Slf4j
public class MqUtils {
    /**
     * 发送用户统计信息
     *
     * @param vest
     */
    public static void sendLoanVest(UserStatistics vest) {
        try {
            IVestService mqService = ApplicationContextHolder.getBean("loanVestMqService");
            mqService.send(vest);
        } catch (Exception e) {
            log.error("[MQUtils][MQUtils_exception]发送用户统计信息，vest={},error={}",
                    vest, e);
        }
    }

    /**
     * 用户注册消息进行广播
     *
     * @param message
     */
    private static void sendRegisterMessage(UserRegisterMqMessage message) {
        try {
            IRegisterMqService rService = ApplicationContextHolder.getBean("registerMqService");
            rService.send(message);
        } catch (Exception e) {
            log.error("[MQUtils][MQUtils_exception]发送用户注册广播信息，message={},error={}",
                    message, e);
        }
    }

    public static UserRet sendRegisterMessage(Long registeredFrom, String demension, User user) {
        UserStatistics statistics = new UserStatistics(user, demension, 2, registeredFrom);
        MqUtils.sendLoanVest(statistics);
        //增加用户注册广播
        UserRegisterMqMessage registerMqMessage = new UserRegisterMqMessage(user);
        MqUtils.sendRegisterMessage(registerMqMessage);
        UserRet userRet = new UserRet(user);
        return userRet;
    }

    /**
     * 腾讯广点通转化的用户注册消息推送
     *
     * @param phoneNo - 转化成功的用户手机号
     * @param clickId - 转化成功的点击动作唯一标识
     */
    public static void sendRegisterMessageForGdt(String phoneNo, String clickId) {
        if (ValidationUtil.validatePhoneNo(phoneNo) && StringUtils.isNotBlank(clickId)) {
            //填充广点通消息
            JSONObject message = new JSONObject();
            message.put("phoneNo", phoneNo);
            message.put("clickId", clickId);
            try {
                IRegisterMqService rService = ApplicationContextHolder.getBean("registerMqService");
                rService.send4Gdt(message);
            } catch (Exception e) {
                log.error("[MQUtils][MQUtils_exception]发送广点通用户注册信息，message={},error={}",
                        message, e);
            }
        }
    }
}
