package com.ym.controller;

import com.ym.mec.common.entity.ImSystemMessage;
import com.ym.mec.common.entity.ImTxtMessage;
import com.ym.service.MessageService;
import io.rong.messages.TxtMessage;
import io.rong.models.message.BroadcastMessage;
import io.rong.models.message.GroupMessage;
import io.rong.models.message.SystemMessage;
import io.rong.models.message.TemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
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 java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system")
public class SystemController {

    @Autowired
    MessageService messageService;

    @RequestMapping(value = "/send", method = RequestMethod.POST)
    public Object send(@RequestBody ImSystemMessage imSystemMessage) throws Exception {
        SystemMessage systemMessage = new SystemMessage();
        ImTxtMessage content = (ImTxtMessage)imSystemMessage.getContent();
        TxtMessage txtMessage = new TxtMessage(content.getContent(),content.getExtra());
        systemMessage.setContent(txtMessage);
        systemMessage.setSenderId(imSystemMessage.getSenderId());
        systemMessage.setObjectName(imSystemMessage.getObjectName());
        String[] targetId = imSystemMessage.getTargetId();
        long i = Math.round(targetId.length / 100d);
        for (int j = 0; j < i; j++) {
            List<String> collect = Arrays.stream(targetId).skip(j * 100).limit(100).collect(Collectors.toList());
            String[] objects = collect.toArray(new String[100]);
            systemMessage.setTargetId(objects);
            messageService.systemSend(systemMessage);
        }
        return null;
    }

    @RequestMapping(value = "/broadcast", method = RequestMethod.POST)
    public Object broadcast(@RequestBody BroadcastMessage broadcastMessage) throws Exception {
        return messageService.systemBroadcast(broadcastMessage);
    }

    @RequestMapping(value = "/sendTemplate", method = RequestMethod.POST)
    public Object sendTemplate(@RequestBody TemplateMessage templateMessage) throws Exception {
        return messageService.systemSendTemplate(templateMessage);
    }
}
