<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { ElScrollbar, ElInput, ElButton } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus'
import  DevicePerformanceTable  from '@/components/DevicePerformanceTabel'

const innerRef = ref<HTMLDivElement>();
const scrollbarRef = ref<InstanceType<typeof ElScrollbar>>();
const input = ref('');
const items = ref<string[]>([
  JSON.stringify([{"CMDS": "$,", "Xaxis": "034.00", "Comma": ",", "Yaxis": "034.00", "Azimuth": "000.00", "ElevationAngle": "090.00", "ACUstatus": "P", "XTrackerSigIntensity": "255", "YTrackerSigIntensity": "255", "X_STATUS": "244", "Y_STATUS": "245", "XInitPhase": "012", "XPolarizationType": "1", "SPolarizationType": "0", "XTrackerVoltageLimit": "255", "STrackerVoltageLimit": "255", "SUpPolarizationType": "1", "XUpPolarizationType": "1", "TrackingStatus": "0", "TrackingBand": "1", "X-Bias": "+0.00", "Y-Bias": "+0.00", "END": "\r\n", "XaxisAlarm": "0", "XaxisServoStatus": "1", "EasternLimit": "0", "WestLimit": "0", "YaxisAlarm": "0", "YaxisServoStatus": "1", "SouthrLimit": "0", "NorthLimit": "1"}]),
  JSON.stringify([{"CMDS": "$,", "Xaxis": "034.00", "Comma": ",", "Yaxis": "034.00", "Azimuth": "000.00", "ElevationAngle": "090.00", "ACUstatus": "P", "XTrackerSigIntensity": "255", "YTrackerSigIntensity": "255", "X_STATUS": "244", "Y_STATUS": "245", "XInitPhase": "012", "XPolarizationType": "1", "SPolarizationType": "0", "XTrackerVoltageLimit": "255", "STrackerVoltageLimit": "255", "SUpPolarizationType": "1", "XUpPolarizationType": "1", "TrackingStatus": "0", "TrackingBand": "1", "X-Bias": "+0.00", "Y-Bias": "+0.00", "END": "\r\n", "XaxisAlarm": "0", "XaxisServoStatus": "1", "EasternLimit": "0", "WestLimit": "0", "YaxisAlarm": "0", "YaxisServoStatus": "1", "SouthrLimit": "0", "NorthLimit": "1"}]),
  JSON.stringify([{"CMDS": "$,", "Xaxis": "034.00", "Comma": ",", "Yaxis": "034.00", "Azimuth": "000.00", "ElevationAngle": "090.00", "ACUstatus": "P", "XTrackerSigIntensity": "255", "YTrackerSigIntensity": "255", "X_STATUS": "244", "Y_STATUS": "245", "XInitPhase": "012", "XPolarizationType": "1", "SPolarizationType": "0", "XTrackerVoltageLimit": "255", "STrackerVoltageLimit": "255", "SUpPolarizationType": "1", "XUpPolarizationType": "1", "TrackingStatus": "0", "TrackingBand": "1", "X-Bias": "+0.00", "Y-Bias": "+0.00", "END": "\r\n", "XaxisAlarm": "0", "XaxisServoStatus": "1", "EasternLimit": "0", "WestLimit": "0", "YaxisAlarm": "0", "YaxisServoStatus": "1", "SouthrLimit": "0", "NorthLimit": "1"}]),
  JSON.stringify([{"CMDS": "$,", "Xaxis": "034.00", "Comma": ",", "Yaxis": "034.00", "Azimuth": "000.00", "ElevationAngle": "090.00", "ACUstatus": "P", "XTrackerSigIntensity": "255", "YTrackerSigIntensity": "255", "X_STATUS": "244", "Y_STATUS": "245", "XInitPhase": "012", "XPolarizationType": "1", "SPolarizationType": "0", "XTrackerVoltageLimit": "255", "STrackerVoltageLimit": "255", "SUpPolarizationType": "1", "XUpPolarizationType": "1", "TrackingStatus": "0", "TrackingBand": "1", "X-Bias": "+0.00", "Y-Bias": "+0.00", "END": "\r\n", "XaxisAlarm": "0", "XaxisServoStatus": "1", "EasternLimit": "0", "WestLimit": "0", "YaxisAlarm": "0", "YaxisServoStatus": "1", "SouthrLimit": "0", "NorthLimit": "1"}]),
  JSON.stringify([{"CMDS": "$,", "Xaxis": "034.00", "Comma": ",", "Yaxis": "034.00", "Azimuth": "000.00", "ElevationAngle": "090.00", "ACUstatus": "P", "XTrackerSigIntensity": "255", "YTrackerSigIntensity": "255", "X_STATUS": "244", "Y_STATUS": "245", "XInitPhase": "012", "XPolarizationType": "1", "SPolarizationType": "0", "XTrackerVoltageLimit": "255", "STrackerVoltageLimit": "255", "SUpPolarizationType": "1", "XUpPolarizationType": "1", "TrackingStatus": "0", "TrackingBand": "1", "X-Bias": "+0.00", "Y-Bias": "+0.00", "END": "\r\n", "XaxisAlarm": "0", "XaxisServoStatus": "1", "EasternLimit": "0", "WestLimit": "0", "YaxisAlarm": "0", "YaxisServoStatus": "1", "SouthrLimit": "0", "NorthLimit": "1"}]),
]);
const flag = ref<boolean>(false);

let chatSocket: WebSocket | null = null;

const send = () => {
  if (chatSocket === null) {
    console.error('chatSocket is null');
    return;
  }
  chatSocket.send(JSON.stringify({
    'message': input.value
  }));
  input.value = '';
}

watch(flag, () => {
  setTimeout(() => {
    scrollbarRef.value!.setScrollTop(innerRef.value!.offsetHeight);
  }, 50);
});

onMounted(() => {
  chatSocket = new WebSocket(
    'ws://'
    + window.location.host
    + '/ws/chat/mqtt/'
  );

  chatSocket.onmessage = (e) => {
    // console.log(e);
    // console.log(e.data)
    // // 接收到的是字节流数据（ArrayBuffer）
    // const byteArray = new Uint8Array(e.data);
    // // 将字节流转换为字符串或其他格式进行处理
    // const message = byteArray.toString();
    // items.value.push(JSON.stringify(e.data));
    items.value.push(e.data);
    flag.value = !flag.value
  };

  chatSocket.onclose = (e) => {
    console.error('Chat socket closed unexpectedly', e);
  };
})

const deviceTableParams = ref<string[]>([]);
const addDeviceTable = () => {
  ElMessageBox.prompt('Please input WebSocket group name', 'Tip', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
  })
    .then(({ value }) => {
      ElMessage({
        type: 'success',
        message: `new websocket group name is chat_${value}`,
      })
      deviceTableParams.value.push(value);
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Input canceled',
      })
    })
}

</script>

<template>
  <el-scrollbar ref="scrollbarRef" mb-10 height="400px" always>
    <div ref="innerRef">
      <p v-for="item in items" :key="item" class="scrollbar-demo-item text-sm">
        <div>{{ JSON.parse(item)?.ts }}</div>
        {{ item }}
      </p>
    </div>
  </el-scrollbar>

  <el-input v-model="input" placeholder="Please input" @keyup.enter="send"></el-input>
  <el-button @click="send">Send</el-button>

  <device-performance-table v-for="param in deviceTableParams" mt-5 :group-name="param" :key="param" />
  <el-button @click="addDeviceTable" class="mt-5" >Add table</el-button>
</template>

<style scoped>
.scrollbar-demo-item {
  display: flex;
  /* align-items: center; */
  /* justify-content: center; */
  height: auto;
  margin: 10px;
  text-align: left;
  border-radius: 4px;
  background: #fff;
  color: #4d4c4c;
}
</style>
