package com.ozs.web.controller.websocket;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ozs.common.core.domain.entity.SysUser;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.entity.BaseCameraManagement;
import com.ozs.entity.MsgAlarm;
import com.ozs.entity.MsgAlarmExt;
import com.ozs.entity.MsgWebPush;
import com.ozs.entity.vo.MsgAlarmResp;
import com.ozs.service.BaseRailwayManagementService;
import com.ozs.service.BaseUserService;
import com.ozs.service.MsgAlarmExtService;
import com.ozs.service.MsgWebPushService;
import com.ozs.system.service.ISysDictDataService;
import com.ozs.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author : sunhh
 * @create 2023/6/5 17:04
 */
@Slf4j
@Component
public class WebSocketCommon {

    @Autowired
    private WebSocketServer webSocketServer;
    @Resource
    private BaseRailwayManagementService baseRailwayManagementService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private MsgWebPushService msgWebPushService;
    @Autowired
    private BaseUserService baseUserService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private MsgAlarmExtService msgAlarmExtService;

    public Map publish(@RequestBody MsgAlarm msgAlarm) {
        String endMile = null;
        log.info("消息推送:" + msgAlarm.toString());
//        LambdaQueryWrapper<BaseCameraManagement> wrapper = new LambdaQueryWrapper<BaseCameraManagement>();
//        if (!ObjectUtils.isEmpty(msgAlarm.getCameraCode())) {
//            wrapper.eq(BaseCameraManagement::getCameraCode, msgAlarm.getCameraCode());
//        }
//        BaseCameraManagement baseCameraManagement = baseCameraManagementService.getOne(wrapper);
//        log.info("baseCameraManagement-----" + baseCameraManagement);

//        String[] list = set.toArray(new String[set.size()]);
//        List<String> userIdList = new ArrayList<>(set);
        MsgAlarmResp msgAlarmResp = new MsgAlarmResp();
        if (!StringUtils.isEmptySunhh(msgAlarm.getEndMile()) && !StringUtils.isEmptySunhh((msgAlarm.getBeginMile()))) {
            String begin = AppendUtils.stringAppend(Integer.valueOf(msgAlarm.getBeginMile()));
            String end = AppendUtils.stringAppend(Integer.valueOf(msgAlarm.getEndMile()));
            endMile = begin + "-" + end;
            msgAlarmResp.setBeginMile(endMile);
        }
        msgAlarmResp.setAlarmType(msgAlarm.getAlarmType());
        String mile = AppendUtils.stringAppend(msgAlarm.getAlarmMile());
        msgAlarmResp.setAlarmMiles(msgAlarm.getAlarmMile());
        msgAlarmResp.setAlarmMile(mile);
//        String cameraCode = msgAlarm.getCameraCode();
//        msgAlarmResp.setCameraCode(cameraCode);

        String cameraName = baseRailwayManagementService.getCameraNameByCameraCode(msgAlarm.getRailwayCode());
        msgAlarmResp.setRailwayName(cameraName != null ? cameraName : "");
        msgAlarmResp.setRailwayCode(msgAlarm.getRailwayCode());
        msgAlarmResp.setLineDirStr(msgAlarm.getLineDir() == 1 ? "上行" : "下行");
        msgAlarmResp.setAlarmTime(msgAlarm.getAlarmTime() != null ? msgAlarm.getAlarmTime() : new Date());
        // 图片
        LambdaQueryWrapper<MsgAlarmExt> wrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(msgAlarm.getAlarmId())) {
            wrapper.eq(MsgAlarmExt::getAlarmId, msgAlarm.getAlarmId());
        }
        MsgAlarmExt msgAlarmExt = msgAlarmExtService.getOne(wrapper);
        if (!StringUtils.isEmptySunhh(msgAlarmExt) && !StringUtils.isEmptySunhh(msgAlarmExt.getAlarmAttType())
                && !StringUtils.isEmptySunhh(msgAlarmExt.getAlarmAttPath())) {
            String[] split = msgAlarmExt.getAlarmAttPath().split(";");
            ArrayList<String> objects = new ArrayList<>(Arrays.asList(split));
            log.info("publish--------" + objects);
            msgAlarmResp.setImageUrls(objects);
            msgAlarmResp.setAlarmAttType(msgAlarmExt.getAlarmAttType());
        }
        if (!StringUtils.isEmptySunhh(msgAlarm.getId())) {
            msgAlarmResp.setId(msgAlarm.getId());
        }
        String userIdLogin = "admin编码";
        SysUser user = userService.selectUserById(1L);
        if (!ObjectUtils.isEmpty(user)) {
            userIdLogin = user.getUserId();
        }
        String alarmId = msgAlarm.getAlarmId();
        msgAlarmResp.setAlarmId(alarmId);

        LambdaQueryWrapper<MsgWebPush> lwMsgWebPush = new LambdaQueryWrapper<MsgWebPush>();
        if (!ObjectUtils.isEmpty(msgAlarm.getAlarmId())) {
            lwMsgWebPush.eq(MsgWebPush::getAlarmId, msgAlarm.getAlarmId());
        }
        List<MsgWebPush> msgWebPushList = msgWebPushService.list(lwMsgWebPush);

        // 获取推送人ID列表
//        log.info("publish-----" + baseCameraManagement.getCreateBy() + "-------------" + baseCameraManagement.getDeptId());
        List<String> usetIdList = baseUserService.getUserListAll();
        log.info("set-----" + usetIdList);
        if (StringUtils.isEmpty(msgWebPushList) || msgWebPushList.size() == 0) {
            for (String userid : usetIdList) {
                String pushId = UUID.randomUUID().toString();
                msgAlarmResp.setPushId(pushId);
                String content = objStr(msgAlarmResp);
                log.info("WEBcontent-----" + content);
                log.info("WEBuserid-----" + userid);
                // 存入数据
                MsgWebPush msgWebPush = new MsgWebPush();
                // 推送消息reqMsgAlarmVo
                boolean userOnline = webSocketServer.userOnline(userid);
                log.info("userOnline-userOnline-userOnline-userOnline-----：：：：：：" + userOnline);
                if (userOnline) {
                    webSocketServer.sendOneMessage(userid, content);
                    msgWebPush.setOnline("1");
                } else {
                    // online 是否推送，1:推送，2:未推
                    msgWebPush.setOnline("2");
                }
                msgWebPush.setRemark(content);
                // 状态：1未读；2已读
                msgWebPush.setStatus(1);
                msgWebPush.setPushId(pushId);
                msgWebPush.setAlarmId(alarmId);
                msgWebPush.setReceiveBy(userid);
                msgWebPush.setCreateBy(userIdLogin);
                msgWebPush.setCreateTime(new Date());
                msgWebPush.setUpdateBy(userIdLogin);
                msgWebPush.setUpdateTime(new Date());
                msgWebPushService.save(msgWebPush);
            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 200);
        return map;
    }

    private String objStr(MsgAlarmResp msgAlarmResp) {
        JSONObject obj = new JSONObject();
        obj.put("data", msgAlarmResp); //data
        obj.put("code", 110); //code
        log.info("【websocket消息】 单点消息:" + obj.toJSONString());
        return obj.toJSONString();
    }
}
