package com.storlead.message.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.storlead.framework.common.aviator.MapKeyExistsFunction;
import com.storlead.message.pojo.entity.MessageTemplateEventGroupEntity;
import com.storlead.message.service.InsideMessageRecordService;
import com.storlead.message.service.MessageTemplateEventDetailService;
import com.storlead.message.service.MessageTemplateEventGroupService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.*;
/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-23 11:34
 */

@Log4j2
@Service
public class MessageService {

    @Resource
    private InsideMessageRecordService messageRecordService;

    @Resource
    private MessageTemplateEventGroupService eventGroupService;

    @Resource
    private MessageTemplateEventDetailService eventDetailService;


    // 客户
    // 商机
//    public void autoMatchEventSendMessage(Map beforeMap,Map afterMap,String templateService,String... sendType) {
//
//    }



    public Map getOldMapData(Map sqlmap,String fieldColumn,String table){
        try {
            Map<String,Object> var1 = messageRecordService.getOldMapDataById(table,fieldColumn,sqlmap.get("id").toString());
            Map<String,Object> vargs = new HashMap<>();
            if (!CollectionUtils.isEmpty(var1)) {
                for (Map.Entry<String, Object> entry : var1.entrySet()) {
                    String camelCaseKey= StrUtil.toCamelCase("before"+entry.getKey());
                    vargs.put(camelCaseKey,entry.getValue());
                }
            }
            return vargs;
        } catch (Exception e) {
            return null;
        }
    }

//    public void autoMatchEventSendMessage(Map beforeMap,Map afterMap,String templateService) {
//        autoMatchEventSendMessage(beforeMap,afterMap,templateService,"site","wecom","sms","mail");
//    }
    public void autoMatchEventSendMessage(Map beforeMap,Map afterMap,String templateService) {

        autoMatchEventSendMessage(beforeMap ,afterMap,templateService,"site","wecom","sms","mail");
    }

    public void autoMatchEventSendMessage(Map<String,Object> messageMap, String templateServiceType, String eventCode, Set<Long> toUserIds, String... args) {
        try {
            LambdaQueryWrapper<MessageTemplateEventGroupEntity> templateEventWrapper = new LambdaQueryWrapper<>();
            templateEventWrapper.eq(MessageTemplateEventGroupEntity::getTemplateServiceType,templateServiceType);
            templateEventWrapper.eq(MessageTemplateEventGroupEntity::getEventCode,eventCode);
            templateEventWrapper.last(" limit 1");
            MessageTemplateEventGroupEntity  eventGroup = eventGroupService.getOne(templateEventWrapper);
            if (Objects.isNull(eventGroup)) {
                return;
            }
            asynSendMessage(eventGroup,messageMap,toUserIds,args);
        }catch (Exception e) {
            log.error("autoMatchEventSendMessage --- error",e);
        }
    }

    /**
     * 自动匹配消息事件规则
     * @param updateDataMap
     * @param oldDataMap
     * @param templateService
     */
    public void autoMatchEventSendMessage(Map beforeMap,Map afterMap,String templateService,String... args) {
        HashMap<String,Object> vargs = new HashMap();
        if (!CollectionUtils.isEmpty(beforeMap)) {
            vargs.putAll(beforeMap);
        }
        vargs.put("beforeMap",beforeMap);
        if (!CollectionUtils.isEmpty(afterMap)) {
            vargs.putAll(afterMap);
        }
        vargs.put("afterMap",afterMap);
        Map<String, Object> env = new HashMap<>();
        env.put("map", vargs);
        LambdaQueryWrapper<MessageTemplateEventGroupEntity> templateEventWrapper = new LambdaQueryWrapper<>();
        templateEventWrapper.eq(MessageTemplateEventGroupEntity::getTemplateServiceCode,templateService);
        List<MessageTemplateEventGroupEntity>  eventGroups = eventGroupService.list(templateEventWrapper);
        if (CollectionUtils.isEmpty(eventGroups)) {
            return;
        }
        for(MessageTemplateEventGroupEntity eventGroup : eventGroups) {
            if (StrUtil.isNotBlank(eventGroup.getEventRuleScript())) {
                AviatorEvaluator.addFunction(new MapKeyExistsFunction());
                String expression = eventGroup.getEventRuleScript();
                Expression exp = AviatorEvaluator.compile(expression);
                Boolean rst = (Boolean)exp.execute(env);
                if (rst) {
                    log.info("-------------匹配到消息事件规则："+eventGroup.getEventRuleScript());
                    asynSendMessage(eventGroup,vargs,null,args);
                }
            }
        }
    }

    public void sendMessage(MessageTemplateEventGroupEntity eventGroup, Map messageMap){
        eventDetailService.asynSendMessage(eventGroup,messageMap);
    }

    public void asynSendMessage(MessageTemplateEventGroupEntity eventGroup, Map messageMap, Set<Long> toUserIds,String... args){
        eventDetailService.asynSendMessage(eventGroup,messageMap,toUserIds,args);
    }



    public static void main(String[] args) {
        // 注册自定义函数
        AviatorEvaluator.addFunction(new MapKeyExistsFunction());
        // 创建一个Map对象并添加一些键值对
        Map<String, Object> map = new HashMap<>();
        map.put("age", 25);
        map.put("city", "New York");

        // 编写表达式判断Map中是否不包含"userName"键
        String expression = "!containsKey(map,'id')";

        // 编译表达式
        Expression compiledExp = AviatorEvaluator.compile(expression);

        // 创建环境变量，将map传入
        Map<String, Object> env = new HashMap<>();
        env.put("map", map);

        // 计算表达式
        Boolean result = (Boolean) compiledExp.execute(env);

        // 输出结果
        System.out.println("Map中是否不包含'userName'键: " + result);
    }
}
