<script setup lang="ts">
import { startCraft } from 'apis/crafts'
import AddLiquid from 'components/home/AddLiquid/index.vue'
import SelectCraft from 'components/home/SelectCraft/index.vue'
import SetTemperature from 'components/home/SetTemperature/index.vue'
import StartExperiment from 'components/home/StartExperiment/index.vue'
import Tube from 'components/home/Tube/index.vue'
import { ElMessageBox } from 'element-plus'
import { FtMessage } from 'libs/message'
import { socket } from 'libs/socket'
import { useHomeStore } from 'stores/homeStore'
import { useSystemStore } from 'stores/systemStore'
import { onMounted, onUnmounted, ref } from 'vue'

const homeStore = useHomeStore()
const systemStore = useSystemStore()

onMounted(() => {
  socket.init(receiveMessage, 'cmd_debug')
  socket.init(receiveMessage, 'cmd_response')
})

onUnmounted(() => {
  socket.unregisterCallback(receiveMessage, 'cmd_debug')
  socket.unregisterCallback(receiveMessage, 'cmd_response')
})

let currentCommandId = ''
const receiveMessage = (data: Socket.cmdData) => {
  data.commandId === currentCommandId && systemStore.pushSystemList(data)
}

const startVisible = ref(false)

// const startExperimentHandle = () => {
//   // TODO 需要判断有没有进行中的实验
//   startVisible.value = true
// }

const selectCraftVisible = ref(false)
const selectCraft = () => {
  const count = homeStore.heatAreaList.filter(item => item.selected).length
  if (!count) {
    FtMessage.warning('请选择加热区')
    return
  }
  selectCraftVisible.value = true
}

const executeCraftHandle = async () => {
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length) {
    FtMessage.warning('请选择加热区')
    return
  }
  // TODO 需要判断有没有选择工艺
  for (let i = 0; i < selectedHeatAreas.length; i++) {
    await startCraft({
      heatId: selectedHeatAreas[i].value,
    })
  }
  FtMessage.success('工艺已开始执行')
}

const setTemperatureVisible = ref(false)
const currentTemperatureId = ref('')
const setTemperature = (id: string) => {
  currentTemperatureId.value = id
  setTemperatureVisible.value = true
}

const addLiquidVisible = ref(false)
const addLiquid = async () => {
  await ElMessageBox.confirm(
    '请确认加液区是否有托盘?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      showClose: false,
      closeOnClickModal: false,
      type: 'warning',
    },
  )
  addLiquidVisible.value = true
  // if (!systemStore.systemStatus.solutionModule.trayStatus) {
  //   FtMessage.warning('加液区无托盘')
  //   return
  // }
}

const door_open = async () => {
  if (systemStore.systemStatus.door.open) {
    FtMessage.warning('门已经是开启状态了')
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'door_open',
    params: { },
  }
  await homeStore.sendControl(params)
}

const door_close = async () => {
  if (!systemStore.systemStatus.door.open) {
    FtMessage.warning('门已经是关闭状态了')
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'door_close',
    params: { },
  }
  await homeStore.sendControl(params)
}

const move_to_heat_area = async () => {
  // if (systemStore.systemStatus.solutionModule.trayStatus === 0) {
  //   FtMessage.warning('加液区无托盘')
  //   return
  // }
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length || selectedHeatAreas.length > 1) {
    FtMessage.warning('请选择一个加热区')
    return
  }
  await ElMessageBox.confirm(
    '请确认加液区是否有托盘?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      showClose: false,
      closeOnClickModal: false,
      type: 'warning',
    },
  )

  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'move_to_heat_area',
    params: {
      heatId: selectedHeatAreas[0].value,
    },
  }
  await homeStore.sendControl(params)
}

const move_to_solution_area = async () => {
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length || selectedHeatAreas.length > 1) {
    FtMessage.warning('请选择一个加热区')
    return
  }
  await ElMessageBox.confirm(
    '请确认加液区无托盘?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      showClose: false,
      closeOnClickModal: false,
      type: 'warning',
    },
  )
  // if (systemStore.systemStatus.solutionModule.trayStatus === 1) {
  //   FtMessage.warning('加液区有托盘')
  //   return
  // }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'move_to_solution_area',
    params: {
      heatId: selectedHeatAreas[0].value,
    },
  }
  await homeStore.sendControl(params)
}

const heat_start = async () => {
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length || selectedHeatAreas.length > 1) {
    FtMessage.warning('请选择一个加热区')
    return
  }
  if (systemStore.systemStatus.heatModule.find(item => item.moduleCode === selectedHeatAreas[0].value)?.targetTemperature) {
    FtMessage.warning('请先设置温度')
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'heat_start',
    params: {
      heatId: selectedHeatAreas[0].value,
      temperature: systemStore.systemStatus.heatModule.find(item => item.moduleCode === selectedHeatAreas[0].value)?.targetTemperature,
    },
  }
  await homeStore.sendControl(params)
}

const heat_stop = async () => {
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length || selectedHeatAreas.length > 1) {
    FtMessage.warning('请选择一个加热区')
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'heat_stop',
    params: {
      heatId: selectedHeatAreas[0].value,
    },
  }
  await homeStore.sendControl(params)
}

const tray_up = async () => {
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length || selectedHeatAreas.length > 1) {
    FtMessage.warning('请选择一个加热区')
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'tray_up',
    params: {
      heatId: selectedHeatAreas[0].value,
    },
  }
  await homeStore.sendControl(params)
}

const tray_down = async () => {
  const selectedHeatAreas = homeStore.heatAreaList.filter(item => item.selected)
  if (!selectedHeatAreas.length || selectedHeatAreas.length > 1) {
    FtMessage.warning('请选择一个加热区')
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'tray_down',
    params: {
      heatId: selectedHeatAreas[0].value,
    },
  }
  await homeStore.sendControl(params)
}

const shake_start = async () => {
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'shake_start',
    params: {
    },
  }
  await homeStore.sendControl(params)
}

const shake_stop = async () => {
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'shake_stop',
    params: {
    },
  }
  await homeStore.sendControl(params)
}

const take_photo = async () => {
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'take_photo',
    params: {
    },
  }
  await homeStore.sendControl(params)
}
</script>

<template>
  <div class="home-page">
    <el-row :gutter="10">
      <el-col :span="15">
        <div class="page-left">
          <Tube v-for="(item, index) in systemStore.systemStatus.heatModule" :key="item.moduleCode" :data="item" @select-change="homeStore.selectChange(index)" @set-temperature="setTemperature" />
        </div>
      </el-col>
      <el-col :span="9">
        <div class="page-right">
          <div class="top">
            <div class="photo" @click="take_photo">
              <el-icon><Camera /></el-icon>
              <span>拍照</span>
            </div>
          </div>
          <div class="button-box">
            <el-row :gutter="10">
              <el-col :span="12">
                <ft-button :click-handle="door_open">
                  开门
                </ft-button>
              </el-col>
              <el-col :span="12">
                <ft-button :click-handle="door_close">
                  关门
                </ft-button>
              </el-col>
            </el-row>
            <!--            <el-row :gutter="10"> -->
            <!--              <el-col :span="12"> -->
            <!--                <ft-button @click="startExperimentHandle"> -->
            <!--                  开始实验 -->
            <!--                </ft-button> -->
            <!--              </el-col> -->
            <!--              <el-col :span="12"> -->
            <!--                <ft-button disabled> -->
            <!--                  停止实验 -->
            <!--                </ft-button> -->
            <!--              </el-col> -->
            <!--            </el-row> -->
            <!--            <el-row :gutter="10"> -->
            <!--              <el-col :span="12"> -->
            <!--                <ft-button @click="selectCraft"> -->
            <!--                  选择工艺 -->
            <!--                </ft-button> -->
            <!--              </el-col> -->
            <!--              <el-col :span="12"> -->
            <!--                <ft-button :click-handle="executeCraftHandle"> -->
            <!--                  执行工艺 -->
            <!--                </ft-button> -->
            <!--              </el-col> -->
            <!--            </el-row> -->
            <el-row :gutter="10">
              <el-col :span="24">
                <ft-button @click="addLiquid">
                  添加溶液
                </ft-button>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <ft-button :click-handle="shake_start">
                  开始摇匀
                </ft-button>
              </el-col>
              <el-col :span="12">
                <ft-button :click-handle="shake_stop">
                  停止摇匀
                </ft-button>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <ft-button :click-handle="move_to_heat_area">
                  移至加热
                </ft-button>
              </el-col>
              <el-col :span="12">
                <ft-button :click-handle="move_to_solution_area">
                  移至加液
                </ft-button>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <ft-button :click-handle="heat_start">
                  开始加热
                </ft-button>
              </el-col>
              <el-col :span="12">
                <ft-button :click-handle="heat_stop">
                  停止加热
                </ft-button>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <ft-button :click-handle="tray_up">
                  抬起托盘
                </ft-button>
              </el-col>
              <el-col :span="12">
                <ft-button :click-handle="tray_down">
                  降下托盘
                </ft-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-col>
    </el-row>

    <StartExperiment v-if="startVisible" @ok="startVisible = false" @cancel="startVisible = false" />
    <SelectCraft v-if="selectCraftVisible" @ok="selectCraftVisible = false" @cancel="selectCraftVisible = false" />
    <SetTemperature v-if="setTemperatureVisible" :id="currentTemperatureId" @ok="setTemperatureVisible = false" @cancel="setTemperatureVisible = false" />
    <AddLiquid v-if="addLiquidVisible" @ok="addLiquidVisible = false" @cancel="addLiquidVisible = false" />
  </div>
</template>

<style scoped lang="scss">
.home-page {
  background: rgba(0, 0, 0, 0) !important;
  padding: 0 !important;
  .el-row {
    height: 100%;
    .el-col {
      height: 100%;
      .page-left, .page-right {
        height: 100%;
        background: #fff;
        border-radius: 8px;
        padding: 10px;
      }
      .page-left {
        display: grid;
        grid-template-columns: repeat(3, 1fr); /* 创建3列等宽轨道 */
        grid-template-rows: repeat(2, auto);   /* 创建2行自动高度 */
        gap: 10px;
        justify-content: center;               /* 水平居中 */
        align-items: center;
      }
      .page-right {
        display: flex;
        flex-direction: column;
        height: 100%;
        .top {
          height: 50%;
          background: #4D6882;
          position: relative;
          border-radius: 8px;
          overflow: hidden;
          .photo {
            width: 100%;
            height: 40px;
            background: rgba(0, 0, 0, 0.3);
            position: absolute;
            bottom: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            color: #fff;
            font-size: 15px;
          }
        }
        .button-box {
          height: 50%;
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
          .el-row {
            height: fit-content;
            margin-bottom: 5px;
          }
        }
      }
    }
  }
}
.el-col {
  .ft-button {
    width: 100%;
    .my-button {
      padding: 0 !important;
    }
  }

}
</style>
