package com.sonic.pigeon.controller.openapi;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sonic.pigeon.domain.input.ReceiveImMsgInput;
import com.sonic.pigeon.service.CommonSendMqService;
import com.sonic.pigeon.service.ReceiveImMsgService;
import com.sonic.pigeon.utils.CheckSumBuilder;
import com.sonic.sdk.api.annotation.IgnoreAuth;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * OPEN_API-IM回调
 */
@Slf4j
@RestController
public class ReceiveImMsgController {

    @Value("${im.appKey}")
    private String defaultAppKey;
    @Autowired
    private ReceiveImMsgService receiveImMsgService;
    @Autowired
    private CommonSendMqService commonSendMqService;

    @IgnoreAuth
    @ApiOperation(value = "IM的点对点消息回调验证", tags = {"OPEN_API-IM回调"})
    @RequestMapping(value = "/open-api/webhook/receive-im-msg", produces = {"application/json"}, method = RequestMethod.POST)
    public Object receiveImMsg(@Validated @RequestBody ReceiveImMsgInput input, HttpServletRequest request) throws Exception {
        //参数签名验证是否通过，不通过则直接返回空
        if (!checkSignPass(input, request)) {
            return null;
        }
        //处理如果是首次检验时触发的回调，直接快速返回成功即可
        if(StringUtils.isEmpty(input.getFromAccount()) && StringUtils.isEmpty(input.getTo())) {
            return receiveImMsgService.buildSuccessResult();
        }

        log.info("===> receiveImMsg req : {}", input);
        Object result = receiveImMsgService.receiveImMsgCheck(input);
        log.info("===> receiveImMsg result : {}", result);

        //如果回调允许发送，则发送mq消息
        String errCode = JSONObject.parseObject(JSONObject.toJSONString(result)).getString("errCode");
        if (errCode.equals("0")) {
            //发送 AI 聊天消息
            commonSendMqService.sendAiChatMq(input);
            commonSendMqService.sendAiChatToFrogMq(input);
        }
        return result;
    }

    /**
     * 参数签名验证
     * @param input
     * @param request
     * @return
     */
    private boolean checkSignPass(ReceiveImMsgInput input, HttpServletRequest request) {
        String requestAppKey = request.getHeader("appkey");
        String requestMd5 = request.getHeader("MD5");
        String requestCurTime = request.getHeader("CurTime");
        String requestCheckSum = request.getHeader("CheckSum");
        log.info("===> receiveImMsg header : requestAppKey : {}, requestMd5 : {}, requestCurTime : {}, requestCheckSum : {}", requestAppKey, requestMd5, requestCurTime, requestCheckSum);
        //校验值是否正确
        if (!requestAppKey.equals(defaultAppKey)) {
            log.info("===> receiveImMsg check appKey error : {} , {}", requestAppKey, defaultAppKey);
            return false;
        }
        String checkMd5 = CheckSumBuilder.getMD5(JSONObject.toJSONString(input));
        if (!requestMd5.equals(checkMd5)) {
            log.info("===> receiveImMsg check md5 error : {} , {}", requestMd5, checkMd5);
            return false;
        }
        if (StringUtils.isNotEmpty(input.getFromAccount()) && (input.getFromAccount().endsWith("@d"))) {
            return false;
        }
        return true;
    }

}
