<script setup lang="ts">
import { 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 { nextTick, onMounted, ref } 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 () => {
  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)
  closeVisible.value = false

  socket.init(receiveMessage, 'cmd_response')
})

const receiveMessage = (data: any) => {
  if (data.cmdId === cmdId && data.status === 'success') {
    for (let i = 0; i < checkList.value.length; i++) {
      checkList.value[i].result = 'padding'
      setTimeout(() => {
        checkList.value[i].result = 'success'
      }, 500)
    }
    buttonRef.value.setLoading(false)
    closeVisible.value = true
  }
}

const cancel = () => {
  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 checkList = ref<any>([])
const buttonRef = ref()
const buttonCloseRef = 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) // 修改为随机数延时
  })
}
</script>

<template>
  <FtDialog visible title="自检" width="40%" @ok="okHandle" @cancel="cancel">
    <div v-for="item 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>
    </div>
    <template #footer>
      <ft-button v-if="closeVisible" ref="buttonCloseRef" @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;
  .el-tag {
    margin: 0 20px 10px 0;
    width: 100%;
  }
}

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

.el-icon.el-icon--loading {
  animation: spin 1s linear infinite; // 确保 Loading 图标应用 spin 动画
}
</style>
