<template>
  <div class="shiyan-page BaseApp-page">
    <main class="BaseApp-page-main">
      <div class="shiyan-run-wrapper">
        <div class="shiyan-run-left">
          <div class="shiyan-article-title__icon"></div>

          <div class="shiyan-run-left-item__label">进行中的试验:</div>
        </div>
        <div class="shiyan-content">
          <van-checkbox-group v-model="checked">
            <template v-for="(item, index) in list" :key="item">
              <div class="shiyan-article-item content">
                <div class="title">
                  <div class="state">试验中</div>

                  <span>{{ index + 1 }}</span>
                  <van-checkbox :key="item.id" :name="item" shape="square"></van-checkbox>
                </div>
                <div class="">
                  <div class="item">
                    <span class="name">电压：</span>
                    <span class="value">{{ (item.voltage || 0).toFixed(4) }}V</span>
                  </div>
                  <div class="item">
                    <span class="name">电流：</span>
                    <span class="value">{{ (item.electric || 0).toFixed(4) }}A</span>
                  </div>
                  <div class="item">
                    <span class="name">电容容量：</span>
                    <span class="value">{{ (item.electric || 0).toFixed(4) }}A</span>
                  </div>
                  <div class="item">
                    <span class="name">温度：</span>
                    <span class="value">{{ (item.temp || 0).toFixed(2) }}℃</span>
                  </div>

                  <div class="item">
                    <span class="name">开始：</span>
                    <span class="value">{{ item.last_start_time }}</span>
                  </div>
                </div>
                <div class="operation content" @click="openEcharts(item)">打开曲线</div>
              </div>
            </template>
          </van-checkbox-group>
        </div>
      </div>
    </main>
    <footer class="BaseApp-page-footer">
      <div class="btn-group">
        <div class="BaseApp-btn" @click="goBack">返回</div>
      </div>
      <div class="btn-group">
        <div class="BaseApp-btn BaseApp-btn--primary" @click="sendMsg('DOOR',1)">开门</div>

        <div
          class="BaseApp-btn BaseApp-btn--red"
          @click="showCameraMonitor">
          实时视频查看
        </div>
        <div
          class="BaseApp-btn BaseApp-btn--blue"
          :class="{ 'BaseApp-btn--disabled': checked.length != 1 }"
          @click="showCloseExperimentDialog">
          停止
        </div>
      </div>
    </footer>
    <van-dialog
      class="BaseApp-dialog BaseApp-dialog--large"
      closeOnClickOverlay="true"
      v-model:show="echartsDialogVisible"
      :showCancelButton="false"
      @close="closeEcharts"
      :showConfirmButton="false"
      width="90%"
      :title="currentMsg?.base_info?.name">
      <div class="shiyan-run-wrapper_echarts">
        <div class="shiyan-run-left">
          <div class="shiyan-run-left-item__label">试验温度:</div>
          <div class="shiyan-run-left-item__value">
            {{ (chart_data_temp1_list[chart_data_temp1_list.length - 1]).toFixed(2) }}℃
          </div>
          <!-- <div class="shiyan-run-left-item__label">表面温度:</div>
          <div class="shiyan-run-left-item__value">{{ currentMsg?.report_list?.temp1 }}mm</div> -->
          <div class="shiyan-run-left-item__label">电池电压:</div>
          <div class="shiyan-run-left-item__value">{{  (chart_data_voltage_list[chart_data_voltage_list.length - 1]).toFixed(4)}}mV</div>
          <div class="shiyan-run-left-item__label">电池电流:</div>
          <div class="shiyan-run-left-item__value">
            {{  (chart_data_electric_list[chart_data_electric_list.length - 1]).toFixed(4) }}mA
          </div>
        </div>
        <div class="shiyan-run-right">
          <div id="echars_div"></div>
        </div>
      </div>
    </van-dialog>
    <!-- 视频查看 -->
    <CameraMonitorDilaog
      v-if="cameraMonitorDialogConfig.visible"
      :bizId="cameraMonitorDialogConfig.bizId"
      :cameraType="cameraMonitorDialogConfig.cameraType"
      @cancel="cameraMonitorDialogConfig.visible = false"></CameraMonitorDilaog>
    <!-- 实验结束弹窗 -->
    <CloseExperimentDialog
      v-if="closeExperimentDialogVisible"
      @cancel="closeExperimentDialogVisible = false"
      @submit="stoptExperiment"></CloseExperimentDialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { notify } from '../../utils/message.js';
import {
  updateExperimentApi,
  sendMsgApi,
  stopExperimentApi,
  updateRecord,
  getChannelList,
  updateDoorApi,
  experimentOver,
  getChannelInfoApi
} from '../../api/equipment.js';
import * as echarts from 'echarts';
import { windowWidth } from 'vant/lib/utils/dom.js';
import CameraMonitorDilaog from '../../components/CameraMonitorDilaog/index.vue';
import CloseExperimentDialog from './components/CloseExperimentDialog.vue';
import { showConfirmDialog } from 'vant';
import { websocketStore } from '@/store/webSocketStore.js';

let socket = websocketStore();

onMounted(() => {
  socket && socket.close({ isActiveClose: true });
  socket.init({ experiment_type: '4', isActiveClose: false });
});
onUnmounted(() => {
  if (socket) {
    socket.close({ isActiveClose: true });
  }
});

let list = ref(
  new Array(5).fill({}).map((_, index) => {
    return {
      name: `通道${index + 1}`,
      index: index + 1
    };
  })
);
let listMap = {
  1: '_a',
  2: '_b',
  3: '_c',
  4: '_d',
  5: '_e'
};
let updateDate = ref({});
watch(
  () => socket.serviceMsg,
  async (newVal) => {
    updateDate.value = newVal;

    list.value.forEach((item) => {
      let isCurrentIndex = showEchartsMsg.value?.index == item.index
      for (let key in newVal) {
        if (key.includes(listMap[item.index])) {
         
          if (key.includes('fd_capacitor')) {
            item['fd_capacitor'] = newVal[key];
          }
          if (key.includes('status')) {
            item['status'] = newVal[key];
          }
          if (key.includes('temp')) {
            item['temp'] = newVal[key];
            echartsDialogVisible.value&& isCurrentIndex &&(chart_data_temp1_list.value.push(newVal[key]))
          }
          if (key.includes('electric')) {
            item['electric'] = newVal[key];
            echartsDialogVisible.value&& isCurrentIndex &&(chart_data_electric_list.value.push(newVal[key]))

          }
          if (key.includes('voltage')) {
            item['voltage'] = newVal[key];
            if(echartsDialogVisible.value&& isCurrentIndex){
              chart_data_voltage_list.value.push(newVal[key])
              chart_data_time_list.value.push(1)
              nextTick(()=>{
                initChart()
              })
            }

          }
        }
      }
    });
  }
);
let checked = ref([]);

// const getChannelListMth  = async () =>{
//   let res = await getChannelList({status:1});
//   list.value =res.data
//   console.log('res', res);
// }
// getChannelListMth()

const updateDoor = async () => {
  let res = await updateDoorApi({ status: 1 });
  if (res.data.code == 1) {
    notify(res.data.desc);
  } else {
    notify(res.data.desc, 'danger');
  }
  console.log('res', res);
};

const route = useRoute();
const router = useRouter();
let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
// 实验基本信息
let experimentBaseInfo = reactive({
  experiment_id: '',
  user_id: userInfo ? userInfo.user_id : '',
  user_name: userInfo ? userInfo.user_name : '',
  name: '',
  specimen_code: '',
  specimen_height: '',
  specimen_model: '',
  specimen_manufacturer: '',
  pressure_value: '',
  test_speed: '',
  placement_time: '',
  test_temp: '',
  test_type: 1 // 试验类型: 1 挤压 2 针刺
});

let closeExperimentDialogVisible = ref(false); // 结束实验弹窗显示
let cameraMonitorDialogConfig = reactive({
  visible: false,
  cameraType: 'CAMERA_LIVE',
  bizId: ''
});

/** echars 图表相关 */
let chart_div;
let chart_data_time_list = ref([]); // x轴，每分钟
let chart_data_temp1_list = ref([]);
let chart_data_voltage_list = ref([]);
let chart_data_electric_list = ref([]);

/**
 * 加载实验详情
 */
const loadExperimentDetail = async () => {
  // 直接从query那获取
  for (let key in route.query) {
    experimentBaseInfo[key] = route.query[key];
  }
};

/**
 * 结束实验
 */
const stoptExperiment = async ({ reasonIdList }) => {
  closeExperimentDialogVisible.value = false;

  let experimentArrId = route.query.arr
  let currentExperimentId = checked.value.map((item) => item.index)[0]
  let updateParams = {
    date: updateDate.value,
    is_disintegrate: 0,
    is_rupture: 0,
    is_fire: 0,
    id: experimentArrId[currentExperimentId-1]
  };
  reasonIdList.forEach((item) => {
    updateParams[item] = 1;
  });
  let updateRes = await updateRecord(updateParams);
  let resultData = updateRes.data;
  if (resultData.code !== 200) {
    notify(resultData.desc, 'danger');
    return;
  }
  let req = {
    channel_list: [currentExperimentId],
  };

  // 结束实验
  let res = await experimentOver(req);
  let { code, desc, data } = res?.data;
  if (code === 200) {
    notify(desc, 'success');
  } else {
    notify(desc);
  }
};



/**
 * 显示结束实验弹窗
 */
const showCloseExperimentDialog = () => {
  closeExperimentDialogVisible.value = true;
};

const openDoor = async () => {};

const goBack = () => {
  router.go(-1);
};
let echartsDialogVisible = ref(false);
let currentMsg = ref({});
let echartInterval = null;
let showEchartsMsg = ref()
const openEcharts = async (row) => {
  showEchartsMsg.value = row
  chart_data_temp1_list.value = [];
  chart_data_voltage_list.value = [];
  chart_data_electric_list.value = []
  chart_data_time_list.value = []
  echartsDialogVisible.value = true;
  nextTick(() => {
    initChart();

  });
};

const closeEcharts = () => {
  echartInterval && clearInterval(echartInterval);
};
/**
 * 初始化chart
 */
const initChart = () => {
  if (!chart_div) {
    chart_div = echarts.init(document.getElementById('echars_div'));
  }
  console.log('initChart', chart_div);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '15%', // 为左侧y轴留出空间
      right: '13%', // 为右侧y轴留出空间
      top: '15%',
      bottom: '15%'
    },
    legend: {
      data: ['表面温度', '电池电压', '电池电流'],
      icon: 'rect',
      itemWidth: 12,
      itemHeight: 10,
      itemGap: 20,
      top: 20,
      textStyle: {
        fontSize: 18
      }
    },
    xAxis: {
      type: 'category',
      data: chart_data_time_list.value, // 时间
      name: '时间 / min',
      nameLocation: 'middle',
      nameGap: 35,
      splitLine: {
        show: true
      },
      nameTextStyle: {
        fontSize: 16
      }
    },
    yAxis: [
      // 左边Y轴：表面温度和电池电压
      {
        type: 'value',
        name: '温度/℃',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#666666FF',
            width: 1,
            type: 'solid'
          }
        },
        splitLine: {
          show: true
        },
        offset: 80,
        nameRotate: 90,
        nameGap: 30,
        nameLocation: 'middle',
        nameTextStyle: {
          fontSize: 14
        }
      },
      {
        type: 'value',
        name: '电压/mv',
        position: 'left',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#666666FF',
            width: 1,
            type: 'solid'
          }
        },
        splitLine: {
          show: false
        },
        offset: 20,
        nameRotate: 90,
        nameGap: 25,
        nameLocation: 'middle',
        nameTextStyle: {
          fontSize: 14
        }
      },
      // 右边Y轴：电池形变和挤压力值
      {
        type: 'value',
        name: '电流/mA',
        position: 'right',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#666666FF',
            width: 1,
            type: 'solid'
          }
        },
        splitLine: {
          show: false
        },
        offset: 20,
        nameRotate: 90,
        nameGap: 40,
        nameLocation: 'middle',
        nameTextStyle: {
          fontSize: 15
        }
      }
    ],
    series: [
      {
        name: '试验温度',
        type: 'line',
        data: chart_data_temp1_list.value,
        yAxisIndex: 0, // 绑定左边第一个Y轴（表面温度）
        itemStyle: {
          color: '#cf4a4a'
        },
        lineStyle: {
          color: '#cf4a4a'
        },
        symbol: 'none'
      },
      {
        name: '电池电压',
        type: 'line',
        data: chart_data_voltage_list.value,
        yAxisIndex: 1, // 绑定左边第二个Y轴（电池电压）
        itemStyle: {
          color: '#51a8ff'
        },
        lineStyle: {
          color: '#51a8ff'
        },
        symbol: 'none'
      },
      {
        name: '电池电流',
        type: 'line',
        data: chart_data_electric_list.value,
        yAxisIndex: 2, // 绑定右边第一个Y轴（电池形变）
        itemStyle: {
          color: '#00d2d9'
        },
        lineStyle: {
          color: '#00d2d9'
        },
        symbol: 'none'
      }
    ]
  };
  console.log(chart_data_electric_list.value);
  chart_div.setOption(option);
};

function calculateAverage(numbers) {
  // 计算数组中所有数字的总和
  const sum = numbers.reduce((total, num) => total + num, 0);
  // 计算平均值
  const average = sum / numbers.length;
  return Number.parseFloat(average.toFixed(1));
}

onMounted(() => {
  loadExperimentDetail();
});

onUnmounted(() => {});

const sendMsg = async (name,value) => {
  let params  ={
    name:name,
    status:value
  }

  let res = await sendMsgApi(params);
  let { code, desc, data } = res?.data;
  if (code === 200) {
    notify(desc, 'success');
  } else {
    notify(desc);
  }
};

const showCameraMonitor = () => {
  cameraMonitorDialogConfig.visible = true;
  cameraMonitorDialogConfig.bizId = '';
};

</script>

<style lang="less" scoped>
.shiyan-page {
  font-size: 20px;
  color: #666666;
  .BaseApp-page-main {
    overflow: hidden;
  }

  .shiyan-run-wrapper {
    width: 100%;
    height: 100%;
    padding: 0 20px;
    margin-top: 10px;
    background: #f6f6f6;
    .shiyan-run-left {
      display: flex;
      padding-left: 20px;
      padding-top: 20px;
      .shiyan-article-title__icon {
        width: 6px;
        height: 28px;
        margin-right: 25px;
        background: linear-gradient(180deg, #ff7b83 0%, #850006 100%);
        box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.4);
        border-radius: 8px 8px 8px 8px;
      }
      .shiyan-run-left-item__label {
        height: 25px;
        font-size: 20px;
        color: #3a3a3a;
        text-align: left;
        font-style: normal;
        text-transform: none;
      }
    }
    .shiyan-run-right {
      flex: 1;
    }
    /* #echars_div {
      width: 1080px;
      height: 450px;
    } */
  }
  .van-checkbox-group {
    display: flex;
    width: 100%;
    gap: 20px;
    overflow: auto;
    padding: 20px;
  }
  .shiyan-article-item {
    width: 19%;
    flex-shrink: 0;
    .title {
      font-size: 28px;
      color: black;
      font-weight: bold;
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      span {
        margin-right: 20px;
      }
      .state {
        background: red;
        color: white;
        font-size: 16px;
        font-weight: 500;
        line-height: 30px;
        height: 30px;
        padding: 0px 10px;
        position: relative;
        left: -15px;
        top: -15px;
      }
      .active {
        background: #0084ff;
      }
      .van-checkbox {
        top: -10px;
        position: relative;
      }
    }
    .item {
      display: flex;
      justify-content: space-between;
      font-size: 16px;
      margin-bottom: 15px;
      .name {
        white-space: nowrap;
      }
    }
    .operation {
      display: flex;
      justify-content: space-around;
    }
  }

  .content {
    border-radius: 12px;
    border: 1px solid #e4e4e4;
    box-shadow: 1px 1px 1px 1px #cccccc9c;
    padding: 15px;
  }
}
.shiyan-run-wrapper_echarts {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100%;
  padding: 0 20px;
  margin-top: 10px;
  .shiyan-run-left {
    display: flex;
    flex-direction: column;
    width: 180px;
    padding-left: 20px;
    .shiyan-run-left-item__label {
      height: 25px;
      margin-top: 20px;
      font-size: 20px;
      color: #3a3a3a;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
    .shiyan-run-left-item__value {
      height: 20px;
      margin-top: 10px;
      font-weight: bold;
      font-size: 20px;
      color: #51a8ff;
      text-align: left;
      font-style: normal;
      text-transform: none;
    }
  }
  .shiyan-run-right {
    flex: 1;
  }
  #echars_div {
    width: 100%;
    height: 550px;
  }
}
</style>
