package thyyxxk.webserver.scheduled;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.dao.his.triage.TriageDao;
import thyyxxk.webserver.entity.triage.MessageForPush;
import thyyxxk.webserver.entity.triage.MzfzPatientOrder;
import thyyxxk.webserver.entity.triage.TriageNotifyRelation;
import thyyxxk.webserver.utils.VoiceUtil;
import thyyxxk.webserver.websocket.WebSocketServer;

import java.util.List;

@Slf4j
@Component
public class QueryNotifiedPatients {
    private final TriageDao dao;
    @Value("${execute-scheduled}")
    private Boolean executeScheduled;

    @Autowired
    public QueryNotifiedPatients(TriageDao dao) {
        this.dao = dao;
    }

    @Scheduled(fixedRate = 6000)
    public void query() {
        if (executeScheduled) {
            List<TriageNotifyRelation> unNotifiedList = dao.selectUnNotifiedList();
            if (null == unNotifiedList || unNotifiedList.isEmpty()) {
                return;
            }
            for (TriageNotifyRelation item : unNotifiedList) {
                MzfzPatientOrder patient = dao.getPatientTriageInfo(item.getSerialNo());
                MessageForPush param = new MessageForPush();
                param.setAction(1);
                param.setSerialNo(patient.getSerialNo());
                param.setFzNo(patient.getFzNo());
                param.setName(patient.getName());
                param.setDeptName(patient.getDeptName());
                param.setRoomNo(patient.getRoomNo());
                param.setRoomCode(patient.getRoomCode());
                final String msg = JSON.toJSONString(param);
                String text = String.format("请%s号%s，到%s%s号诊室就诊。", param.getFzNo(), param.getName(),
                        param.getDeptName(), param.getRoomNo());
                VoiceUtil.textToSpeech(text, String.valueOf(param.getSerialNo()));
                WebSocketServer.sendFloorTriageMessage(item.getSocketSid(), msg);
                WebSocketServer.sendRoomTriageMessage(item.getRoomCode(), msg);
                dao.updateNotifyDatetime(param.getSerialNo());
            }
        }
    }
}
