<script setup lang="ts">
import { deviceSelfTestFinish, getDeviceSelfTest } from 'apis/system'
import FtDialog from 'components/common/FTDialog/index.vue'
import { FtMessage } from 'libs/message'
import { socket } from 'libs/socket'
import { sendControl } from 'libs/utils'
import { onMounted, ref, watch } from 'vue'

const emits = defineEmits(['ok', 'cancel'])

const okLoading = ref(false)
const okHandle = () => {
  okLoading.value = true

  setTimeout(() => {
    okLoading.value = false
    FtMessage.success('保存成功')
    emits('ok')
  }, 300)
}

const list = ['x轴是否在原点', 'y轴是否在原点', 'z轴是否在原点']
const status = ref<any>({})
onMounted(async () => {
  socket.init(receiveMessage, 'cmd_response')
  await change()
})

const change = async () => {
  let num = 0
  // await nextTick(() => {
  //   buttonCloseRef.value?.setLoading(true)
  // })
  status.value = await getDeviceSelfTest()

  const interval = async () => {
    if (num < list.length) {
      await addTextToCheckList(list[num], num)
      num++
      await interval() // 递归调用 interval 处理下一条数据
    }
  }
  await interval()
  // buttonCloseRef.value?.setLoading(false)
}

const receiveMessage = (data: any) => {
  if (data.status === 'success') {
    for (const cmdIdsKey in cmdIds) {
      if (data.cmdId === cmdIds[cmdIdsKey]) {
        checkList.value[cmdIdsKey].result = 'success'
      }
    }
  }
  if (data.status === 'finish') {
    for (const cmdIdsKey in cmdIds) {
      if (data.cmdId === cmdIds[cmdIdsKey]) {
        toHomeButtonRefs.value[cmdIdsKey].setLoading(false)
      }
    }
  }
}

const cancel = async () => {
  await deviceSelfTestFinish()
  emits('cancel')
}

let cmdId = ''
// const motorXYZOrigin = async () => {
//   buttonRef.value.setLoading(true)
//   cmdId = Date.now().toString()
//   const params = {
//     cmdCode: 'device_self_test',
//     cmdId,
//     params: {},
//   }
//
//   await sendControl(params)
// }

const cmdIds: any = {}

const toHomeButtonRefs = ref()

const toHome = async (index: number) => {
  cmdId = Date.now().toString()
  cmdIds[index] = cmdId
  const params = {
    cmdCode: ['motor_x_to_home', 'motor_y_to_home', 'motor_z_to_home'][index],
    cmdId,
    params: {},
  }
  toHomeButtonRefs.value[index].setLoading(true)
  await sendControl(params)
}

const checkList = ref<any>([])
// const buttonRef = ref()

const closeVisible = ref(true)

const addTextToCheckList = async (text: string, id: number) => {
  // 检查 checkList 中是否存在该 id 的对象，如果不存在则初始化
  if (!checkList.value.some(item => item.id === id)) {
    checkList.value.push({ id, title: '', result: 'padding' })
  }

  let displayedText = ''
  return new Promise<void>((resolve) => {
    const interval = setInterval(() => {
      if (displayedText.length < text.length) {
        displayedText += text[displayedText.length]
        const itemIndex = checkList.value.findIndex(item => item.id === id)
        if (itemIndex !== -1) {
          checkList.value[itemIndex].title = displayedText
        }
      }
      else {
        clearInterval(interval)
        // 文字显示完毕后，设置 result 为 'success' 或 'failed' 以显示成功或失败图标
        const itemIndex = checkList.value.findIndex(item => item.id === id)
        if (itemIndex !== -1) {
          setTimeout(() => {
            checkList.value[itemIndex].result = status.value[['xAxisAtOrigin', 'yAxisAtOrigin', 'zAxisAtOrigin'][itemIndex]] ? 'success' : 'failed'
            resolve() // 解析 Promise，表示当前数据已完全展示
          }, Math.random() * 200) // 修改为随机数延时
        }
      }
    }, Math.random() * 100) // 修改为随机数延时
  })
}

watch(() => checkList.value, () => {
  if (checkList.value.every(item => item.result === 'success')) {
    closeVisible.value = false
  }
}, { deep: true })
</script>

<template>
  <FtDialog visible title="自检" width="40%" :ok-handle="okHandle" @cancel="cancel">
    <div v-for="(item, index) in checkList" :key="item.id" class="mask-box">
      <el-tag> {{ item.title }}</el-tag>
      <el-icon v-show="item.result === 'success'" color="green">
        <SuccessFilled />
      </el-icon>
      <el-icon v-show="item.result === 'failed'" color="red">
        <CircleCloseFilled />
      </el-icon>
      <el-icon v-show="item.result === 'padding'" color="gray" class="el-icon--loading">
        <Loading />
      </el-icon>
      <ft-button ref="toHomeButtonRefs" class="check-button" type="primary" :disabled="item.result === 'success'" @click="() => toHome(index)">
        回原点
      </ft-button>
    </div>
    <template #footer>
      <ft-button :disabled="closeVisible" @click="cancel">
        关闭
      </ft-button>
      <!--      <ft-button v-else ref="buttonRef" type="primary" @click="motorXYZOrigin"> -->
      <!--        回原点 -->
      <!--      </ft-button> -->
    </template>
  </FtDialog>
</template>

<style scoped lang="scss">
.mask-box {
  display: flex;
  font-size: 35px;
  align-items: center;
  margin-bottom:  40px;
  .el-tag {
    margin-right: 20px;
    width: 100%;
  }
}

// 添加旋转动画
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.el-icon.el-icon--loading {
  animation: spin 1s linear infinite; // 确保 Loading 图标应用 spin 动画
}
:deep(.el-tag) {
  padding:  30px 0;
}
:deep(.check-button) {
  margin-left: 10px;
  .my-button {
    width: 230px;
  }

}
</style>
