<template>
  <div class="experiment_page">
    <div class="base-msg">
      <div class="experiment">
        <div class="msg-add">
          <div class="base">
          <div class="title">试验参数</div>

            <span>目标温度</span>
            <div style="position: relative">
              <el-input
                class="normal_input"
                size="small"
                v-model="tagTemp"
                placeholder="请输入"
                clearable />
              <span
                style="
                  margin-left: 20px;
                  position: absolute;
                  right: 0.1rem;
                  top: -0.08rem;
                  color: rgba(0, 0, 0, 0.4);
                ">
                ℃
              </span>
            </div>
          </div>
          <div class="button">
            <CommonButton
              v-if="!startStatus"
              class="btn"
              msg="确定"
              size="default"
              paddingLeft="33"
              paddingRight="33"
              height="60"
              :type="begin ? 'disabledColor' : 'danger' "
              @click="confirm"></CommonButton>
          </div>
        </div>
        <div class="experiment-msg" style="justify-content: start">
          <CommonButton
            v-if="!startStatus"
            class="btn"
            msg="返回"
            size="default"
            paddingLeft="33"
            paddingRight="33"
            height="60"
            @click="confirmExit"></CommonButton>
        </div>
      </div>

      <div class="experiment">
        <div class="echart">
          <div class="current-temp">当前温度 <span>{{ currentTemp }}</span> ℃</div>
          <CommonCharts :chartOption="chartOption"  />
        </div>
        <div class="experiment-msg">
          <CommonButton
            v-if="!startStatus"
            class="btn"
            msg="开始实验"
            size="default"
            paddingLeft="33"
            paddingRight="33"
            height="60"
            :type=" canStart ? 'danger' : 'disabledColor' "
            @click="startExperiment"></CommonButton>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { notify } from '@/utils/message';

import {  stopExperimentApi,openExe  ,sendMsgApi} from '@/api/experiment.js';

import { showConfirmDialog } from 'vant';

let tagTemp = ref(100);
let currentTemp = ref(0);
let ws = ref(null);
//试验状态码
onMounted(() => {
  viewEcharts();
  ws = new WebSocket('ws://' + import.meta.env.VITE_WEBSOCKET_URL + '/api/get_status');

  ws.onopen = () => {
    console.log('WebSocket 连接已建立！');
    if (ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({ username: '张三', age: 33 }));
    } else {
      console.error('Websocket未连接');
    }
  };

  ws.onmessage = (event) => {
    let exp_data = JSON.parse(event.data);
    let { t, temp } = exp_data;
    currentTemp.value = temp;
    if (begin.value && temp >= tagTemp.value) {
      canStart.value = true
    }
    chartOption.value.series_data.push(temp);
    chartOption.value.x_data.push(t);
    console.log(chartOption.value);
  };
});

onUnmounted(() => {
  ws.close();
});

let begin = ref(false)
let canStart = ref(false)
const confirm = () =>{
  begin.value = true
  sendMsgApi({tem:parseFloat(tagTemp.value)})
}

let chartOption = ref({});
const viewEcharts = () => {
  chartOption.value = {
    name: '',
    xAxis_name: '时间/s',
    yAxis_name: '温度/℃',
    series_name: '温度曲线',
    x_data: [],
    series_data: [],
  };
};
const router = useRouter();
const route = useRoute();
let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
let { userId, userName } = userInfo || {};

const disabledComponents = computed(() => {
  return ['disableKeyboard'];
});

let countTime = ref(0);
let startStatus = ref(false);
const startExperiment = async () => {
  if(!canStart.value){
    return
  }
  openExe()
};


const exitPage = () => {
  clearInterval(countTime.value);
  countTime.value = null;
  router.push('/home');
};
const confirmExit = () => {
  showConfirmDialog({
    title: '确认退出实验？'
  })
    .then(() => {
      exitExperiment();
      clearInterval(countTime.value);
      countTime.value = null;
    })
    .catch(() => {
      notify('已取消', 'primary');
    });
};
//结束实验 type:1为手动结束 2为自动结束 默认为1
const exitExperiment = async (type = 1) => {
  console.log('exitExperiment');
 
  let res = await stopExperimentApi();
  let { code, desc } = res.data;
  if (code == 200) {
   
      router.push('/home');
  } else {
    notify(desc);
  }
};

const stopExperiment = async (val) => {
  webSocket.value.close(); //关闭websock

  let data = {
    record_id: record_id.value,
    is_stop: val
  };
  const res = await stopExperimentApi(data);
  router.push({
    path: '/report/detail',
    query: {
      experiment_id: experiment_id.value
    }
  });
};

</script>
<style lang="less" scoped>
@COOMSIZE: 12px;

.base-msg {
  display: grid;
  grid-template-columns: 2.4rem 1fr;
  grid-template-rows: 1fr;
  height: 100%;

  .msg-add {
    height: 100%;
    background: #f6f6f6;
    width: 2.4rem;
    border-radius: 0.05456rem;
    border: 1px solid #e6e6e6;
    padding: 10px;
    display: flex;
    flex-direction: column;
    position: relative;
    border-right: 1px;
    border-radius: 5px 0px 0px 5px;
    justify-content: space-between;
    // justify-content: space-between;
    .title {
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: bold;
      font-size: 14px;
      color: #3a3a3a;
      font-style: normal;
      margin-bottom: 10px;
    }
    .base {
      display: flex;
      flex-direction: column;
    }
    .normal_input {
      width: 100%;
    }
    .button {
      margin-top: 30px;
      width: 100%;
    }
    .btn {
      margin: 0;
      width: 100%;
    }
    // gap: 10px;
    span {
      margin-top: 10px;
      margin-bottom: 3px;
      font-size: 12px;
      color: #424242;
    }
  }

  .experiment {
    display: flex;
    flex-direction: column;
    gap: 10px;

    .experiment-msg {
      gap: 10px;
      font-size: 10px;
      display: flex;
      justify-content: end;

      .time {
        border-bottom: 1px solid #e6e6e6;
        padding: 2px 8px;
        background: #f6f6f6;
        border-radius: 0.05456rem;
        border: 0.01546rem solid #e6e6e6;
      }

      .status {
        display: flex;
        justify-content: space-around;
        padding: 10px 0;
        background: #f6f6f6;
        flex: 1;
        border-radius: 0.05456rem;
        border: 0.01546rem solid #e6e6e6;

        span {
          display: flex;
          flex-direction: column;
          gap: 5px;
        }

        .experiment-status {
          color: red;
        }

        .num {
          font-size: 12px;
          color: black;

          .unit {
            display: inline-block;
            font-size: 10px;
            color: gray;
          }
        }
      }
    }
    .echart {
      flex: 1;
      background: #f6f6f6;
      // margin: 10px;
      border-radius: 0.05456rem;
      border: 1px solid #e6e6e6;
      display: flex;
      flex-direction: column;
      padding: 10px;
      border-radius: 0 5px 5px 0;
      .button {
        display: flex;
        justify-content: flex-end;
        .left {
          display: flex;
          // flex-direction: column;
          gap: 10px;
        }
      }
    }
    .button {
      display: flex;
      justify-content: space-between;
    }
  }
}

.experiment_page {
  width: 97vw;
  height: 85%;
  position: fixed;
  .el-form--inline .el-form-item {
    width: 50%;
    margin-right: 0px;
  }

  ::v-deep .el-form-item__label {
    padding-right: 3px;
    font-size: @COOMSIZE;
  }

  .el-input {
    width: 80%;
  }

  .footer_btn {
    display: flex;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100vw;
    background: #ffffff;
    justify-content: space-between;
    padding: 4px 4px 12px;
    z-index: 100;
  }
}
.current-temp{
  font-size: 10px;
  text-align: center;
  span{
    font-size: 16px;
  }
}
</style>
