package com.tuoheng.admin.websocket;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.tuoheng.admin.constant.WebSocketConstant;
import com.tuoheng.admin.entity.Accident;
import com.tuoheng.admin.enums.AccidentStatusEnum;
import com.tuoheng.admin.mapper.AccidentMapper;
import com.tuoheng.admin.request.accident.QueryAccidentListRequest;
import com.tuoheng.admin.service.accident.build.BuildAccidentVoListService;
import com.tuoheng.admin.vo.accident.AccidentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class WebSocketServiceImpl implements WebSocketService {

    @Autowired
    private AccidentMapper accidentMapper;

    @Autowired
    private BuildAccidentVoListService buildAccidentVoListService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void accidentNotice(String tenantId) {
        QueryAccidentListRequest request = new QueryAccidentListRequest();
        List<Integer> statusList = new ArrayList<>();
        statusList.add(AccidentStatusEnum.UNTREATED.getCode());
        statusList.add(AccidentStatusEnum.PROCESSING.getCode());
        statusList.add(AccidentStatusEnum.PROCESSED.getCode());
        request.setStatusList(statusList);
        request.setTenantId(tenantId);
        List<Accident> accidentList = accidentMapper.selectAccidentList(request);

        // 构造返回结果对象
        List<AccidentVo> accidentVoList = buildAccidentVoListService.build(accidentList);

        if (CollectionUtil.isNotEmpty(accidentVoList)) {
            String json = JSONObject.toJSONString(accidentVoList, SerializerFeature.WriteMapNullValue);
            redisTemplate.convertAndSend(WebSocketConstant.TOPIC_ACCIDENT, json);
        }
    }

}
