package me.zhengjie.modules.thirdparty.v1;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.base.BaseResponse;
import me.zhengjie.base.QueryPageParams;
import me.zhengjie.modules.dm.messageSendLog.domain.DmMessageSendLog;
import me.zhengjie.modules.dm.messageSendLog.service.DmMessageSendLogService;
import me.zhengjie.modules.system.service.dto.DeptQueryNoAuthCriteria;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "消息接口")
@RequestMapping("/api/thirdparty/v1/message")
public class MessageSendLogApiController {

    private final DmMessageSendLogService dmMessageSendLogService;

    private final String erpapiUrl = "http://222.84.157.37:25894";

    @Log("发送IM消息")
    @ApiOperation("发送IM消息")
    @AnonymousPostMapping(value = "/sendChatMessage")
    public BaseResponse<Object> sendChatMessage(@RequestBody QueryPageParams<DmMessageSendLog> params) {
        SecurityUtils.CheckApiAuth(params);
        String url = "/api-im-logic/busi/im/logic/c2c/sendChatMessage";
        //组装erp发送信息接口请求参数
        JSONObject bodyJSON = new JSONObject();
        bodyJSON.put("clientId","yw");
        bodyJSON.put("token","9cc3dbc9-415a-479f-a03a-cbe15412875b");
        bodyJSON.put("payload",params.getQuery().getSendContent());
        bodyJSON.put("payloadType","text");
        bodyJSON.put("messageFrom","usky");
        bodyJSON.put("messageTo",params.getQuery().getUsernames());
        log.info("bodyJSON:"+bodyJSON.toJSONString());
        String res = HttpRequest.get(erpapiUrl+url)
                .header("serviceId", "USky")
                .header("serviceUserId",params.getQuery().getSendUserId())
                .body(bodyJSON.toJSONString()).execute().body();
        JSONObject json = JSONObject.parseObject(res);
        log.info("json:"+json);
        String code = json.getString("code");
        if(StringUtils.equals("0000",code)){
            dmMessageSendLogService.create(params.getQuery());
        } else {
            return new BaseResponse<>("发送失败",-1,"fail");
        }
        return new BaseResponse<>("发送成功");
    }

}
