package com.xueyi.nlt.nlt.controller;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchAllQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xueyi.common.cache.utils.SourceUtil;
import com.xueyi.common.core.constant.basic.SecurityConstants;
import com.xueyi.common.core.constant.digitalman.MessageConstants;
import com.xueyi.common.core.context.SecurityContextHolder;
import com.xueyi.common.core.utils.core.ListUtil;
import com.xueyi.common.core.web.result.AjaxResult;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.core.web.validate.V_A;
import com.xueyi.common.core.web.validate.V_E;
import com.xueyi.common.log.annotation.Log;
import com.xueyi.common.log.enums.BusinessType;
import com.xueyi.common.security.annotation.Logical;
import com.xueyi.common.security.annotation.RequiresPermissions;
import com.xueyi.common.security.utils.SecurityUtils;
import com.xueyi.common.web.entity.controller.BaseController;
import com.xueyi.nlt.api.netty.domain.vo.DmWebSocketMessageVo;
import com.xueyi.nlt.api.nlt.domain.vo.*;
import com.xueyi.nlt.api.nlt.feign.RemoteIntentService;
import com.xueyi.nlt.api.nlt.feign.RemoteLandingLlmService;
import com.xueyi.nlt.api.nlt.feign.RemoteQAService;
import com.xueyi.nlt.netty.client.WebSocketClient;
import com.xueyi.nlt.nlt.context.TerminalSecurityContextHolder;
import com.xueyi.nlt.nlt.domain.dto.DmIntentDto;
import com.xueyi.nlt.nlt.domain.query.DmIntentQuery;
import com.xueyi.nlt.nlt.domain.vo.IntentTemplateVo;
import com.xueyi.nlt.nlt.service.IDmIntentService;
import com.xueyi.nlt.nlt.template.FreeChatTemplate;
import com.xueyi.nlt.nlt.template.GenerativeKnowledgeTemplate;
import com.xueyi.nlt.nlt.template.MeetingOrderTemplate;
import com.xueyi.system.api.digitalmans.domain.dto.DmManDeviceDto;
import com.xueyi.system.api.digitalmans.domain.dto.DmSkillDto;
import com.xueyi.system.api.digitalmans.domain.vo.DmBatchQuestionsVo;
import com.xueyi.system.api.digitalmans.feign.RemoteDigitalmanService;
import com.xueyi.system.api.digitalmans.feign.RemoteManDeviceService;
import com.xueyi.system.api.digitalmans.feign.RemoteQuestionanswersService;
import com.xueyi.system.api.digitalmans.feign.RemoteSkillService;
import com.xueyi.system.api.model.Source;
import com.xueyi.system.api.organize.domain.dto.SysEnterpriseDto;
import com.xueyi.system.api.organize.feign.RemoteEnterpriseService;
import com.xueyi.tenant.api.tenant.domain.dto.TeTenantDto;
import com.xueyi.tenant.api.tenant.feign.RemoteTenantService;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.xueyi.common.core.constant.digitalman.SkillConstants.SkillType;

import java.io.IOException;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.xueyi.common.core.constant.digitalman.MessageConstants.SYS_DICT_DATA_SPLITED;

@RestController
@RequestMapping("/intent")
public class DmIntentController extends BaseController<DmIntentQuery, DmIntentDto, IDmIntentService> {

    private static final Logger log = LoggerFactory.getLogger(DmIntentController.class);
    @Autowired
    IDmIntentService dmIntentService;

    @Autowired
    WebSocketClient webSocketClient;

    /** 定义节点名称 */
    @Override
    protected String getNodeName() {
        return "意图管理 ";
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate2;



    @Autowired
    private RemoteManDeviceService manDeviceService;

    @Autowired
    private RemoteIntentService remoteIntentService;
    
    @Autowired
    private MeetingOrderTemplate meetingOrderTemplate;

    @Autowired
    private GenerativeKnowledgeTemplate generativeKnowledgeTemplate;

    @Autowired
    private FreeChatTemplate freeChatTemplate;

    @Autowired
    private RemoteQuestionanswersService questionanswersService;

    @Autowired
    private RemoteSkillService remoteskillService;

    @Autowired
    RemoteEnterpriseService enterpriseService;

    @Autowired
    RemoteLandingLlmService remoteLandingLlmService;

    @Autowired
    RemoteQAService remoteQAService;

    @Autowired
    RemoteDigitalmanService remoteDigitalmanService;

    @Autowired
    RemoteEnterpriseService remoteEnterpriseService;
    @Autowired
    private ElasticsearchClient esClient;
    /**
     * 意图请求
     列表
     */
    @PostMapping("/api/conversation")
    @ResponseBody
    public AjaxResult conversationApi(@RequestBody DmIntentVo intent) {
        TerminalSecurityContextHolder.setOperatorId(String.valueOf(intent.getOperator()));
        log.info("交互对象：{}", intent.toString());
        redisTemplate.opsForValue().increment("dashboard:server", 1);
        // 获取今天日期，并格式化成yyyy-MM-dd
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(new Date());
        redisTemplate.opsForValue().increment(("dashboard:server-chart:" + today), 1);
        R<DmManDeviceDto> manDeviceDtoR = manDeviceService.manDeviceInfoInner(intent.getDevId());
        Source source = SourceUtil.getSourceCache(manDeviceDtoR.getData().getStrategyId());
        R<JSONObject> jsonObjectR = remoteIntentService.conversationInner(intent,  manDeviceDtoR.getData().getTId(), source.getMaster(), SecurityConstants.INNER);
        IntentTemplateVo voResult = new IntentTemplateVo();
        voResult.setMsg("");
        if (jsonObjectR.getData() != null) {
            if (jsonObjectR.getData().containsKey("result") && StringUtils.isEmpty(jsonObjectR.getData().getString("result")) ) {
                voResult.setTarget(0);
            } else {
                voResult.setTarget(1);
            }
        } else {
            voResult.setTarget(0);
        }
        if (intent.getMode() != null && intent.getMode().equals(MessageConstants.MODE_FREE_CHAT)) {
           voResult.setMsg(jsonObjectR.getData().get("msg").toString());
        }
        else {
            voResult.setFormat(jsonObjectR.getData());
        }
        return AjaxResult.success(voResult);
    }

    @PostMapping("/api/skill-intent")
    @ResponseBody
    public AjaxResult skillIntentApi(@RequestBody DmIntentVo intent) {
        log.info("交互对象：{}", intent.toString());
        redisTemplate.opsForValue().increment("dashboard:server", 1);
        R<DmManDeviceDto> manDeviceDtoR = manDeviceService.manDeviceInfoInner(intent.getDevId());
        Source source = SourceUtil.getSourceCache(manDeviceDtoR.getData().getStrategyId());
        IntentTemplateVo voResult = new IntentTemplateVo();
        //查询es，将满足条件的数据调用后续处理，不满足条件的返回原始数据
        SearchResponse<JSONObject> dateResponse = null;
        List<Hit<JSONObject>> question_list = null;
        try {
            MatchQuery byName = MatchQuery.of(m->m.field("name").query(intent.getContent()));
            dateResponse = esClient.search(builder -> builder
                            .index("regular_expression").query(q->q.match(byName)),
                    JSONObject.class);
            question_list = dateResponse.hits().hits();
            log.info("esClient search result: {}", dateResponse);
        }catch (IOException ie) {
            log.error("esClient search error", ie);
            return null;
        }
        for (Hit<JSONObject> jsonObjectHit : question_list) {
            JSONObject jo = jsonObjectHit.source();
            Pattern pat = Pattern.compile(jo.get("name").toString());
            Matcher m = pat.matcher(intent.getContent());
            if (m.find()) {
//            R<JSONObject> jsonObjectR = remoteIntentService.conversationInner(intent,  manDeviceDtoR.getData().getTId(), source.getMaster(), SecurityConstants.INNER);

                voResult.setMsg(jo.get("answer").toString());
                // 如果包含Json数据并且json的skillCode字段不等于空
                if (jo.containsKey("json") && StringUtils.isNotEmpty(jo.getString("json"))) {
                    String skillCode = jo.getJSONObject("json").getString("skillCode");
                    intent.setSkillCode(skillCode);
                    R<List<DmSkillDto>> skilllistInner = remoteskillService.skilllistInner(intent.getDevId(),"1",manDeviceDtoR.getData().getTId(), source.getMaster(), SecurityConstants.INNER);
                    if(skilllistInner.isOk()){
                        List<DmSkillDto> skilllist=skilllistInner.getData();
                        for (DmSkillDto dmSkillDto : skilllist) {
                            if (dmSkillDto.getSkillCode().equals(skillCode)) {
                                if(dmSkillDto.getStatus().equals("0")){
                                    return AjaxResult.error(10001,"操作无权限");
                                }
                                voResult.setMotion(dmSkillDto.getMotionName());
                            }
                        }
                    }
                    voResult.setJsonFormat(jo.getJSONObject("json"));
                    voResult.setType("1");
                }

//            return AjaxResult.success(voResult);
            }
        }

        //走知识库
        R<JSONObject> jsonObjectR = remoteIntentService.conversationInner(intent,  manDeviceDtoR.getData().getTId(), source.getMaster(), SecurityConstants.INNER);
        if (jsonObjectR.getData() != null) {
            if (jsonObjectR.getData().containsKey("result") && StringUtils.isEmpty(jsonObjectR.getData().getString("result")) ) {
                voResult.setTarget(0);
            } else {
                voResult.setTarget(1);
            }
        } else {
            voResult.setTarget(0);
        }
        if (intent.getMode() != null && intent.getMode().equals(MessageConstants.MODE_FREE_CHAT)) {
            voResult.setMsg(jsonObjectR.getData().get("msg").toString());
        }
        else {
            voResult.setFormat(jsonObjectR.getData());
        }
        return AjaxResult.success(voResult);
    }

    /**
     * 意图请求
     列表
     */
    @PostMapping("/api/say_hello")
    @ResponseBody
    public AjaxResult sayHelloApi(@RequestBody DmRecognitionVo recognition) {
        log.info(recognition.toString());
        redisTemplate.opsForValue().increment("dashboard:recognition", 1);

        redisTemplate.opsForValue().increment("dashboard:conversation-times", 1);
        JSONObject joResult = new JSONObject();
        joResult.put("msg","");
        joResult.put("target",0);
        if (StringUtils.isNotEmpty(recognition.getRegistered()) && recognition.getRegistered().equals("1")) {

            Map cntMap = redisTemplate.opsForHash().entries("group:nlp" + ":" + recognition.getPersonId());
            //遍历key和value
            for (Object key : cntMap.keySet()) {
                String value = (String) cntMap.get(key);
                if (String.valueOf(key).equals("meeting")) {
                    JSONObject jo = JSONObject.parseObject(value);
                    // 判断是否在30分钟内
                    System.out.println("timestamp:" + jo.get("timestamp"));
                    System.out.println("currenttime:" + System.currentTimeMillis());
                    if(jo.containsKey("timestamp") &&
                            Double.valueOf(String.valueOf(jo.get("timestamp"))) - System.currentTimeMillis() < 1800000) {
                        joResult.put("msg",jo.get("content"));
                        joResult.put("target",1);
                        redisTemplate.opsForHash().delete("group:nlp" + ":" + recognition.getPersonId(), "meeting");
                        redisTemplate.opsForValue().increment("dashboard:conversation-duration", jo.get("content").toString().length() / 4);
                        return AjaxResult.success(joResult);
                    } else if (Double.valueOf(String.valueOf(jo.get("timestamp"))) - System.currentTimeMillis() < 0) {
                        redisTemplate.opsForHash().delete("group:nlp" + ":" + recognition.getPersonId(), "meeting");
                    }
                } else {
                    JSONObject jo = JSONObject.parseObject(value);
                    JSONObject joresult = addNotificaion(String.valueOf(key),recognition.getPersonId(),jo);
                    if (joresult!= null) {
                        return AjaxResult.success(joresult);
                    }
                    joResult.put("msg",value);
                    redisTemplate.opsForValue().increment("dashboard:conversation-duration", value.toString().length() / 4);
                    joResult.put("target",1);
                    redisTemplate.opsForHash().delete("group:nlp" + ":" + recognition.getPersonId(),key);
                    return AjaxResult.success(joResult);
                }
            }
        }
        redisTemplate.opsForValue().increment("dashboard:conversation-duration", 3);
        return AjaxResult.success(joResult);
    }

    /**
     * 知识库问答请求
     */
    @PostMapping("/api/searchQA")
    @ResponseBody
    public AjaxResult searchQA(@RequestBody DmIntentVo intent) {
        log.info("交互对象：{}",intent.toString());

        R<DmManDeviceDto> manDeviceDtoR = manDeviceService.manDeviceInfoInner(intent.getDevId());
        Source source = SourceUtil.getSourceCache(manDeviceDtoR.getData().getStrategyId());
        KnowledgeVo knowledgeVo = new KnowledgeVo();
        knowledgeVo.setMan_code(manDeviceDtoR.getData().getManCode());
        knowledgeVo.setTenant_id(manDeviceDtoR.getData().getTId());
        knowledgeVo.setQuestion(intent.getContent());
//        return remoteQAService.query(manDeviceDtoR.getData().getManCode(),intent.getContent(),manDeviceDtoR.getData().getTId());
        return remoteQAService.query(knowledgeVo);

    }

    /**
     * 联动北方大模型请求
     */
    @PostMapping("/api/searchQuestionAnswer")
    @ResponseBody
    public AjaxResult searchQuestionAnswer(@RequestBody DmIntentVo intent) {
        log.info("交互对象：{}",intent.toString());
        redisTemplate.opsForValue().increment("dashboard:recognition", 1);
        JSONObject joResult = new JSONObject();
        joResult.put("msg","");
        joResult.put("target",0);
        DmLandingLlmVo vo = new DmLandingLlmVo();
        vo.setCategory("bj_unicom");
        vo.addDmLlm("user", intent.getContent());
        JSONObject testJ = new JSONObject();
        testJ.put("category","bj_unicom");
        JSONArray ja1 = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("role","user");
        jo.put("content",intent.getContent());
        ja1.add(jo);
        testJ.put("messages",ja1);
        JSONObject resultJson = remoteLandingLlmService.query(testJ);
        JSONArray ja = resultJson.getJSONArray("data");

        if (ja.size() > 0) {
            joResult.put("msg",ja.getJSONObject(0).get("text"));
            joResult.put("target",1);
        }
        return AjaxResult.success(joResult);
    }


    /**
     * 意图请求列表
     */
    @PostMapping("/inner/conversation")
    @ResponseBody
    public R<JSONObject> conversationInner(@RequestBody DmIntentVo intent) {
        JSONObject joResult = null;
        if (intent.getMode() !=null && intent.getMode().equals(MessageConstants.MODE_FREE_CHAT)) {
            // 闲聊
            joResult = freeChatTemplate.handle(intent.getDevId(),intent.getContent());
            return R.ok(joResult);
        }

        String enterpriseId = (String)SecurityContextHolder.getLocalMap().get("enterprise_id");
        String enterpriseName = "";
        R<SysEnterpriseDto> enterpriseDtoR = remoteEnterpriseService.getInfo(Long.valueOf(enterpriseId));
        if (enterpriseDtoR.isOk()) {
            enterpriseName = enterpriseDtoR.getData().getName();
        }
        // 获取设备号对应缓存
        CoversationSessionVo sessionObject = (CoversationSessionVo) redisTemplate2.opsForValue().get("group:device" + ":" + intent.getDevId() + ":" +"session"); //category
        if (sessionObject != null) {
            switch (sessionObject.getCategory()) {
                case "meeting":
                    joResult = meetingOrderTemplate.handle(intent.getDevId(),intent.getContent(), Long.parseLong(SecurityContextHolder.getLocalMap().get("enterprise_id").toString()));
                    return R.ok(joResult);
            }
        }
        if (StringUtils.isEmpty(intent.getSkillCode())) {
            // 调用知识库问答
            AjaxResult qaAjax = searchQA(intent);
            String content = "";
            if (qaAjax.toJson().containsKey("data") && StringUtils.isNotEmpty(qaAjax.toJson().getJSONObject("data").getJSONObject("format").getString("result"))) {

                content = qaAjax.toJson().getJSONObject("data").getJSONObject("format").getJSONArray("result").getJSONObject(0).getJSONObject("knowledge_lib").toString();
            }
            pushIntoDashboardRedis(enterpriseName,content,"knowledge");
            return R.ok(JSONObject.from(qaAjax.get("data")));
        }
        SkillType.BOOK_MEETING_ROOM.getCode();
        // 判断skill code的值
        if (SkillType.BOOK_MEETING_ROOM.getCode().equals(intent.getSkillCode()) ) {
            if (!redisTemplate2.hasKey("group:device" + ":" + intent.getDevId() + ":" +"session")) {
                // 获取名称为"meeting-order"的BaseTemplate的实例
                redisTemplate.opsForValue().increment("dashboard:meeting", 1);
                pushIntoDashboardRedis(enterpriseName, "会议室预定", "skill");
            }
            joResult = meetingOrderTemplate.handle(intent.getDevId(), intent.getContent(), Long.parseLong(SecurityContextHolder.getLocalMap().get("enterprise_id").toString()));
        } else if (SkillType.CREATE_VISITOR_INFO.getCode().equals(intent.getSkillCode())) {
            // 访客预定
            redisTemplate.opsForValue().increment("dashboard:create_visitor_info", 1);
            pushIntoDashboardRedis(enterpriseName,"访客邀约","skill");
        } else if (SkillType.REGISTER_VISITOR.getCode().equals(intent.getSkillCode())) {
            // 访客登记
            redisTemplate.opsForValue().increment("dashboard:register_visitor", 1);
            pushIntoDashboardRedis(enterpriseName,"陌生人登记","skill");
        } else if (SkillType.BROADCAST_DISPLAY.getCode().equals(intent.getSkillCode())) {
            // 播报展示
            redisTemplate.opsForValue().increment("dashboard:broadcast_display", 1);
            pushIntoDashboardRedis(enterpriseName,"播报展示","skill");
        } else if (SkillType.OPEN_DOOR.getCode().equals(intent.getSkillCode())) {
            // 开门记录
            redisTemplate.opsForValue().increment("dashboard:open_door", 1);
            pushIntoDashboardRedis(enterpriseName,"开门","skill");
        }
        return R.ok(joResult);
    }

    /**
     * 意图请求
     列表
     */
    @PostMapping("/inner/sendMessage")
    @ResponseBody
    public R<Object> sendMessage(@RequestBody DmWebSocketMessageVo message) {

        log.info("websocket sendMessage:{}", message);
        if (message == null || message.getFormat() == null) {
            return R.fail("参数为空");
        }
        JSONObject jo = message.getFormat();
        //SimpleDateFormat dateFormat3 = new SimpleDateFormat("MM-dd");
        SimpleDateFormat dateFormat4 = new SimpleDateFormat("M月d日");
        Double timestamp = Double.valueOf((String)jo.get("timestamp"));
        String meetingRoom = jo.getString("meetingRoom");
        if (StringUtils.isNotEmpty(message.getTemplate()) && message.getTemplate().equals("birthday")) {
            String prefix = "假设你是一名公司前台，你看到" + message.getFormat().get("name")+ "已知今天是他的生日。请你从个人角度输出给他的生日贺词。要求待人平和，具有人情味，用词正式，内容与工作无关。输出只包含你要对他说的话，在20字以内。";
            webSocketClient.sendMsg(prefix);
            redisTemplate2.opsForValue().set("gpt:websocket" + ":" + "1", message);
            return R.ok();
        }
        if (StringUtils.isNotEmpty(message.getTemplate()) && message.getTemplate().equals("hireDate")) {
            String prefix = "假设你是一名公司前台，你看到"+ message.getFormat().get("name")+ "，已知今天是他入职" + message.getFormat().get("years")+"周年，请你从个人角度说出对他入职周年的祝贺。要求具有人情味，有特色，字数在25字左右，不要提到生日，要带人名。输出只包含你要对他说的话。";
            webSocketClient.sendMsg(prefix);
            redisTemplate2.opsForValue().set("gpt:websocket" + ":" + "1", message);
            return R.ok();
        }
        Date date = new Date(timestamp.longValue());
        if (message.getSkillCode().equals("1")) {
            String prefix = "假设你是一名公司前台，你看到在你们公司工作的\\"+ jo.getString("orderName")+ "\\，请你从个人角度提醒他参加\\" +
                    dateFormat4.format(timestamp) + "\\在\\" + meetingRoom + "\\的会，要求语气友好。输出只包含你要对他说的话，在20字左右。";
            webSocketClient.sendMsg(prefix);
            // 设置缓存
            redisTemplate2.opsForValue().set("gpt:websocket" + ":" + "1", message);
        }
        return R.ok();
    }

    /**
     * 意图请求
     列表
     */
    @PostMapping("/inner/taskGenerativeKnowledge")
    @ResponseBody
    public R<Object> taskGenerativeKnowledge() {

        // 从列表中获取知识库任务
        TaskKnowledgeVo vo = (TaskKnowledgeVo) redisTemplate2.opsForList().leftPop("group:task");

        if (vo == null) {
            return R.ok(null,"没有任务");
        }

        if (vo.getSplit() != SYS_DICT_DATA_SPLITED) {
            // 请开始你的表演
            String contents = vo.getContent();

            List<String> results = Arrays.stream(contents.split("\n")).filter(StringUtils::isNotBlank).collect(Collectors.toList());
            results.forEach(item->{
                TaskKnowledgeVo temp = new TaskKnowledgeVo();
                temp.setContent(item);
                temp.setCount(item.length());
                temp.setManId(vo.getManId());
                temp.setKnowledgeId(vo.getKnowledgeId());
                temp.setTenantId(vo.getTenantId());
                temp.setSplit(SYS_DICT_DATA_SPLITED);
                temp.setCreateBy(vo.getCreateBy());
                redisTemplate2.opsForList().rightPush("group:task", temp);
            });
            return R.ok(null,"处理成功");
        }
        log.info("交互对象：{}",vo.toString());
        JSONObject joResult = generativeKnowledgeTemplate.handle(null,vo.getContent());

        if (joResult == null) {
            redisTemplate2.opsForList().rightPush("group:task", vo);
            return R.ok(null,"任务处理失败，重新放入队列");
        }

        R<SysEnterpriseDto> enterpriseDtoR = enterpriseService.getInfo(vo.getTenantId());
        if (enterpriseDtoR.isFail()) {
            log.warn("任务执行失败：{}",vo);
        }
        Source source = SourceUtil.getSourceCache(enterpriseDtoR.getData().getStrategyId());
        DmBatchQuestionsVo batchQuestionsVo = new DmBatchQuestionsVo();
        batchQuestionsVo.setKnowledgeId(vo.getKnowledgeId());
        batchQuestionsVo.setQuestions(JSONArray.from(joResult.get("questions")));
        batchQuestionsVo.setCreateId(vo.getCreateBy());
        questionanswersService.batchInsertInner(batchQuestionsVo,vo.getTenantId(),source.getMaster(),SecurityConstants.INNER);

        return R.ok(null,"处理成功");
    }

    /**
     * 查询意图管理
     列表
     */
    @Override
    @GetMapping("/list")
    @RequiresPermissions(Auth.DM_INTENT_LIST)
    public AjaxResult list(DmIntentQuery intent) {
        return super.list(intent);
    }

    /**
     * 查询意图管理
     详细
     */
    @Override
    @GetMapping(value = "/{id}")
    @RequiresPermissions(Auth.DM_INTENT_SINGLE)
    public AjaxResult getInfo(@PathVariable Serializable id) {
        return super.getInfo(id);
    }

    /**
     * 意图管理
     新增
     */
    @Override
    @PostMapping
    @RequiresPermissions(Auth.DM_INTENT_ADD)
    @Log(title = "意图管理", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated({V_A.class}) @RequestBody DmIntentDto intent) {
        return super.add(intent);
    }

    /**
     * 意图管理
     修改
     */
    @Override
    @PutMapping
    @RequiresPermissions(Auth.DM_INTENT_EDIT)
    @Log(title = "意图管理", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated({V_E.class}) @RequestBody DmIntentDto intent) {
        return super.edit(intent);
    }

    /**
     * 意图管理
     修改状态
     */
    @Override
    @PutMapping("/status")
    @RequiresPermissions(value = {Auth.DM_INTENT_EDIT, Auth.DM_INTENT_ES}, logical = Logical.OR)
    @Log(title = "意图管理", businessType = BusinessType.UPDATE_STATUS)
    public AjaxResult editStatus(@RequestBody DmIntentDto intent) {
        return super.editStatus(intent);
    }

    /**
     * 意图管理
     批量删除
     */
    @Override
    @DeleteMapping("/batch/{idList}")
    @RequiresPermissions(Auth.DM_INTENT_DEL)
    @Log(title = "意图管理", businessType = BusinessType.DELETE)
    public AjaxResult batchRemove(@PathVariable List<Long> idList) {
        return super.batchRemove(idList);
    }

    /**
     * 获取意图管理
     选择框列表
     */
    @Override
    @GetMapping("/option")
    public AjaxResult option() {
        return super.option();
    }


    private JSONObject addNotificaion(String key,Long personId,JSONObject jo) {
        JSONObject joResult = new JSONObject();
        if (String.valueOf(key).equals("birthday") || String.valueOf(key).equals("hireDate")) {
            // 获取value中的timestamp,判断是否是当天
            if (jo.containsKey("timestamp")) {
                // 判断jo.get("timestamp")的月份是否与当天相同
                DateFormat dateFormat = new SimpleDateFormat("MM-dd");
                if (dateFormat.format(new Date(Long.valueOf(String.valueOf(jo.get("timestamp"))))).equals(dateFormat.format(new Date()))) {
                    joResult.put("msg", jo.get("content"));
                    joResult.put("target", 1);
                    redisTemplate.opsForHash().delete("group:nlp" + ":" + personId, key);
                    redisTemplate.opsForValue().increment("dashboard:conversation-duration", jo.get("content").toString().length() / 4);
                    return joResult;
                }
            }
        }
        return joResult;
    }

    private int pushIntoDashboardRedis(String name,String content,String type) {
        try {
            JSONObject object = new JSONObject();
            object.put("tenantName", name);
            object.put("content", content);
            if (type.equals("skill")) {
                redisTemplate2.opsForList().leftPush("dashboard:skill-consume", object.toJSONString());
            } else if (type.equals("knowledge")) {
                redisTemplate2.opsForList().leftPush("dashboard:knowledge-consume", object.toJSONString());
            }
            return 1;
        } catch (Exception e) {
            log.error("推送到仪表盘失败：{}",e.getMessage());
            return 0;
        }
    }
    interface Auth {
        /** 系统 - 意图管理
         管理 - 列表 */
        String DM_INTENT_LIST = "nlt:intent:list";
        /** 系统 - 意图管理
         管理 - 详情 */
        String DM_INTENT_SINGLE = "nlt:intent:single";
        /** 系统 - 意图管理
         管理 - 新增 */
        String DM_INTENT_ADD = "nlt:intent:add";
        /** 系统 - 意图管理
         管理 - 修改 */
        String DM_INTENT_EDIT = "nlt:intent:edit";
        /** 系统 - 意图管理
         管理 - 修改状态 */
        String DM_INTENT_ES = "nlt:intent:es";
        /** 系统 - 意图管理
         管理 - 删除 */
        String DM_INTENT_DEL = "nlt:intent:delete";
    }
}
