<script setup lang="ts">
import { list as listMatrix } from 'apis/matrix'
import { getDeviceStatus, getSprayStatus, setParams } from 'apis/system'
import SprayParams from 'components//spray/sprayParams/index.vue'
import TrayGraph from 'components/spray/trayGraph/index.vue'
import { FtMessage } from 'libs/message'
import { socket } from 'libs/socket'
import { colors, sendControl } from 'libs/utils'
import { cloneDeep } from 'lodash'
import { useSprayStore } from 'stores/useSprayStore'
import { useSystemStore } from 'stores/useSystemStore'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'

const systemStore = useSystemStore()
const sprayStore = useSprayStore()

onMounted(async () => {
  socket.init(sprayPointReceiveMessage, 'spray_point')
  socket.init(finishMessage, 'cmd_response')
  await getMatrixList()
  await getDeviceStatus().then((res: any) => {
    systemStore.updateSystemStatus(res)
    if (systemStore.systemStatus.spraying) {
      FtMessage.info('正在喷涂中...')
      maskVisible.value = true
      getSpraying()
    }
  })
})

onUnmounted(() => {
  socket.unregisterCallback(sprayPointReceiveMessage, 'spray_point')
  socket.unregisterCallback(finishMessage, 'cmd_response')
})

const matrixList = ref<{ name: string, id: number }[]>([])
const getMatrixList = async () => {
  const res = await listMatrix({ pageNum: 1, pageSize: 100, matrixName: '' })
  matrixList.value = res.list
}

const getSpraying = async () => {
  const res: any = await getSprayStatus()
  cmdId = res.cmdId
  res.sprayTaskParams.forEach((item: any) => {
    sprayStore.updateSprayForm(item, item.index)
  })
  res.sprayTaskSprayedList
    .forEach((task: any) => {
      nextTick(() => {
        drawLine(task.index, { x: task.sprayedPoints.x * 5, y: task.sprayedPoints.y * 5 }, task.number)
      })
    })
}

const sprayRefs = ref<any>([])

const maskVisible = ref(false)

const startWork = async () => {
  const data = sprayStore.sprayTaskParams.filter(item => item.select)
  if (!data.length) {
    FtMessage.error('至少选择一个喷涂玻片')
    return
  }
  const errIndex = []
  data.forEach((item, index) => {
    if (!item.hasSet) {
      errIndex.push(index)
      FtMessage.error(`玻片${index + 1}: 请设置喷涂参数`)
    }
  })
  if (errIndex.length) {
    return
  }
  sprayStore.sprayTaskParams.forEach((item, index) => {
    if (item.select) {
      sprayRefs.value[index].clearLines()
    }
  })
  await setParams({ sprayTaskParams: sprayStore.sprayTaskParams.filter(item => item.select) })
  cmdId = Date.now().toString()
  const params = {
    cmdCode: 'matrix_spray_start',
    cmdId,
    params: {
    },
  }

  await sendControl(params)
  maskVisible.value = true
  // currentSpeed = Number(form.value.movingSpeed)
}

const pauseWork = async () => {
  const params = {
    cmdCode: 'matrix_spray_pause',
    cmdId: '',
  }
  await sendControl(params)
}

const continueWork = async () => {
  const params = {
    cmdCode: 'matrix_spray_continue',
    cmdId: '',
    params: {
    },
  }
  await sendControl(params)
  // currentSpeed = Number(form.value.movingSpeed)
}

const stopWork = async () => {
  const params = {
    cmdCode: 'matrix_spray_stop',
    cmdId: '',
  }
  await sendControl(params)
  sprayStore.sprayTaskParams.forEach((item, index) => {
    if (item.select) {
      sprayRefs.value[index].clearLines()
      item.select = false
    }
  })
}

// let currentSpeed = 0
// console.log(currentSpeed)
// let poll: ReturnType<typeof setInterval>

let cmdId = ''
const sprayPointReceiveMessage = (data: any) => {
  if (data.cmdId === cmdId) {
    const { currentPoint, index, number } = data
    drawLine(index, { x: currentPoint.x * 5, y: currentPoint.y * 5 }, number)
  }

  // if (poll) {
  //   clearInterval(poll)
  // }
  // const { currentPoint, nextPoint, index } = data
  // // 计算累加的mm
  // const moveDistance = currentSpeed / 2
  // // y轴移动
  // if (currentPoint.x === nextPoint.x) {
  //   let currentY = currentPoint.y
  //   poll = setInterval(() => {
  //     currentY += moveDistance
  //     if (currentY >= nextPoint.y) {
  //       clearInterval(poll)
  //     }
  //     drawLine(index, { x: currentPoint.x * 5, y: currentY * 5 })
  //   }, 500)
  // }
  // else if (currentPoint.y === nextPoint.y) {
  //   // x轴移动
  //   let currentX = currentPoint.x
  //   poll = setInterval(() => {
  //     currentX += moveDistance
  //     if (currentX >= nextPoint.x) {
  //       clearInterval(poll)
  //     }
  //     drawLine(index, { x: currentX * 5, y: currentPoint.y * 5 })
  //   }, 500)
  // }
}

const finishMessage = (data: any) => {
  console.log(data, cmdId)
  if (data.cmdId === cmdId) {
    if (data.status === 'fail') {
      FtMessage.error(data.title)
    }
    if (data.status === 'success') {
      FtMessage.success('喷涂执行成功')
    }
    if (data.status === 'spray_task_finish') {
      sprayStore.sprayTaskParams.forEach((item, index) => {
        if (item.select) {
          sprayRefs.value[index].clearLines()
          item.select = false
        }
      })
      maskVisible.value = false
    }
  }
}

const drawLine = async (index: number, point: { x: number, y: number }, number: number) => {
  console.log('drawLine', sprayRefs.value[index], index, point, number)
  await nextTick(() => {
    if (!sprayRefs.value[index].hasLine(number)) {
      sprayRefs.value[index].addLine(colors[number])
    }
    sprayRefs.value[index].updateLine(point, number, colors[number])
  })
}

const selectCraftVisible = ref(false)
const ok = async (data: any) => {
  selectCraftVisible.value = false
  sprayStore.updateSprayForm(data, selectIndex.value)
}

const sprayParamsCancelHandle = () => {
  selectCraftVisible.value = false
}

const selectIndex = ref(0)
const currentFormData = ref()
const openSetting = (index: number) => {
  selectIndex.value = index
  currentFormData.value = cloneDeep(sprayStore.sprayTaskParams[index])
  sprayParamsDisabled.value = false
  selectCraftVisible.value = true
}

const checkChange = (index: number, checked: boolean) => {
  // if (checked) {
  //   selectCraftVisible.value = true
  // }
  console.log(checked, index)
}

const sprayParamsDisabled = ref(false)

const viewParams = (index: number) => {
  selectIndex.value = index
  currentFormData.value = cloneDeep(sprayStore.sprayTaskParams[index])
  sprayParamsDisabled.value = true
  selectCraftVisible.value = true
}
</script>

<template>
  <div class="spray-container">
    <div class="button-box">
      <ft-button type="primary" :disabled="systemStore.systemStatus.spraying" @click="startWork">
        开始喷涂
      </ft-button>
      <!--            <ft-button type="primary" :disabled="!systemStore.systemStatus.spraying" @click="updateParam"> -->
      <!--              调整参数 -->
      <!--            </ft-button> -->
      <ft-button type="primary" :disabled="!systemStore.systemStatus.spraying" @click="pauseWork">
        暂停喷涂
      </ft-button>
      <ft-button type="primary" :disabled="!systemStore.systemStatus.paused" @click="continueWork">
        继续喷涂
      </ft-button>
      <ft-button type="primary" :disabled="!systemStore.systemStatus.spraying" @click="stopWork">
        结束喷涂
      </ft-button>
    </div>
    <div class="spray-box">
      <div v-show="maskVisible" class="mask-box" />
      <div
        v-for="(p, index) in sprayStore.sprayTaskParams"
        :key="index"
        style="height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: space-evenly"
      >
        <p class="tray-name">
          <el-checkbox v-model="p.select" @change="val => checkChange(index, val)" />
          <span>玻片{{ index + 1 }}</span>
        </p>
        <TrayGraph ref="sprayRefs" :key="index" :container="`spray-${index + 1}`" :edit-select="false" />
        <ft-button v-if="!systemStore.systemStatus.spraying" type="primary" @click="() => openSetting(index)">
          喷涂设置
        </ft-button>
        <ft-button v-else type="primary" @click="() => viewParams(index)">
          运行参数
        </ft-button>
      </div>
    </div>
    <SprayParams
      v-if="selectCraftVisible"
      :disabled="sprayParamsDisabled"
      :form-data="currentFormData"
      @ok="ok"
      @cancel="sprayParamsCancelHandle"
    />
  </div>
</template>

<style scoped lang="scss">
.spray-container {
  width: 100%;
  height: 100%;
  padding: 30px 10px !important;
  display: flex;
  flex-direction: column;
  align-items: center;
  .button-box {
    width: 100%;
    display: flex;
    justify-content: center;
    height: 120px;
    gap: 50px;
  }
  .spray-box {
    position: relative;
    width: 100%;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
    //gap: 200px;
  }
}
.el-input,
.el-select {
  width: 400px;
  margin: 0 40px;
}
.unit-text {
  font-size: 40px;
  color: #0349a8;
  font-weight: 500;
}
.select-box {
  display: flex;
  margin: 40px;
}
.route-img {
  display: flex;
  img {
    width: 70px;
  }
}

.voltage-box {
  display: flex;
  align-items: center;
  margin-left: 40px;
  height: 100px;
  .voltage-input {
    width: 280px;
  }
}
:deep(.el-form-item__error) {
  font-size: 22px;
  margin-left: 50px;
}
.mask-box {
  position: absolute;
  width: 100%;
  top: 0;
  height: 50%;
  background: rgba(255, 255, 255, 0.01);
  z-index: 2000;
}
.tray-name {
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}
:deep(.ft-button) {
  margin: 0;
}
:deep(.el-drawer) {
  width: 33% !important;
}
:deep(.el-tabs) {
  margin: 0;
}
:deep(.el-tabs__content) {
  display: none;
}
</style>
