<script lang="ts" setup>
import { getSelfFinish, getSelfStatus } from 'apis/self'
import { requireOutTray, setIgnoreItem } 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 } from 'vue'

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

const checkMap = ref(new Map([
  ['transferZOrigin', { status: '', ignoreKey: 'transferZOriginIsIgnore', name: 'z轴回原点', params: { commandId: '', command: `transfer_z_origin`, params: {} } }],
  ['transferXOrigin', { status: '', ignoreKey: 'transferXOriginIsIgnore', name: 'x轴回原点', params: { commandId: '', command: `transfer_x_origin`, params: {} } }],
  ['doorOrigin', { status: '', ignoreKey: 'doorOriginIsIgnore', name: '门电机回原点', params: { commandId: '', command: `door_origin`, params: {} } }],
  ['dualRobotOrigin', { status: '', ignoreKey: 'dualRobotOriginIsIgnore', 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'
    }
    for (const [checkKey] of checkMap.value) {
      const data = checkMap.value.get(checkKey)
      if (key === data?.ignoreKey) {
        res[key] && (data.status = 'ignore')
      }
    }
  }
  await ElMessageBox.confirm(
    '设备转运机械臂x、z, 加液机械臂, 门等需进行初始化，请确认机械臂行进路径无杂物',
    '提示',
    {
      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 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: '加热区1',
    status: 'success',
    command: 'heat_module_01',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_01' } },
  },
  {
    name: '加热区2',
    status: 'success',
    command: 'heat_module_02',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_02' } },
  },
  {
    name: '加热区23',
    status: 'success',
    command: 'heat_module_03',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_03' } },
  },
  {
    name: '退火区',
    status: 'success',
    command: 'heat_module_04',
    params: { commandId: '', command: `tray_out`, params: { heatId: 'heat_module_04' } },
  },
])

const checkHandle1 = async () => {
  const res = await requireOutTray()
  res.forEach((item) => {
    const heatItem = heatList.value.find(heatItem => heatItem.command === item.moduleCode)
    heatItem!.status = 'error'
  })
  activeStep.value = 2
}

const ignore = async (item: any) => {
  await setIgnoreItem({
    ignoreSelfTestType: item.ignoreKey,
    ignore: true,
  })
  item.status = 'ignore'
}
</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="item.status !== 'success'" type="primary" :click-handle="() => commandHandle(item)">
          回原点
        </ft-button>
        <ft-button v-if="item.status !== 'ignore'" type="primary" :click-handle="() => ignore(item)">
          忽略
        </ft-button>
        <ft-button v-if="item.status === 'ignore'" type="danger" :click-handle="() => ignore(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.every(item => ['success', 'ignore'].includes(item.status))" 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: 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: 30vh;
  overflow: auto;

}

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