package com.wecloud.im.controller.serverapi;

import com.wecloud.im.entity.ImApplication;
import com.wecloud.im.param.add.ImMsgSendToOnlineClient;
import com.wecloud.im.service.ImApplicationService;
import com.wecloud.im.service.ImMessageService;
import com.wecloud.im.core.common.api.ApiCode;
import com.wecloud.im.core.common.api.ApiResult;
import com.wecloud.im.core.common.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 消息存储表 控制器
 *
 * @author wei
 * @since 2021-04-29
 */
@Slf4j
@RestController
@RequestMapping("/server/imMessage")
@Api(value = "服务端rest-API-消息", tags = {"服务端rest-API-消息"})
public class ApiImMessageController extends BaseController {

    @Autowired
    private ImApplicationService imApplicationService;
    @Autowired
    private ImMessageService imMessageService;

    /**
     * 向会话中在线client,下发透传消息
     */
    @PostMapping("/sendToOnlineClient")
    @ApiOperation(value = "向会话中在线client,下发透传消息", notes = "应用服务端向某会话中所有client下发透传消息, 不会保存进离线消息, 仅在线client能收到")
    public ApiResult<Boolean> restApiImMessageSend(@RequestBody ImMsgSendToOnlineClient imMsgSendToOnlineClient, @RequestHeader String appkey, @RequestHeader String appSecret) throws Exception {
//        return imMessageService.updateMsgWithdrawById(imMsgRecall);


        //  根据appKey从数据库查询密钥
        ImApplication imApplication = imApplicationService.getCacheAppByAppKey(appkey);

        if (imApplication == null) {
            return ApiResult.result(ApiCode.FAIL, null);
        }

        // 校验appkey 和appSecret
        if (!imApplication.getAppSecret().equals(appSecret)) {
            return ApiResult.result(ApiCode.FAIL, null);
        }

        return imMessageService.restApiImMessageSend(imMsgSendToOnlineClient, imApplication);

    }

}

