<template>
  <div>




<div class="chat__messages">

      <div class="chat__message" v-for="message in messages">
          <div>{{ message.d }}</div>
          <div>{{ message.text }}</div>
      </div>

</div>


    <div class="chat">
           <my-input v-on:keyup.enter="QQ" v-model="text"></my-input><my-button  @click="QQ">ok</my-button>

    </div>

  </div>
</template>

<script>
// We store the reference to the SSE client out here
// so we can access it from other methods
import test from "./test.vue";

import axios from 'axios';

let sseClient;

export default {
  name: 'sse-test',
  components: {},
  computed: {

  },
  data() {
    return {
      messages: [],
      text:'',
      obj: {},
      port:3024,


    };
  },
  mounted() {
    sseClient = this.$sse.create({
      url: 'http://10.10.0.168:'+this.port+'/events',
      format: 'text',
      withCredentials: false,
      polyfill: true,
    });


    sseClient.on('message', this.handleChat);


    sseClient.connect()
        .then(sse => {
          console.log('We\'re connected!');

        })
        .catch((err) => {

          console.error('Failed to connect to server', err);
        });
  },
  methods: {

    async sendData() {
      const response = await fetch('http://10.10.0.168:'+this.port+'/user', { method: "POST", body: "Pavel Zykov"});
      const responseText = await response.text();
      console.log(responseText);
    },

    QQ(){

      this.queryQ().then(
          (r)=>{

            //console.log(r.data);
            this.text='';
          }


      )

    },


    async queryQ() {
      //let error=new Event('error');

      try {

        const json = JSON.stringify({
          data: JSON.stringify({name:this.text,id:1}),
        });


        const response = await axios.post("http://10.10.0.168:"+this.port+"/user",json,{
          headers: {'Content-Type': 'application/json'}
        });
        console.log(response);
        return response.data;

      } catch (e) {
        console.log(e)
      } finally {

      }
    },



    handleChat(event) {
//console.log(event);
     // this.messages.push(event);
      this.obj=JSON.parse(event);
      this.messages.push(this.obj);

    },

  },
  beforeDestroy() {
    // Make sure to close the connection with the events server
    // when the component is destroyed, or we'll have ghost connections!
    sseClient.disconnect();

    // Alternatively, we could have added the `sse: { cleanup: true }` option to our component,
    // and the SSEManager would have automatically disconnected during beforeDestroy.
  },
};
</script>
<style scoped>
.chat{
 display: flex;
  gap:5px;
margin-top: 10px;
}

.chat__messages{
  border-radius: 8px;
  border: 1px solid #ababab;
padding: 10px;
  overflow-x: hidden;
  overflow-y: auto;
  height: 85vh;
}

.chat__message{
  display: flex;
  flex-direction: column;
  gap: 5px;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #ababab;
  margin-top: 10px;
}

</style>
