<template>
  <el-dialog :title="dialogTitle" :model-value="dialogVisible" :before-close="beforeClose" @close="handleClose" width="1200px" height="1000px"
             draggable>

    <div class="steps-container">
      <el-steps class="test-head-steps" simple :active="stepsActiveIndex-1" process-status="finish" finish-status="success">
        <el-step v-if="preTestSelected" title="预检测" :icon="stepsActive === 1? SuccessFilled :Edit" @click="handleStepClick(1)"/>
        <el-step v-if="timeTestSelected" title="守时检测" :icon="stepsActive === 2? SuccessFilled :UploadFilled" @click="handleStepClick(2)"/>
        <el-step v-if="channelsTestSelected" title="系数校准" :icon="stepsActive === 3? SuccessFilled :Odometer" @click="handleStepClick(3)"/>
        <el-step v-if="testSelected" title="正式检测" :icon="stepsActive === 4? SuccessFilled :Coin" @click="handleStepClick(4)"/>
        <el-step title="检测完成" :icon="stepsActiveIndex > stepsTotalNum ? SuccessFilled :Key"/>
      </el-steps>
    </div>

    <preTest v-if="showComponent" v-show="preTestSelected && stepsActiveView==1" ref="preTestRef" v-model:testStatus="preTestStatus" :webMsgSend="webMsgSend"/>
    <timeTest v-if="showComponent" v-show="timeTestSelected && stepsActiveView==2" v-model:testStatus="timeTestStatus"/>
    <!--     <channelsTest v-if="stepsActiveIndex === 3" v-model:testStatus="channelsTestStatus"></channelsTest>-->
    <factorTest v-if="showComponent" v-show="channelsTestSelected && stepsActiveView==3" v-model:testStatus="channelsTestStatus"/>
    <test v-if="showComponent" v-show="testSelected && stepsActiveView==4" v-model:testStatus="TestStatus" :webMsgSend="webMsgSend"
          @update:webMsgSend="webMsgSend=$event" @sendPause="sendPause" @sendResume="sendResume" @sendReCheck="sendReCheck"/>

    <template #footer>
      <div>
        <el-button type="primary" :icon="DArrowRight" v-if="stepsActiveIndex < stepsTotalNum && ActiveStatue != 'success'" @click="nextStep">跳过</el-button>
        <el-button type="primary" :icon="VideoPlay" v-if="ActiveStatue === 'waiting'" @click="handleSubmit" :disabled="btnState">开始检测</el-button>
        <el-button type="primary" v-if="ActiveStatue === 'process'" @click="handleSubmit" disabled>
          <el-icon class="loading-box" style="color: #fff;margin-right: 8px;">
            <component :is="Refresh"/>
          </el-icon>
          检测中
        </el-button>
        <el-button type="warning" :icon="VideoPlay" v-if="TestStatus === 'paused'" @click="handleSubmit">继续检测</el-button>
        <el-button type="primary" :icon="RefreshLeft" v-if="TestStatus === 'test_recheck'" @click="handleSubmit">重新检测</el-button>
        <el-button type="primary" v-if="TestStatus === 'test_init'" disabled>
          <el-icon class="loading-box" style="color: #fff;margin-right: 8px;">
            <component :is="Refresh"/>
          </el-icon>
          初始化中
        </el-button>
        <el-button type="warning" v-if="TestStatus === 'paused_ing'" disabled>
          <el-icon class="loading-box" style="color: #fff;margin-right: 8px;">
            <component :is="Refresh"/>
          </el-icon>
          暂停中
        </el-button>
        <el-button :type="ActiveStatue==='success'?'primary':'danger'" :icon="Right"
                   v-if="ActiveStatue === 'success'||ActiveStatue==='error'||ActiveStatue==='test_init_fail'||ActiveStatue==='connect_timeout'||ActiveStatue==='pause_timeout'"
                   @click="nextStep">
          {{ nextStepText }}
        </el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script lang="tsx" setup name="testPopup">
import {reactive, ref, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus'
import {Coin, DArrowRight, Edit, Key, Odometer, Refresh, RefreshLeft, Right, SuccessFilled, UploadFilled, VideoPlay} from '@element-plus/icons-vue'
import preTest from './preTest.vue'
import timeTest from './timeTest.vue'
import factorTest from './factorTest.vue'
import test from './test.vue'
import {Device} from '@/api/device/interface/device';
import socketClient from '@/utils/webSocketClient';
import {useCheckStore} from "@/stores/modules/check";
import {pauseTest, startPreTest} from '@/api/socket/socket'

const btnState = ref(false)
const checkStore = useCheckStore();
const nextStepText = ref('下一步');
const dialogVisible = ref(false)

const stepsTotalNum = ref(-1);//步骤总数
const stepsActiveIndex = ref(1); //当前正在执行的步骤索引
const stepsActiveView = ref(-1); //当前正在执行的步骤在（预处理、守时校验、系数校准、正式检测）中的排序，仅用于页面显示
const stepsActive = ref(-1); //当前正在执行的步骤在（预处理、守时校验、系数校准、正式检测）中的排序，实际记录步骤的状态
const ActiveStatue = ref('waiting');//当前步骤状态
const preTestStatus = ref('waiting');//预检测执行状态
const timeTestStatus = ref('waiting');//守时校验执行状态
const channelsTestStatus = ref('waiting');//通道系数校准执行状态
const TestStatus = ref('waiting');//正式检测执行状态
const webMsgSend = ref();//webSocket推送的数据

const dialogTitle = ref('')
const showComponent = ref(true)
const preTestRef = ref(null)

const dataSocket = reactive({
  socketServe: socketClient.Instance,
});

// 勾选的检测内容
const preTestSelected = ref(false)
const timeTestSelected = ref(false)
const channelsTestSelected = ref(false)
const testSelected = ref(false)

const initOperate = () => {
  showComponent.value = true
  // 初始化勾选的检测内容
  preTestSelected.value = checkStore.selectTestItems.preTest
  timeTestSelected.value = checkStore.selectTestItems.timeTest
  channelsTestSelected.value = checkStore.selectTestItems.channelsTest
  testSelected.value = checkStore.selectTestItems.test

  let count = 0
  for (let key in checkStore.selectTestItems) {
    if (checkStore.selectTestItems[key]) {
      count++
    }
  }
  stepsTotalNum.value = count + 1

  if (preTestSelected.value) {
    stepsActiveView.value = 1
    stepsActive.value = 1
    return
  }
  if (timeTestSelected.value) {
    stepsActiveView.value = 2
    stepsActive.value = 2
    return
  }
  if (channelsTestSelected.value) {
    stepsActiveView.value = 3
    stepsActive.value = 3
    return
  }
  if (testSelected.value) {
    stepsActiveView.value = 4
    stepsActive.value = 4
    return
  }
}

const open = (selection: Device.ResPqDev[], title: string) => {
  initOperate()

  // const checkStates = selection.map(item => item.checkState);
  //
  // const allCheckStatesEqual = new Set(checkStates).size <= 1;
  //
  // debugger
  // if (!allCheckStatesEqual) {
  //   ElMessageBox.confirm('所勾选设备检测状态不一致，请重新选择', '提示',
  //       {
  //         confirmButtonText: '确定',
  //         cancelButtonText: '取消',
  //         type: 'warning',
  //       }
  //   )
  //   return
  // }

  dialogTitle.value = title;
  dialogVisible.value = true;

  if (preTestRef.value) {
    preTestRef.value.initializeParameters();
  }

  ActiveStatue.value = 'waiting'
  preTestStatus.value = 'waiting'
  timeTestStatus.value = 'waiting'
  channelsTestStatus.value = 'waiting'
  TestStatus.value = 'waiting'

  //开始创建webSocket客户端

  socketClient.Instance.connect();
  dataSocket.socketServe = socketClient.Instance;
  dataSocket.socketServe.registerCallBack('aaa', (res) => {
    // 处理来自服务器的消息
    // console.log('Received message:', res);
    // 根据需要在这里添加更多的处理逻辑
    if (res.code === 20000) {
      //ElMessage.error(message.message)
      // loading.close()
    } else {
      webMsgSend.value = res
    }


  });
}

// let loading;
const handleSubmit = () => {
  console.log('=============', stepsActiveIndex.value)

  let deviceIds = checkStore.devices.map((item) => item.deviceId)
  let planId = checkStore.plan.id

  if (!dataSocket.socketServe.connected) {
    ElMessage.error('webSocket连接中断！')
    return
  }
  switch (stepsActive.value) {
    case 1:
      startPreTest({
        userPageId: "cdf",
        devIds: deviceIds,
        planId: planId,
        operateType: '1' // '1'为预检测、‘2‘为正式检测
      }).then(res => {
        if (res.code === 'A001014') {
          ElMessageBox.alert('装置配置异常', '检测失败', {
            confirmButtonText: '确定',
            type: 'error',
          })
          preTestStatus.value = 'error'
        }
      })
      preTestStatus.value = 'start'
      break;
    case 2:
      timeTestStatus.value = 'start'
      break;
    case 3:
      channelsTestStatus.value = 'start'
      break;
    case 4:
      if (TestStatus.value == "waiting") {
        //   startPreTest({
        //     userPageId: "cdf",
        //     devIds: deviceIds,
        //     planId: planId,
        //     operateType: '2' // '1'为预检测、‘2‘为正式检测
        //   }).then(res => {
        //     console.log(res)
        //     if (res.code === 'A001014') {
        //       ElMessageBox.alert('装置配置异常', '初始化失败', {
        //         confirmButtonText: '确定',
        //         type: 'error',
        //       })
        //       TestStatus.value = 'test_init_fail'
        //     }
        //   })
        TestStatus.value = 'start'
      } else if (TestStatus.value == 'paused') {
        // 发送继续指令
        sendResume()
      } else if (TestStatus.value == 'test_recheck') {
        // 发送重新检测指令
        sendReCheck()
      } else if (TestStatus.value == 'success') {
        handleClose()
      }
      break;
    default:
      break;
  }
};

const emit = defineEmits<{
  (e: 'quitClicked'): void;
}>();

watch(preTestStatus, function (newValue, oldValue) {
  console.log(newValue, oldValue);

  ActiveStatue.value = newValue
})
watch(timeTestStatus, function (newValue, oldValue) {
  console.log(newValue, oldValue);

  ActiveStatue.value = newValue
})
watch(channelsTestStatus, function (newValue, oldValue) {
  console.log(newValue, oldValue);

  ActiveStatue.value = newValue
})
watch(TestStatus, function (newValue, oldValue) {
  console.log(newValue, oldValue);

  ActiveStatue.value = newValue
})

watch(ActiveStatue, function (newValue, oldValue) {
  if (newValue === 'error' && stepsActive.value === 1) {
    stepsActiveIndex.value = stepsTotalNum.value + 2
    nextStepText.value = '检测失败'
  }
  if (newValue === 'success' && stepsActive.value === 4) {
    stepsActiveIndex.value += 2
    nextStepText.value = '检测完成'
  }
  if (newValue === 'test_init_fail' && stepsActive.value === 4) {
    stepsActiveIndex.value += 2
    nextStepText.value = '初始化失败'
  }
  if (newValue === 'connect_timeout' && stepsActive.value === 4) {
    stepsActiveIndex.value += 2
    nextStepText.value = '连接超时'
  }
  if (newValue === 'pause_timeout' && stepsActive.value === 4) {
    stepsActiveIndex.value += 2
    nextStepText.value = '结束测试'
  }
})

const sendPause = () => {
  console.log('发起暂停请求')

  TestStatus.value = 'paused_ing'
  pauseTest()
  setTimeout(() => {
    Object.assign(webMsgSend.value, {
      requestId: 'preStopTest',
      operateCode: 'stop'
    })
  }, 5000)
}
const sendResume = () => {
  console.log('发起继续检测请求')

  // resumeTest({
  //   userPageId: "cdf",
  //   devIds: checkStore.devices.map((item) => item.deviceId),
  //   planId: checkStore.plan.id,
  //   operateType: '2' // '1'为预检测、‘2‘为正式检测
  // }).then(res => {
  //   Object.assign(webMsgSend.value, {
  //     requestId: 'Resume_Success'
  //   })
  // })
  Object.assign(webMsgSend.value, {
    requestId: 'Resume_Success'
  })
}

const sendReCheck = () => {
  console.log('发送重新检测指令')
  // startPreTest({
  //   userPageId: "cdf",
  //   devIds: checkStore.devices.map((item) => item.deviceId),
  //   planId: checkStore.plan.id,
  //   operateType: '2' // 0:'系数校验'，'1'为预检测、‘2‘为正式检测
  // }).then(res => {
  //   console.log(res)
  //   if (res.code === 'A001014') {
  //     ElMessageBox.alert('装置配置异常', '初始化失败', {
  //       confirmButtonText: '确定',
  //       type: 'error',
  //     })
  //     TestStatus.value = 'test_init_fail'
  //   }
  // })
  TestStatus.value = 'start'
}

const nextStep = () => {
  if (stepsActiveIndex.value == stepsTotalNum.value + 1 || ActiveStatue.value === 'error') {
    handleClose()
    return
  }
  if (ActiveStatue.value != 'error') {
    ActiveStatue.value = 'waiting'
    let tempStep = stepsActiveIndex.value
    let idx = 1
    stepsActiveIndex.value++
    for (let selectTestItemsKey in checkStore.selectTestItems) {
      if (tempStep == 0 && checkStore.selectTestItems[selectTestItemsKey]) {
        stepsActiveView.value = idx
        stepsActive.value = idx
        return
      }
      if (checkStore.selectTestItems[selectTestItemsKey] && tempStep != 0) {
        tempStep--
      }
      idx++
    }
  }

  // if (stepsActiveIndex.value < stepsTotalNum.value && ActiveStatue.value != 'error') {
  //   stepsActiveIndex.value++
  //   if (!checkStore.selectTestItems.timeTest) { // 不具备守时检测
  //     stepsActiveIndex.value++
  //   }
  //
  //   ActiveStatue.value = 'waiting'
  // } else if (stepsActiveIndex.value === stepsTotalNum.value || ActiveStatue.value === 'error') {
  //   //emit('update:visible', false); // 关闭对话框
  //   clearData()
  //   dialogVisible.value = false;
  // }
}

const handleStepClick = (step: number) => {
  if (step > stepsActive.value) {
    return
  } else {
    stepsActiveView.value = step
  }
}

function clearData() {
  stepsTotalNum.value = -1
  stepsActiveIndex.value = 1
  stepsActiveView.value = -1
  preTestStatus.value = "waiting"
  timeTestStatus.value = "waiting"
  channelsTestStatus.value = "waiting"
  TestStatus.value = "waiting"
  ActiveStatue.value = "waiting"
  nextStepText.value = "下一步"
}

const beforeClose = (done: () => void) => {
  if (stepsActiveIndex.value < stepsTotalNum.value) {
    ElMessageBox.confirm('检测未完成，是否退出当前检测流程?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    ).then(() => {
      handleClose()
    })
  } else {
    handleClose()
  }
}

const handleClose = () => {
  dataSocket.socketServe.closeWs()
  dialogVisible.value = false;
  clearData()
  showComponent.value = false;

  emit('quitClicked'); // 触发事件
}

// 对外映射
defineExpose({open})
</script>

<style scoped lang="scss">

:deep(.dialog-big .el-dialog__body) {
  max-height: 840px !important;
}

.steps-container :deep(.test-head-steps) {
  height: 80px;
  margin-bottom: 10px;
}

.steps-container :deep(.el-step__title) {
  font-size: 20px !important; /* 设置标题字体大小 */
  vertical-align: baseline !important;
  display: inline-block; /* 确保文字和图标在同一行 */
  line-height: 1; /* 调整行高以确保底部对齐 */
}

.steps-container :deep(.el-step__icon-inner) {
  font-size: 18px !important;
  vertical-align: baseline !important;
  display: inline-block; /* 确保文字和图标在同一行 */
  line-height: 1; /* 调整行高以确保底部对齐 */
}

.steps-container :deep(.el-step__icon) {
  font-size: 18px !important;
  vertical-align: baseline !important;
  display: inline-block; /* 确保文字和图标在同一行 */
  line-height: 1; /* 调整行高以确保底部对齐 */
}

.loading-box {
  animation: loading 1.5s linear infinite;
}

@keyframes loading {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// :deep(.test-head-steps){
//     height: 100px;
//     margin-bottom: 20px;
// } 

// .el-step__icon.is-text {
//   border-radius: 50%;
//   border: 4px solid;
//   width: 50px;
//   height: 50px;
//   border-color: inherit;
// }
// .el-step__icon.is-icon {
//   border-radius: 50%;
//   border: 4px solid;
//   width: 50px;
//   height: 50px;
//   border-color: inherit;
// }

// .test-head-steps .el-step__line{
//   height:50px !important;
// }

// .test-head-steps .el-step__icon-inner{
//   width: 40px !important;
//   height:40px !important;
// }

// .test-head-steps .el-step__icon{
//   width: 48px !important;
//   height:48px !important;
//   font-size: 48px !important; /* 调整图标大小 */
//   line-height: 80px !important; /* 使图标居中 */
// }

// :deep(.el-step__title)  {
//   font-size: 24px !important; /* 设置标题字体大小 */
//   margin-top: 10px !important; /* 调整标题与图标的间距 */
// }

// :deep(.el-step__icon-inner) {
//   font-size: 24px !important;
// }
// .test-head-steps .el-step__description {
//   font-size: 20px !important; /* 设置描述字体大小 */
// }

</style>