package com.mortals.xhx.common.utils;

import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.framework.util.HttpUtil;
import com.mortals.xhx.common.pdu.UploadDeviceReq;
import com.mortals.xhx.feign.device.IDeviceMessageFeign;
import com.mortals.xhx.module.metting.model.MettingRecordEntity;
import com.mortals.xhx.module.room.model.RoomDeviceQuery;
import com.mortals.xhx.module.room.model.RoomEntity;
import com.mortals.xhx.module.room.service.RoomDeviceService;
import com.mortals.xhx.module.room.service.RoomService;
import com.mortals.xhx.utils.SpringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.mortals.framework.util.HttpUtil.HEADER_CONTENT_TYPE;


@Slf4j
@AllArgsConstructor
public class SendNotifyTask implements Runnable {


    private IDeviceMessageFeign messageFeign;

    private RoomService roomService;

    private RoomDeviceService roomDeviceService;

    private MettingRecordEntity mettingRecordEntity;

    public SendNotifyTask(MettingRecordEntity mettingRecordEntity) {
        this.mettingRecordEntity = mettingRecordEntity;
        this.messageFeign= SpringUtils.getBean(IDeviceMessageFeign.class);
        this.roomService= SpringUtils.getBean(RoomService.class);
        this.roomDeviceService= SpringUtils.getBean(RoomDeviceService.class);
    }

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
            //手动结束会议 延迟发送刷新通知
            UploadDeviceReq uploadDeviceReq = new UploadDeviceReq();
            RoomEntity roomEntity = roomService.get(mettingRecordEntity.getRoomId());
            if (!ObjectUtils.isEmpty(roomEntity)) {
                List<String> deviceList = roomDeviceService.find(new RoomDeviceQuery().roomId(roomEntity.getId())).stream().map(i -> i.getDeviceCode()).collect(Collectors.toList());
                uploadDeviceReq.setDeviceCodeList(deviceList);
                uploadDeviceReq.setAction("postMeet");
                Rest<String> rest = messageFeign.downMsg(uploadDeviceReq);
                log.info("手动结束会议记录后发送消息：{}", JSON.toJSONString(deviceList));
            }

        } catch (Exception e) {
            log.error("异常:", e);
        }
    }
}
