<template>
  <div class="third-step">
    <div style="display: flex; justify-content: space-between; align-items: center">
      <div class="step_title">{{ page_title || '未知' }}</div>
      <div style="font-size: 24px; color: #06a800">{{ experimentData.status_text }}</div>
    </div>

    <div class="result_info">
      <div class="info_card">
        <div class="row">
          <div class="info_card_left">
            <div class="info_card_item test_title">{{ experimentalData.name }}</div>
          </div>
          <div class="info_card_right">
            <div class="info_card_item">
              试验用时：{{ experimentData.work_time }}s
              <!-- <svg-icon name="yellow_tip" size="12" />
              请将试验放置在玻璃板，就绪后开始试验！ -->
            </div>
          </div>
        </div>
        <div class="row_col">
          <div class="col">
            <div class="col_title">样品类型</div>
            <div class="col_content">
              <div class="col_num col_size">{{ getTypeName(experimentalData.material_type) }}</div>
            </div>
          </div>
          <div class="col">
            <div class="col_title">单次试验时长</div>
            <div class="col_content">
              <div class="col_num">{{ experimentalData.simple_time }}</div>
              <div class="col_unit">s</div>
            </div>
          </div>
          <div class="col">
            <div class="col_title">当前功率</div>
            <div class="col_content">
              <div class="col_num">{{ experimentData.rate || 0 }}</div>
              <div class="col_unit">W</div>
            </div>
          </div>
        </div>
        <div class="row_col">
          <div class="col col_w">
            <div class="col_title">当前准备</div>
            <div class="col_content">
              <div class="col_num col_red">第{{ N }}次试验</div>
            </div>
          </div>
          <div class="col" :class="query.data == '3' ? 'col_w' : 'col_w1'">
            <div class="col_title">检测质量</div>
            <div class="col_content">
              <div class="col_num">{{ experimentData.weight }}</div>
              <div class="col_unit">g</div>
            </div>
          </div>
          <div class="col col_w" v-if="query.data == '3'">
            <div class="col_title">平均燃烧速率</div>
            <div class="col_content" v-if="experimentalData.burning_rate">
              <div class="col_num">
                {{ experimentalData.burning_rate }}
              </div>
              <div class="col_unit">g/s</div>
            </div>
            <div class="col_content" v-else>暂无</div>
          </div>
        </div>
        <div class="table_part">
          <div class="chart_container" v-if="query.data == '3'">
            <CommCharts :chartOption="chart" />
          </div>
          <div class="table_container">
            <vxe-table :data="tableData" stripe min-height="220px">
              <vxe-column field="number" title="试验序号" width="138"></vxe-column>
              <vxe-column field="start_time" title="开始时间" width="260"></vxe-column>
              <vxe-column
                v-if="query.data == '1'"
                field="fanying_time"
                title="反应时间(s)"
                width="200"></vxe-column>
              <vxe-column
                v-if="query.data == '3'"
                field="burning_rate"
                title="燃烧速率(g/s)"
                width="200"></vxe-column>
              <vxe-column field="rsqk" title="燃烧情况" width="180"></vxe-column>
              <vxe-column title="操作" width="120">
                <template #default="{ row }">
                  <div class="operate-container">
                    <span style="color: #cf4a4a; margin-left: 8px" @click="deleteRecode(row)">
                      删除
                    </span>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </div>
    </div>
    <div class="footer_btn">
      <div style="display: flex">
        <CommonButton msg="退出试验" size="default" type="warning" @click="stopExperiment('out')" />
        <CommonButton msg="天平置零" size="default" type="default" @click="sendMsg('ZEROING', 1)" />
        <CommonButton msg="天平校准" size="default" type="default" @click="promptVisibile = true" />
        <CommonButton
          msg="点火丝成型"
          size="default"
          type="info"
          @click="sendMsg('HEARTING', 15)" />
      </div>

      <div style="display: flex">
        <CommonButton msg="完成试验" size="default" type="primary" @click="finishExperiment()" />
        <CommonButton
          msg="开始试验"
          size="default"
          type="danger"
          @click="selfCheck()"
          v-if="!start_status" />
        <CommonButton
          msg="结束试验"
          size="default"
          type="danger"
          @click="stopExperiment()"
          v-if="start_status" />
      </div>
    </div>
    <CommonConfirm
      msg="请确保试样已经放置在玻璃板上"
      @cancel="confirmVisibile = false"
      @confirm="handleConfirm"
      :visibile="confirmVisibile" />
    <CommonPrompt
      msg="请输入试样重量"
      @cancel="promptVisibile = false"
      @confirm="handleConfirmPrompt"
      :visibile="promptVisibile" />
    <CommonConfirm
      msg="确定完成试验吗？"
      @cancel="finishVisibile = false"
      @confirm="handlefinish"
      :visibile="finishVisibile" />
    <CommonConfirm
      msg="点火丝烧断了，请及时更换！"
      @cancel="ignitionWireVisibile = false"
      @confirm="ignitionWireVisibile = false"
      :visibile="ignitionWireVisibile" />
    <div class="mask" v-show="showMask">
      <div class="mask_tip">确认点火倒计时</div>
      <div id="countdown" class="mask_num">5</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getReportDetailApi } from '@/api/report.js';
import {
  getExperimentDetailApi,
  sendMsgApi,
  stopExperimentApi,
  selfCheckApi,
  machineInsertExperimentApi,
  deleteRecodeApi
} from '@/api/experiment';
import Table from './Table.vue';
import CommCharts from '@/components/CommCharts.vue';
import { notify } from '@/utils/message.js';
import { websocketStore } from '@/store/webSocketStore.js';
let route = useRoute();
let router = useRouter();
let { path, query } = route;
let page_title = ref(query.data == '1' ? 'O.1正式试验流程-试验' : 'O.3正式试验流程-试验');
// let material_type = ref(query.material_type);
// let simple_time = ref(query.simple_time);
let experiment_id = ref(query.experiment_id);
let fire_type = ref(query.fire_type);
// let experiment_id = ref('9709ece6-4028-11ef-9492-8cc84ba8982e');
const start_status = ref(false); // 试验是否开启
const finish_status = ref(false); // 试验是否完成
const ignitionWireVisibile = ref(false); // 判断点火丝是否烧断

let base_info = ref({
  material_name: '',
  experiment_user_name: '',
  start_time: '',
  total_count: 0
});

let tableData = ref([]);

// 记录第几次试验
const N = ref(1);

const getTypeName = (type) => {
  let name = '';
  switch (type) {
    case '1-1':
      name = '样品与纤维素重量1:1';
      break;
    case '4-1':
      name = '样品与纤维素重量4:1';
      break;
    case '3-2':
      name = '溴酸钾与纤维素重量3:2';
      break;
    case '2-3':
      name = '溴酸钾与纤维素重量2:3';
      break;
    case '3-7':
      name = '溴酸钾与纤维素重量3:7';
      break;
    case '3-1':
      name = '过氧化钙与纤维素重量3:1';
      break;
    case '5-5':
      name = '过氧化钙与纤维素重量1:1';
      break;
    case '1-2':
      name = '过氧化钙与纤维素重量1:2';
      break;
    default:
      name = '未知';
      break;
  }
  return name;
};

const experimentalData = ref({});
// 获取试验详情
const getExperimentDetail = async () => {
  let res = await getExperimentDetailApi({ experiment_id: experiment_id.value });
  let { code, data, desc } = res.data;
  if (code == 200) {
    if (data.burning_rate) {
      data.burning_rate = parseFloat(data.burning_rate).toFixed(2);
    }
    experimentalData.value = data;
    data.info?.forEach((item) => {
      item.fanying_time = item.fanying_time / 1000;
      if (item.burning_rate) {
        item.burning_rate = parseFloat(item.burning_rate).toFixed(2);
      }
    });
    tableData.value = data.info;
  } else {
    notify(desc);
  }
};
getExperimentDetail();

const sendMsg = async (msg, status) => {
  let res = await sendMsgApi({ name: msg, status: status });
  let { code, desc } = res.data;
  if (code == 200) {
    notify(desc, 'success');
  } else {
    notify(desc);
  }
};

// 删除单个试验
const deleteRecode = async (row) => {
  let res = await deleteRecodeApi(row.record_id);
  if (res.data.code == 200) {
    notify(res.data.desc, 'success');
    getExperimentDetail();
  } else {
    notify(res.data.desc, 'danger');
  }
};

// 结束试验
const stopExperiment = async (val) => {
  console.log(val);
  let res = await stopExperimentApi({ id: experiment_id.value });
  let { code, desc } = res.data;
  if (code == 200) {
    if (val == 'out') {
      router.push('/home');
    } else {
      notify(desc, 'success');
    }
  } else {
    notify(desc);
  }
};

const finishVisibile = ref(false);
// 完成试验
const finishExperiment = async () => {
  finishVisibile.value = true;
};

const handlefinish = async () => {
  finishVisibile.value = false;
  let res = await stopExperimentApi({ id: experiment_id.value });
  let { code, desc } = res.data;
  if (code) {
    // notify(desc, 'success');
    router.push({
      path: '/equipment/thirdStep',
      query: {
        experiment_id: experiment_id.value,
        data: query.data
      }
    });
  } else {
    notify(desc);
  }
};

const confirmVisibile = ref(false);
// 安全检查
const selfCheck = async () => {
  let res = await selfCheckApi();
  let { code, desc } = res.data;
  if (code) {
    // notify(desc, 'success');
    confirmVisibile.value = true;
  } else {
    notify(desc);
    confirmVisibile.value = true;
  }
};

const showMask = ref(false);
const handleConfirm = async () => {
  confirmVisibile.value = false;
  if (fire_type.value == '6' || fire_type.value == '7') {
    // 延时点火
    let countdown = 5; // 10秒倒计时
    showMask.value = true; // 开启蒙版
    // 开始倒计时
    let timer = setInterval(() => {
      countdown -= 1;
      // 更新界面上的倒计时显示
      document.getElementById('countdown').innerHTML = `${countdown}`;
      if (countdown <= 0) {
        clearInterval(timer);
        showMask.value = false;
        countdown = 5;
        // 执行延时点火操作
        startExperiment();
      }
    }, 1000); // 每秒执行一次
  } else {
    startExperiment();
  }
};

const promptVisibile = ref(false);
const handleConfirmPrompt = (val) => {
  // notify('开始试验', 'success');
  console.log(val);
  if (val && 1 <= val <= 2000) {
    promptVisibile.value = false;
    sendMsg('CALIBRATION', val);
  } else {
    notify('请输入重量且重量范围在1-2000之间', 'danger');
  }
};

// 开始试验
const startExperiment = async () => {
  let res = await machineInsertExperimentApi({
    items: {
      fire_type: fire_type.value,
      simple_time: experimentalData.value.simple_time,
      experiment_id: experiment_id.value,
      number: N.value
    }
  });
  let { code, desc } = res.data;
  if (code == 200) {
    chart.value.x_data = [];
    chart.value.y_data = [];
    start_status.value = true;
    N.value++;
    notify(desc, 'success');
  } else {
    notify(desc);
  }
};
const chart = ref({
  name: '质量损失趋势图',
  yAxis_name: '质量(g)',
  xAxis_name: '时间(s)',
  id: 'riseTemp',
  x_data: [],
  y_data: []
});

const experimentData = ref({});
let socket = websocketStore();
onMounted(() => {
  socket.init({ isActiveClose: false });
});
watch(
  () => socket.serviceMsg,
  async (newVal) => {
    //执行操作，更新视图
    console.log(newVal, 'sfsf');
    let { rate, weight, status, status_text, work_time } = newVal;
    weight = weight.toFixed(2);
    rate = rate.toFixed(2);
    work_time = (work_time / 1000).toFixed(0);
    experimentData.value = { rate, weight, status, status_text, work_time };
    if (start_status.value) {
      chart.value.x_data.push(work_time);
      chart.value.y_data.push(weight);
    }
    //状态切换 判断结束状态
    if (status_text == '停止并复位状态' && start_status.value) {
      start_status.value = false;
    }

    // 监测试验完成
    if (status == '6' && start_status.value && !finish_status.value) {
      getExperimentDetail();
      finish_status.value = true;
      setTimeout(() => {
        finish_status.value = false;
      }, 5000);
    }

    // 监测加热丝断掉
    if (status == '52' && start_status.value) {
      // 弹框提示
      ignitionWireVisibile.value = true;
    }
    // 当试验完成处理数据
    if (experimentData.value.status) {
      console.log('本次试验完成');
    }
  }
);
onUnmounted(() => {
  socket.close({ isActiveClose: true });
});
</script>
<style lang="less" scoped>
@COOMSIZE: 14px;
.third-step {
  width: 100%;
  overflow: auto;
  .step_title {
    font-size: 16px;
    font-weight: bold;
    color: #3a3a3a;
    // margin-left: 22px;
    // margin-bottom: 12px;
  }
  .result_info {
    padding: 12px;
    position: relative;
    margin-bottom: 70px;
    .info_card {
      font-size: @COOMSIZE;
      background: #f6f6f6;
      box-shadow: 0px 3px 9px 1px rgba(0, 0, 0, 0.16);
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #cccccc;
      color: #3a3a3a;
      .row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 12px;
        height: 40px;
        line-height: 40px;
        box-sizing: border-box;
        .info_card_left,
        .info_card_right {
          display: flex;
          justify-content: flex-start;
          gap: 24px;
          .test_title {
            font-size: 16px;
          }
          .info_card_item {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
      .row:first-child {
        border-bottom: 1px solid #dcdcdc;
      }
      .row:last-child {
        border-top: 1px solid #dcdcdc;
      }
      .row_col {
        display: flex;
        height: 52px;

        .col {
          width: 207px;
          padding: 6px 12px;
          border-bottom: 1px solid #dcdcdc;
          border-left: 1px solid #dcdcdc;
          .col_content {
            margin-top: 4px;
            display: flex;
            align-items: center;
            .col_num {
              font-size: 16px;
            }
            .col_size {
              font-size: 14px;
            }
            .col_red {
              font-size: 14px;
              color: #cf4a4a;
            }
            .col_unit {
              margin-left: 8px;
              color: #888888;
            }
          }
        }
        .col_w {
          width: 207px;
        }
        .col_w1 {
          width: 414px;
        }
        .col:first-child {
          border-left: none;
        }
      }
    }
    .table_part {
      // margin-top: 8px;
      padding: 12px;
      font-size: @COOMSIZE;
      background: #f6f6f6;
      color: #3a3a3a;
      box-sizing: border-box;
      .chart_container {
        margin-bottom: 10px;
        height: 240px;
        background-color: #fff;
      }
    }
  }
  .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;
  }
  .mask {
    width: 100vw;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.6);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 24px;
    z-index: 9999;
    .mask_tip {
      font-size: 14px;
      color: #fff;
    }
    .mask_num {
      font-size: 40px;
      color: #fff;
    }
  }
}
</style>
