package com.fs.app.controller;

import cn.hutool.json.JSONUtil;
import com.fs.app.params.SendAIParam;
import com.fs.app.websocket.bean.RestBean;
import com.fs.app.websocket.service.WebSocketServer;
import com.fs.common.core.domain.R;
import com.fs.qw.domain.QwSession;
import com.fs.qw.param.QwMsgSendParam;
import com.fs.qw.service.IQwMsgService;
import com.fs.qw.service.IQwSessionService;
import com.fs.qwHookApi.param.QwHookSendMsgParam;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Api("企微消息")
@RestController
@RequestMapping(value="/app/qwmsg")
@Slf4j
public class QwMsgController {

    @Autowired
    WebSocketServer webSocketServer;

    @Autowired
    private IQwMsgService qwMsgService;

    @Autowired
    private IQwSessionService qwSessionService;


    @PostMapping("/sendMsg")
    public R sendQwMsg(@RequestBody QwMsgSendParam param) {
        //文本消息
        QwSession qwSession = qwSessionService.selectQwSessionBySessionId(param.getSessionId());
        if (qwSession==null){
            return R.error("会话不存在！");
        }
        QwHookSendMsgParam sendMsgParam=new QwHookSendMsgParam();
        QwHookSendMsgParam.QwHookSendMsgData sendMsgData=new QwHookSendMsgParam.QwHookSendMsgData();
        sendMsgParam.setType(101003);
        sendMsgData.setMsg(param.getContent());
        sendMsgData.setSendId(qwSession.getQwExtWxId());
        sendMsgData.setSyncKey("1");
        sendMsgParam.setData(sendMsgData);
        SendAIParam sendAIParam = new SendAIParam();
        sendAIParam.setCmd("aiReplyMsg");
        sendAIParam.setData(JSONUtil.toJsonStr(sendMsgParam));
        sendAIParam.setKey(param.getAppKey());
        webSocketServer.sendBaseSleepInfo(param.getAppKey(), JSONUtil.toJsonStr(sendAIParam));
        qwMsgService.addAiMsg(qwSession, param.getContent(), 1,null);
        return R.ok();
    }

    @PostMapping("/receiveMsg")
    public void receiveMsg(@RequestBody RestBean param) {
        try {
            log.info("发送接收消息socket:{}",param);
            webSocketServer.sendBaseSleepInfo(param.getId(), JSONUtil.toJsonStr(param.getMessage()));
        } catch (Exception e) {
            log.error("receiveMsg error", e);
        }
    }

    @PostMapping("/sendFinishCourseMsg")
    public void sendFinishCourseMsg(@RequestBody RestBean param) {
        try {
            webSocketServer.sendBaseSleepInfo(param.getId(), JSONUtil.toJsonStr(param.getMessage()));
        } catch (Exception e) {
            log.error("sendFinishCourseMsg error", e);
        }
    }


}
