<template>
  <div class="shiyan-page BaseApp-page">
    <main class="BaseApp-page-main">
      <div class="BaseMsg-edit content">
        <div class="shiyan-article-title">
          <div class="shiyan-article-title__icon"></div>
          样品信息
            <el-icon @click="goEdit"><Edit /></el-icon>
        </div>
        <vxe-select
          disabledComponents
          v-model="formData.sample_id"
          class="BaseApp-select"
          @change="changeExperiment"
          >
          <vxe-option
            v-for="item in sampleList"
            :key="item.sample_id"
            :value="item.sample_id"
            :label="item.battery_name"></vxe-option>
        </vxe-select>
        <div class="selectAll-btn">
          <van-checkbox
            v-model="isCheckAll"
            @change="checkAllChange"
            shape="square"
          >
            选择全部频道
          </van-checkbox>
        </div>

      </div>
      <div class="ConfigMsg-edit content">
   
        <div class="shiyan-article-item">
            <div class="shiyan-article-item__label">设置温度</div>
            <div class="shiyan-article-item__value">
              <CommonInput v-model="formData.test_temp" inputUnit="℃" size="small"></CommonInput>
            </div>
          </div>
          <div class="shiyan-article-item">
            <div class="shiyan-article-item__label">电池质量</div>
            <div class="shiyan-article-item__value">
              <CommonInput v-model="formData.weight" size="small" inputUnit="kg"></CommonInput>
            </div>
          </div>
          <div class="shiyan-article-item">
            <div class="shiyan-article-item__label">静置时间</div>
            <div class="shiyan-article-item__value">
              <CommonInput v-model="formData.standing_time" size="small" inputUnit="min"></CommonInput>
            </div>
          </div>
          <div class="shiyan-article-item">
            <div class="shiyan-article-item__label">暴露时间</div>
            <div class="shiyan-article-item__value">
              <CommonInput v-model="formData.expose_time" size="small" inputUnit="min"></CommonInput>
            </div>
          </div>
          <div class="shiyan-article-item">
            <div class="shiyan-article-item__label">结束时间</div>
            <div class="shiyan-article-item__value">
              <CommonInput v-model="formData.end_time" size="small" inputUnit="min"></CommonInput>
            </div>
          </div> <div class="shiyan-article-item">
            <!-- <div class="shiyan-article-item__label">短路参数</div>
            <div class="shiyan-article-item__value">
              <CommonInput v-model="formData.specimen_model" size="medium" inputUnit="A"></CommonInput>
            </div> -->
          </div>
      </div>
      <div class="Select-box content">
        <van-checkbox-group v-model="checkedResult" @change="checkedResultChange">

        
        <template v-for=" (item,index) in list" :key="item">
          <div class="shiyan-article-item content">
            <div class="title">
             <div class="state" v-if="item.status != 0" :class="{'active':item.status!=0}">
              试验中
             </div>
             <div class="state" v-else>
              空闲
             </div>
              {{ index + 1}}
              <van-checkbox  :key="item" :name="item"  shape="square" :disabled="item.status != 0">
              </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">
              合闸
            </div> -->
          </div>
        </template>
      </van-checkbox-group>
      </div>
       
      <!-- <div></div> -->
    </main>
    <footer class="BaseApp-page-footer">
      <div class="BaseApp-btn" @click="goBack">返回</div>
      <div style="display: flex;">
        <div class="BaseApp-btn BaseApp-btn--primary" @click="sendMsg('DOOR',1)">开门</div>
        <div class="BaseApp-btn BaseApp-btn--primary" @click="goNext">启动</div>
      </div>

    </footer>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, onMounted, nextTick ,onUnmounted,watch} from 'vue';
import { useRouter } from 'vue-router';
import { notify } from '../../utils/message.js';
import { websocketStore } from '@/store/webSocketStore.js';

import { startExperimentApi, getAllSpecimen,getChannelList,updateDoorApi
  ,sendMsgApi
} from '../../api/equipment.js';
const router = useRouter();
let userInfo = JSON.parse(sessionStorage.getItem('userInfo') as string);
let socket = websocketStore();

onMounted(() => {
  socket && socket.close({ isActiveClose: true });
  socket.init({ experiment_type: '4', isActiveClose: false });
})
onUnmounted(() => {
  if (socket) {
    socket.close({ isActiveClose: true });
  }
});
let sampleList = ref([])
const getAllSpecimenMet = async () =>{
  let res = await getAllSpecimen();
  console.log('res', res);
  sampleList.value = res.data.data
  
}
getAllSpecimenMet()

let currentExperiment = ref({})
const changeExperiment = (e) =>{
  currentExperiment.value =  sampleList.value.find(item => item.specimen_name == e.value)
}
let list = ref(new Array(5).fill({}).map((_,index)=>{
  return{
    name: `通道${index+1}`,
    'index':index+1
  }
 }));

let isCheckAll = ref(false);
const checkedResult = ref([])
const checkAllChange = (val: boolean) => {
  val ?
  list.value.forEach(item => {
    if(item.status ==0){
      checkedResult.value.push(item)
    }
  }): checkedResult.value =[]
  console.log('checkedResult', checkedResult.value)
}

const checkedResultChange = (value: string[]) => {
  const checkedCount = value.length
  isCheckAll.value = checkedCount === list.value.length
}
const goEdit = () => {
  router.push({
    name: 'msgEdit',
    query: {
      ...currentExperiment.value,
    }
  })
}
let formData = reactive<any>({
  experiment_id: '',
  user_id:'',
  user_name:'',
  sample_id:'',
  test_temp:'',
  temp_tag:'1',
  weight:'',
  standing_time:'',
  expose_time:'',
  end_time:"",
  channel_list:[],
});



const goBack = () => {
  router.go(-1);
};

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 goNext = async () => {
  console.log('formData', formData,currentExperiment,checkedResult.value);

  formData.channel_list = checkedResult.value.map(item => {
    console.log(item,item.index,)
    return item.index
  });
  console.log(
    checkedResult.value.map(item => {
    console.log(item,item.index)
    return item.index
  }),formData
  )
  // 必填校验
  if (!formData.sample_id) {
    return notify('请选择样品信息！');
  }
  if (!formData.weight) {
    return notify('请填写电池重量！');
  }
  if (!formData.standing_time) {
    return notify('请填写静置时间！');
  }
  if (!formData.test_temp) {
    return notify('请填写设置温度！');
  }
  if (!formData.expose_time) {
    return notify('请填写暴露时间！');
  }
  if (!formData.end_time) {
    return notify('请填写结束时间！');
  }
  formData.test_temp = parseFloat(formData.test_temp);

  let res = await startExperimentApi({items:formData} );
  let { data, desc ,code} = res.data;
  console.log('res', res);
  if (code !== 200) {
    notify(desc, 'danger');
    return;
  } else {
    notify(desc, 'success');
  }
  router.push({
    path: '/experiment/secondStep',
    query: {
      arr:data.experiment_id_list
    }
  });
};
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);
  }
};
let listMap = 
  {
    1:'a',
    2:'b',
    3:'c',
    4:'d',
    5:'e',
  }
watch(
  () => socket.serviceMsg,
  async (newVal) => {
    list.value.forEach(item =>{
      for (let key in newVal){
       if(key.includes(listMap[item.index])) {
        if(key.includes('electric')){
          item['electric'] = newVal[key]
        }
        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]
        }
        if(key.includes('voltage')){
          item['voltage'] = newVal[key]
        }
       }
      }
    })
  })
</script>

<style lang="less" scoped>
.shiyan-page {
  font-size: 20px;
  color: #666666;
  .BaseApp-page-main {
    overflow: hidden;
    display: grid;
    grid-template-columns: 1.5fr 3fr ;
    grid-template-rows: 1.5fr 2fr;
    gap:12px; 
    .shiyan-article-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      font-weight: bold;
      font-size: 24px;
      color: #3a3a3a;
      display: flex;
      align-items: center;
      position: relative;
      .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;
      }
    }
    .content{
      border-radius: 12px;
      border: 1px solid #e4e4e4;
      box-shadow: 1px 1px 1px 1px #cccccc9c;
      padding: 15px;
      .el-icon{
        font-size: 24px;
        color: #208BE9;
        position: absolute;
        right: 0px;
      }
      .selectAll-btn{
        width: 95%;
        height: 60px;
        background: white;
        border-radius: 6px;
        border: 1px solid #cccccc9c;
        display: flex;
        justify-content: center;
        background-image: linear-gradient(to bottom,white,#e4e6eb);
      }
    }
    .content:first-child{
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    .content:last-child{
      grid-area: 2 / 1 / 3 / 3;
    }
    .ConfigMsg-edit{
      display: grid;
      grid-template-columns: repeat(3,1fr);
    }
    .Select-box{
      display: flex;

      .van-checkbox-group{
        display: flex;
        gap: 20px;
        width: 100%;
        overflow: auto;
      }
      .content:first-child{
       justify-content: unset; 
      }
      .shiyan-article-item{
        width: 18.5%;
        flex-shrink: 0;
        .title{
          font-size: 28px;
          color:black;
          font-weight: bold;
          display: flex;
          justify-content: space-between;
          .state{
            background: #0084FF;
            color:white;
            font-size: 16px;
            font-weight: 500;
            line-height: 30px;
            height: 30px;
            padding: 0px 10px;
            position: relative;
            left: -15px;
            top:-15px
          }
          .active{
            background: red;
          }
          .van-checkbox{
            top: -10px;
            position: relative;
          }
        }
        .item{
          display: flex;
          justify-content: space-between;
          font-size: 16px;
          margin-bottom: 15px;
        }
        .operation{
          display: flex;
          justify-content: space-around;
          
        }
      }
    }
  }
}
.input-unit{
  margin-left: -80px;
  z-index: 999;
  color: darkgray;
}
</style>
