package cn.quantgroup.xyqb.event;

import cn.quantgroup.xyqb.entity.User;
import cn.quantgroup.xyqb.model.UserRegisterParam;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Slf4j
@Component
public class BlackHoleRegisteredEventListener implements ApplicationListener<RegisterEvent> {

    @Value("${registered.notify.black.hole.rabbitmq.connection.exchange}")
    private String exchange;
    @Value("${registered.notify.black.hole.rabbitmq.connection.routingKey}")
    private String routingKey;
    @Resource
    private RabbitTemplate registeredNotifyBlackHoleRabbitTemplate;
    private long [] templateIds = {8L,280L};
    private long [] templateIds_159913 = {433L,434L}; // 羊小咩小程序的渠道，合同内容不包含现金分期业务，如果这种情况较多可以考虑配置化
    private static final Long YXM_CHANNEL = 159913L; // 羊小咩小程序的渠道(小程序_电商，小程序_VCC)

    @Override
    public void onApplicationEvent(RegisterEvent event) {
        UserRegisterParam userRegisterParam = event.getUserRegisterParam();
        User user = userRegisterParam.getUser();
        log.info("onApplicationEvent cn.quantgroup.xyqb.event.BlackHoleRegisteredEventListener start userId = 【{}】， registerFrom = 【{}】", user.getId(), userRegisterParam.getRegisterFrom());
        LocalDate signDate = LocalDate.now();
        String dateStr = signDate.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
        int day = signDate.getDayOfMonth();
        // 信用钱包服务与隐私协议
        long[] regTempIds = YXM_CHANNEL.equals(userRegisterParam.getRegisterFrom()) ? templateIds_159913 : templateIds;
        for (long id : regTempIds) {
            JSONObject fields = new JSONObject();
            fields.put("phoneNo", user.getPhoneNo());
            fields.put("genarateDateStr", dateStr);
            fields.put("day", day);
            JSONObject json = new JSONObject();
            json.put("userId", user.getId());
            json.put("mustReal", false);
            json.put("templateId", id);
            json.put("fields", fields);
            JSONArray array = new JSONArray();
            array.add(json);
            registeredNotifyBlackHoleRabbitTemplate.convertAndSend(exchange, routingKey, array.toString());
        }


    }
}
