<script lang="ts" setup>
import { getSelfFinish } from 'apis/self'
import { ElMessageBox } from 'element-plus'
import { socket } from 'libs/socket'
import { useHomeStore } from 'stores/homeStore'
import { useSystemStore } from 'stores/systemStore'
import { onMounted, ref } from 'vue'

const emits = defineEmits(['close'])
const homeStore = useHomeStore()
const systemStore = useSystemStore()

const checkMap = ref(new Map([
  ['zOrigin', { status: '', ignoreKey: 'zOriginIsIgnore', name: 'Z轴回原点', params: { commandId: '', command: `check_z_origin`, params: {} } }],
  ['xyOrigin', { status: '', ignoreKey: 'xyOriginIsIgnore', name: '机械臂回原点', params: { commandId: '', command: `check_xy_origin`, params: {} } }],
  ['titrationOrigin', { status: '', ignoreKey: 'titrationOriginIsIgnore', name: '滴定电机回原点', params: { commandId: '', command: `check_titration_motor_origin`, params: {} } }],
  ['shakeOrigin', { status: '', ignoreKey: 'shakeOriginIsIgnore', name: '摇匀电机回原点', params: { commandId: '', command: `check_shake_motor_origin`, params: {} } }],
  ['stirOrigin', { status: '', ignoreKey: 'stirOriginIsIgnore', name: '磁子投放电机回原点', params: { commandId: '', command: `check_stir_motor_origin`, params: {} } }],
]))

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

onMounted(async () => {
  socket.init(receiveMessage1, 'cmd_debug')
  socket.init(receiveMessage2, 'cmd_response')
  socket.init(receiveMessageSelfMove, 'self_move_test')
  await ElMessageBox.confirm(
    '设备转运机械臂、滴定电机、摇匀电机、磁子投放电机，请确认机械臂行进路径无杂物',
    '提示',
    {
      confirmButtonText: '确认',
      showClose: false,
      showCancelButton: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning',
      customClass: 'init-message',
    },
  )
  const keys = [...checkMap.value.keys()]
  for (let i = 0; i < keys.length; i++) {
    checkList.value.push(checkMap.value.get(keys[i]))
  }
})

let currentCommandId = ''

const receiveMessage1 = (data: Socket.cmdData) => {
  data.commandId === currentCommandId && systemStore.pushSystemList(data)
}
const receiveMessage2 = (data: Socket.cmdData) => {
  data.commandId === currentCommandId && systemStore.pushSystemList(data)
  const item = checkList.value.find(item => item.params.commandId === data.commandId)
  if (item && data.commandId === item.params.commandId && ['success', 'error'].includes(data.status)) {
    item.status = data.status
  }
}

const commandHandle = async (data: any) => {
  data.params.commandId = currentCommandId = Date.now().toString()
  await homeStore.sendControl(data!.params)
}

const onConfirm = async () => {
  await getSelfFinish(true)
  emits('close')
}

const percentage = ref(0)

const checkHandle = async () => {
  activeStep.value = 1
  await ElMessageBox.confirm(
    '设备即将开始自检',
    '提示',
    {
      confirmButtonText: '确认',
      showClose: false,
      showCancelButton: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning',
      customClass: 'init-message',
    },
  )
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'check_move_test',
    params: {},
  }
  await homeStore.sendControl(params)
}

const checkTextList = ref<{ title: string, type: 'success' | 'error' }[]>([])

const selfAgain = ref(true)
const receiveMessageSelfMove = (data: any) => {
  checkTextList.value.push(data)
  percentage.value = data.schedule
  if (data.type === 'error') {
    selfAgain.value = true
  }
}
const activeStep = ref(0)

const checkAgain = async () => {
  selfAgain.value = false
  checkTextList.value = []
  percentage.value = 0
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'check_move_test',
    params: {},
  }
  await homeStore.sendControl(params)
  selfAgain.value = true
}
</script>

<template>
  <FtDialog visible title="设备初始化" width="60%">
    <!--    <el-steps style="max-width: 600px" :active="activeStep" finish-status="success">
      <el-step title="初始化" />
      <el-step title="自检" />
      <el-step title="设备状态" />
    </el-steps> -->
    <div v-if="activeStep === 0" class="check-main">
      <div v-for="item in checkList" :key="item.name" class="check-item">
        <el-tag>{{ item.name }}</el-tag>
        <el-icon v-if="item.status === 'success'" color="#26D574">
          <CircleCheckFilled />
        </el-icon>
        <el-icon v-else-if="item.status === 'error'" color="#FE0A0A">
          <CircleCloseFilled />
        </el-icon>
        <el-icon v-else-if="item.status === ''" class="el-icon--loading">
          <Loading />
        </el-icon>
        <el-icon v-else-if="item.status === 'ignore'">
          <More />
        </el-icon>
        <ft-button v-if="!['ignore', 'success'].includes(item.status)" type="primary" size="small" :click-handle="() => commandHandle(item)">
          回原点
        </ft-button>
        <!--        <ft-button v-if="!['ignore', 'success'].includes(item.status) && item.name === '门电机回原点'" size="small" type="primary" :click-handle="() => ignore(item)">
          忽略
        </ft-button>
        <ft-button v-if="item.status === 'ignore' && item.name === '门电机回原点'" size="small" type="danger" :click-handle="() => ignoreFalse(item)">
          取消忽略
        </ft-button> -->
      </div>
    </div>
    <div v-if="activeStep === 1" class="check-box">
      <div class="progress-box">
        <p>自检进度: </p>
        <el-progress
          :stroke-width="20"
          :percentage="percentage"
        />
      </div>
      <ul>
        <li v-for="(item, index) in checkTextList" :key="index">
          <span :style="{ color: item.type === 'success' ? '#14A656' : '#DF1515' }">{{ item.title }}</span>
        </li>
      </ul>
    </div>

    <template #footer>
      <div style="height: 40px">
        <FtButton v-if="activeStep === 0 && checkList.every(item => ['success', 'ignore'].includes(item.status))" type="primary" :click-handle="checkHandle">
          下一步
        </FtButton>
        <FtButton v-if="activeStep === 1 && selfAgain" type="primary" :click-handle="checkAgain">
          重新自检
        </FtButton>
        <FtButton v-if="activeStep === 1" :click-handle="onConfirm">
          关闭
        </FtButton>
      </div>
    </template>
  </FtDialog>
</template>

<style scoped>
.check-box {
  height: 30vh;
  ul {
    li {
      margin: 3px 0;
    }
  }
}
.progress-box {
  width: 100%;
  height: 40px;
  display: flex;
  align-items: center;
  p {
    margin-right: 10px;
  }
  span {
    margin-left: 10px;
  }
  .el-progress {
    width: 80%;
  }
}
.check-main{
  height: 25vh;
  overflow: auto;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  margin-top: 20px;
}

.check-item {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10px;
  .el-tag {
    width: 50%;
  }
  .el-icon {
    margin: 0 10px;
    font-size: 18px;
  }
}

.check-status{
  display: grid;
  grid-template-columns: 2fr 1fr 1fr;
  margin-top: 5px;
  height: 30px;
}
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.el-icon.el-icon--loading {
  animation: spin 1s linear infinite;
}
.ft-button {
  width:120px
}
</style>
