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

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

const checkMap = ref(new Map([
  ['gantryZOrigin', { status: '', name: '龙门架z轴回原点', params: { commandId: '', command: `gantry_z_origin`, params: {} } }],
  ['gantryXOrigin', { status: '', name: '龙门架x轴回原点', params: { commandId: '', command: `gantry_x_origin`, params: {} } }],
  ['gantryYOrigin', { status: '', name: '龙门架y轴回原点', params: { commandId: '', command: `gantry_y_origin`, params: {} } }],
  ['trayLifting01Origin', { status: '', name: 'A-1托盘升降电机回原点', params: { commandId: '', command: `tray_lifting_origin`, params: { heatId: 'heat_module_01' } } }],
  ['trayLifting02Origin', { status: '', name: 'A-2托盘升降电机回原点', params: { commandId: '', command: `tray_lifting_origin`, params: { heatId: 'heat_module_02' } } }],
  ['trayLifting03Origin', { status: '', name: 'A-3托盘升降电机回原点', params: { commandId: '', command: `tray_lifting_origin`, params: { heatId: 'heat_module_03' } } }],
  ['trayLifting04Origin', { status: '', name: 'A-4托盘升降电机回原点', params: { commandId: '', command: `tray_lifting_origin`, params: { heatId: 'heat_module_04' } } }],
  ['trayLifting05Origin', { status: '', name: 'A-5托盘升降电机回原点', params: { commandId: '', command: `tray_lifting_origin`, params: { heatId: 'heat_module_05' } } }],
  ['trayLifting06Origin', { status: '', name: 'A-6托盘升降电机回原点', params: { commandId: '', command: `tray_lifting_origin`, params: { heatId: 'heat_module_06' } } }],
  ['capLiftingOrigin', { status: '', name: '拍子升降电机回原点', params: { commandId: '', command: `cap_lifting_origin` } }],
  ['doorOrigin', { status: '', name: '门电机回原点', params: { commandId: '', command: `door_origin`, params: {} } }],
  ['shakeOrigin', { status: '', name: '摇匀电机回原点', params: { commandId: '', command: `shake_origin`, params: {} } }],
  ['dualRobotOrigin', { status: '', name: '加液机械臂回原点', params: { commandId: '', command: `dual_robot_origin`, params: {} } }],
]))

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

onMounted(async () => {
  socket.init(receiveMessage1, 'cmd_debug')
  socket.init(receiveMessage2, 'cmd_response')
  socket.init(receiveMessageSelfMove, 'self_move_test')
  const res = await getSelfStatus()
  for (const key in res) {
    const entry = checkMap.value.get(key)
    if (entry) {
      entry.status = res[key] ? 'success' : 'error'
    }
  }
  await ElMessageBox.confirm(
    '设备转运机械臂x、y、z需进行初始化，请确认机械臂行进路径无杂物，夹爪没有在夹取物品',
    '提示',
    {
      confirmButtonText: '确认',
      showClose: false,
      showCancelButton: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning',
      customClass: 'init-message',
    },
  )
  const keys = [...checkMap.value.keys()]
  checkList.value.push(checkMap.value.get(keys[0]), checkMap.value.get(keys[1]), checkMap.value.get(keys[2]))
})

watch(() => checkList.value, async (newVal) => {
  console.log('checkList', newVal)
  if (newVal.length === 3 && newVal.every(item => item.status === 'success')) {
    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 = 3; i < keys.length; i++) {
      checkList.value.push(checkMap.value.get(keys[i]))
    }
  }
}, { deep: true })

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 item1 = heatList.value.find(item => item.params.commandId === data.commandId)
  if (item1 && data.commandId === item1.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: 'move_test',
    params: {},
  }
  await homeStore.sendControl(params)
}

const checkTextList = ref<string[]>([])

const receiveMessageSelfMove = (data: any) => {
  checkTextList.value.push(data.title)
  percentage.value = data.schedule
}

const activeStep = ref(0)

const heatList = ref([
  {
    name: 'A-1',
    status: 'success',
    command: 'heat_module_01',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_01' } },
  },
  {
    name: 'A-2',
    status: 'success',
    command: 'heat_module_02',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_02' } },
  },
  {
    name: 'A-3',
    status: 'success',
    command: 'heat_module_03',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_03' } },
  },
  {
    name: 'A-4',
    status: 'success',
    command: 'heat_module_04',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_04' } },
  },
  {
    name: 'A-5',
    status: 'success',
    command: 'heat_module_05',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_05' } },
  },
  {
    name: 'A-6',
    status: 'success',
    command: 'heat_module_06',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_06' } },
  },
])

const checkHandle1 = async () => {
  const res = await requireOutTray()
  res.forEach((item) => {
    const heatItem = heatList.value.find(heatItem => heatItem.command === item.moduleCode)
    heatItem!.status = item.trayExist ? 'error' : 'success'
  })
  activeStep.value = 2
}
</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>
        <ft-button v-if="item.status !== 'success'" size="small" type="primary" :click-handle="() => commandHandle(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 in checkTextList" :key="item">
          {{ item }}
        </li>
      </ul>
    </div>

    <div v-if="activeStep === 2" class="check-box">
      <div v-for="item in heatList" :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>
        <ft-button v-if="item.status !== 'success'" size="small" type="primary" :click-handle="() => commandHandle(item)">
          移出托盘
        </ft-button>
      </div>
    </div>

    <template #footer>
      <div style="height: 40px">
        <FtButton v-if="activeStep === 0 && checkList.length === 13 && checkList.every(item => item.status === 'success')" type="primary" :click-handle="checkHandle">
          下一步
        </FtButton>
        <FtButton v-if="activeStep === 1 && percentage === 100" type="primary" :click-handle="checkHandle1">
          下一步
        </FtButton>
        <FtButton v-if="activeStep === 2" :click-handle="onConfirm">
          关闭
        </FtButton>
      </div>
    </template>
  </FtDialog>
</template>

<style scoped>
.check-box {
  height: 45vh;
  ul {
    li {
      margin: 3px 0;
    }
  }
}
.progress-box {
  width: 100%;
  display: flex;
  align-items: center;
  p {
    margin-right: 10px;
  }
  span {
    margin-left: 10px;
  }
  .el-progress {
    flex: 1;
  }
}
.check-main{
  height: 65vh;
  overflow: auto;

}

.check-item {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  .el-tag {
    flex: 1;
  }
  .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;
}
</style>
