package com.yeejoin.amos.boot.module.jyjc.biz.event.listener;

import com.yeejoin.amos.boot.module.jyjc.biz.event.TouchRuleEvent;
import com.yeejoin.amos.boot.module.jyjc.biz.rule.InspectionEquipInfo;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.rule.Rule;
import com.yeejoin.amos.feign.rule.model.FactBaseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @author Administrator
 */
@Component
@Slf4j
public class TouchRuleEventListener implements ApplicationListener<TouchRuleEvent> {

    private AmosRequestContext amosRequestContext;

    @Value("${inspection.rule.project-name:报检规则}")
    private String ruleName;


    public TouchRuleEventListener(AmosRequestContext amosRequestContext) {
        this.amosRequestContext = amosRequestContext;
    }

    @Override
    public void onApplicationEvent(TouchRuleEvent event) {
        this.touchRuleWithApi(event.getInspectionEquipInfo());
    }

    private void touchRuleWithApi(InspectionEquipInfo inspectionEquipInfo) {
        try {
            RequestContext.setAppKey(amosRequestContext.getAppKey());
            RequestContext.setProduct(amosRequestContext.getProduct());
            RequestContext.setToken(amosRequestContext.getToken());
            HashMap<String, byte[]> factMap = new HashMap<>();
            List<Object> factList = new ArrayList<>();
            factList.add(inspectionEquipInfo);
            for (Object fact : factList) {
                factMap.put(fact.getClass().getName(), toJSONString(fact).getBytes());
            }
            FactBaseModel factBaseModel = new FactBaseModel();
            factBaseModel.setFactMap(factMap);
            factBaseModel.setPackageId(ruleName + "/" + inspectionEquipInfo.getBizType());
            factBaseModel.setProcessIds(null);
            if (log.isInfoEnabled()) {
                log.info("发送规则的消息对象:{},\n变量对象：{}", toJSONString(factBaseModel), toJSONString(factBaseModel));
            }
            Rule.ruleClient.fireRule(factBaseModel);
        } catch (Exception e) {
            log.error("调用规则触发获取报检规则失败", e);
        }
    }
}
