package com.ruoyi.xq.controller.app;

import cn.dev33.satoken.annotation.SaIgnore;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.xq.domain.UserChatRecord;
import com.ruoyi.xq.executor.ExecutorConstant;
import com.ruoyi.xq.service.UserChatRecordService;
import com.ruoyi.yunxin.manager.YunxinManager;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/api/yx/im")
@Tag(name = "Yunxin相关的接口")
@Slf4j
public class YxNotifyController {

    @Autowired
    private YunxinManager yunxinManager;
    @Autowired
    private UserChatRecordService userChatRecordService;

    @PostMapping("/notify")
    @Operation(hidden = true)
    @SaIgnore
    public R<Void> notifyYx(HttpServletRequest request) throws IOException {
        String appKey = request.getHeader("AppKey");
        String curTime = request.getHeader("CurTime");
        String md5 = request.getHeader("MD5");
        String checkSum = request.getHeader("CheckSum");
        String requestBody = readBody(request);
        boolean check = yunxinManager.checkNotify(requestBody, curTime, checkSum,md5);
        if(!check){
            log.info("检验失败！");
            return R.fail("401",null);
        }
        JSONObject body = JSON.parseObject(requestBody);
        if(body == null){
            return R.fail("401",null);
        }
        String eventType = body.getString("eventType");
        if("2".equals(eventType) || "3".equals(eventType)){ // 登陆登出事件
            log.info("request yx notify login body = {}", requestBody);
            String accid = body.getString("accid");
            String timestamp = body.getString("timestamp");
//            onlineService.updateOnlineByYunxin(eventType,Long.valueOf(accid),Long.valueOf(timestamp));
        }else if("1".equals(eventType)){ // 会话记录
            String convType = body.getString("convType");
            String msgType = body.getString("msgType");
            if("PICTURE".equals(msgType) && "PERSON".equals(convType)){
                String ext = body.getString("ext");
                ExecutorConstant.SYNC_EXECUTOR.execute(() -> {
                    try {
                        log.info("request yx notify chat body = {}", requestBody);
                        JSONObject extJson = JSON.parseObject(ext);
                        String recordId = extJson.getString("recordId");
                        if(StringUtils.isEmpty(recordId)){
                            log.warn("同步图片忽略，recordId为空");
                            return;
                        }
                        UserChatRecord userChatRecord = userChatRecordService.getById(recordId);
                        if(userChatRecord == null){
                            log.warn("同步图片忽略，recordId未找到记录");
                            return;
                        }
                        String attach = body.getString("attach");
                        JSONObject attachJson = JSON.parseObject(attach);
                        String url = attachJson.getString("url");
                        userChatRecordService.update(Wrappers.lambdaUpdate(UserChatRecord.class)
                                .eq(UserChatRecord::getId, userChatRecord.getId())
                                .set(UserChatRecord::getContent, url));
                    }catch (Exception e){
                        log.warn("同步图片失败!",e);
                    }
                });
            }
        }
        return R.ok();
    }

    private String readBody(HttpServletRequest request) throws IOException {
        if (request.getContentLength() > 0) {
            byte[] bytes = StreamUtils.copyToByteArray(request.getInputStream());
            return new String(bytes, StandardCharsets.UTF_8);
        } else
            return null;

    }
}
