<script setup lang="ts">
import { trayIn } from 'apis/home'
import AddLiquid from 'components/home/AddLiquid/index.vue'
import CheckCraft from 'components/home/CheckCraft/index.vue'
import ExecuteCraft from 'components/home/ExecuteCraft/index.vue'
import ExtractLiquid from 'components/home/ExtractLiquid/index.vue'
import FillSolution from 'components/home/FillSolution/index.vue'
import SetTemperature from 'components/home/SetTemperature/index.vue'

import StartClean from 'components/home/StartClean/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 { cmdNameMap, formatDateTime } from 'libs/utils'
import { useHomeStore } from 'stores/homeStore'
import { useSystemStore } from 'stores/systemStore'
import { computed, onMounted, onUnmounted, provide, 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)
  if (['start', 'success', 'fail'].includes(data.status)) {
    const cmdName = cmdNameMap[data.command as keyof typeof cmdNameMap] || data.command
    systemStore.insertLog({ cmdName, status: data.status as System.SystemLog['status'], time: formatDateTime() })
  }
}

const selectedHeatArea = computed(() => {
  return homeStore.heatAreaList.find(item => item.selected)
})

const startVisible = ref(false)

const selectCraftVisible = ref(false)

const executeCraftHandle = async () => {
  selectCraftVisible.value = true
}

const setTemperatureVisible = ref(false)
const currentTemperatureData = ref<{ id: string, label: string | undefined }>({
  id: '',
  label: 'A-1',
})
provide('currentTemperatureData', currentTemperatureData)
const setTemperature = (data: System.HeatArea) => {
  const craft = systemStore.systemStatus.trays?.find(item => item.heatModuleCode === data.moduleCode)?.crafts
  if (craft?.craft) {
    FtMessage.warning(`当前加热区已绑定工艺`)
    return
  }
  currentTemperatureData.value = {
    id: data.moduleCode,
    label: homeStore.heatAreaList.find(item => item.value === data.moduleCode)?.label,
  }
  setTemperatureVisible.value = true
}

const fillSolutionVisible = ref(false)

const addLiquidVisible = ref(false)

const cleanVisible = ref(false)

const extractLiquidVisible = ref(false)

const commandHandle = async (command: string, params?: unknown) => {
  currentCommandId = Date.now().toString()
  const data = {
    commandId: currentCommandId,
    command,
    params,
  }
  await homeStore.sendControl(data)
}

const move_to_liquid_area = async () => {
  if (!selectedHeatArea.value?.value) {
    await ElMessageBox.confirm(
      '是否要将上料区托盘移至加液位? ',
      '提示',
      {
        confirmButtonText: '确认',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        customClass: 'init-message',
      },
    )
  }
  await commandHandle('move_to_liquid_area', { heatModuleCode: selectedHeatArea.value?.value })
}

const move_to_feed_area = async () => {
  if (!selectedHeatArea.value?.value) {
    await ElMessageBox.confirm(
      '是否要将加液位托盘移至上料区? ',
      '提示',
      {
        confirmButtonText: '确认',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        customClass: 'init-message',
      },
    )
  }
  await commandHandle('move_to_feed_area', { heatModuleCode: selectedHeatArea.value?.value })
}

const move_to_anneal_area = async () => {
  if (!selectedHeatArea.value?.value) {
    await ElMessageBox.confirm(
      '是否要将加液位或上料区的托盘移至退火区? ',
      '提示',
      {
        confirmButtonText: '确认',
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        customClass: 'init-message',
      },
    )
  }
  await commandHandle('move_to_anneal_area', { heatModuleCode: selectedHeatArea.value?.value })
}

const trayInHandle = async () => {
  await trayIn()
  FtMessage.success('设置放入托盘成功')
}

// const trayOutHandle = async () => {
//   await trayOut()
// }

const checkCraftVisible = ref(false)

const moreVisible = ref(false)

const cleanHandle = async () => {
  await ElMessageBox.confirm(
    '请确认已把托盘放至上料位或移至加液位? ',
    '提示',
    {
      confirmButtonText: '确认',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning',
      customClass: 'init-message',
    },
  )
  cleanVisible.value = true
}

const addLiquidHandle = async () => {
  await ElMessageBox.confirm(
    '请确认已把托盘放至上料位或移至加液位? ',
    '提示',
    {
      confirmButtonText: '确认',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning',
      customClass: 'init-message',
    },
  )
  addLiquidVisible.value = true
}

const extractLiquidHandle = async () => {
  await ElMessageBox.confirm(
    '请确认已把托盘放至上料位或移至加液位? ',
    '提示',
    {
      confirmButtonText: '确认',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      type: 'warning',
      customClass: 'init-message',
    },
  )
  extractLiquidVisible.value = true
}
</script>

<template>
  <div class="home-page">
    <div class="page-top">
      <Tube
        v-for="(item, index) in systemStore.systemStatus.heatModule"
        :key="item.moduleCode"
        :data="item"
        @select-change="homeStore.selectChange(index)"
        @set-temperature="setTemperature(item)"
      />
    </div>
    <div class="button-box">
      <el-row style="width: 100%; height: 100%" :gutter="20">
        <el-col :span="24">
          <div style="padding: 30px 0;display: grid; gap: 20px; grid-template-columns: repeat(4, 1fr);grid-template-rows: repeat(1, 1fr);height: 100%">
            <el-card>
              <ft-button type="primary" size="large" :disabled="!systemStore.systemStatus.doorModule.actionable" :click-handle="() => commandHandle('door_open')">
                开门
              </ft-button>
              <ft-button type="primary" size="large" :disabled="systemStore.systemStatus.doorModule.actionable" :click-handle="() => commandHandle('door_close')">
                关门
              </ft-button>
            </el-card>

            <el-card>
              <ft-button type="primary" size="large" :click-handle="trayInHandle">
                放入托盘
              </ft-button>
              <ft-button type="primary" size="large" :click-handle="() => commandHandle('out_tray', { heatModuleCode: selectedHeatArea!.value })" :disabled="!selectedHeatArea">
                取出托盘
              </ft-button>
            </el-card>
            <el-card>
              <ft-button type="primary" style="margin: auto 0;" class="manual-button" size="large" :click-handle="executeCraftHandle">
                执行工艺
              </ft-button>
              <!--              <ft-button type="primary" size="large" :click-handle="() => checkCraftVisible = true"> -->
              <!--                <el-icon v-if="systemStore.errorCraft" color="#DF1515" size="15" style="margin-right: 5px"> -->
              <!--                  <WarningFilled /> -->
              <!--                </el-icon> -->
              <!--                异常工艺 -->
              <!--              </ft-button> -->
            </el-card>
            <el-card>
              <el-popover
                :visible="moreVisible"
                placement="left-start"
                width="auto"
                trigger="click"
                popper-class="button-popper"
              >
                <template #reference>
                  <ft-button type="primary" size="large" style="margin: auto 0;" class="manual-button" @click="moreVisible = !moreVisible">
                    手动操作
                  </ft-button>
                </template>
                <template #default>
                  <div class="container-box">
                    <ft-button type="primary" size="large" :disabled="!selectedHeatArea" :click-handle="() => commandHandle('heater_start', { heatModuleCode: selectedHeatArea!.value })">
                      开始加热
                    </ft-button>
                    <ft-button type="primary" size="large" :disabled="!selectedHeatArea || selectedHeatArea?.label === '退火区'" :click-handle="() => commandHandle('dry_start', { heatModuleCode: selectedHeatArea!.value })">
                      开始烘干
                    </ft-button>

                    <ft-button type="primary" size="large" :disabled="!selectedHeatArea || selectedHeatArea?.label !== '退火区'" :click-handle="() => commandHandle('anneal_start', { heatModuleCode: selectedHeatArea!.value })">
                      开始退火
                    </ft-button>

                    <ft-button type="primary" size="large" :disabled="!selectedHeatArea" :click-handle="() => commandHandle('heater_stop', { heatModuleCode: selectedHeatArea!.value })">
                      停止加热
                    </ft-button>

                    <ft-button type="primary" size="large" :disabled="!selectedHeatArea" :click-handle="() => commandHandle('fan_start', { heatModuleCode: selectedHeatArea!.value })">
                      开始降温
                    </ft-button>

                    <ft-button type="primary" size="large" :disabled="!selectedHeatArea" :click-handle="() => commandHandle('fan_stop', { heatModuleCode: selectedHeatArea!.value })">
                      停止降温
                    </ft-button>

                    <ft-button type="primary" size="large" :click-handle="() => commandHandle('move_to_heat_area', { heatModuleCode: selectedHeatArea!.value })" :disabled="!selectedHeatArea">
                      移至加热位
                    </ft-button>

                    <ft-button type="primary" size="large" :click-handle="move_to_liquid_area">
                      移至加液位
                    </ft-button>
                    <ft-button type="primary" size="large" :click-handle="move_to_feed_area">
                      移至上料区
                    </ft-button>
                    <ft-button type="primary" size="large" :click-handle="move_to_anneal_area">
                      移至退火位
                    </ft-button>
                    <ft-button type="primary" size="large" @click="cleanHandle">
                      开始清洗
                    </ft-button>

                    <ft-button type="primary" size="large" @click=" fillSolutionVisible = true">
                      预充管路
                    </ft-button>

                    <ft-button type="primary" size="large" @click="addLiquidHandle">
                      添加溶液
                    </ft-button>

                    <ft-button type="primary" size="large" @click="extractLiquidHandle">
                      抽取溶液
                    </ft-button>
                    <ft-button type="primary" size="large" :click-handle="() => commandHandle('drain_liquid')">
                      关机排空
                    </ft-button>
                    <ft-button type="primary" size="large" :click-handle="() => commandHandle('liquid_motor_origin')">
                      加液臂回原点
                    </ft-button>
                    <ft-button type="primary" size="large" :click-handle="() => commandHandle('z_origin')">
                      z轴回原点
                    </ft-button>
                    <ft-button type="primary" size="large" :click-handle="() => commandHandle('x_origin')">
                      x轴回原点
                    </ft-button>
                  </div>
                </template>
              </el-popover>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
    <CheckCraft v-if="checkCraftVisible" @close="checkCraftVisible = false" />
    <StartExperiment v-if="startVisible" @ok="startVisible = false" @cancel="startVisible = false" />
    <StartClean v-if="cleanVisible" @ok="cleanVisible = false" @cancel="cleanVisible = false" />
    <ExecuteCraft v-if="selectCraftVisible" @ok="selectCraftVisible = false" @cancel="selectCraftVisible = false" />
    <SetTemperature v-if="setTemperatureVisible" @ok="setTemperatureVisible = false" @cancel="setTemperatureVisible = false" />
    <AddLiquid v-if="addLiquidVisible" @ok="addLiquidVisible = false" @cancel="addLiquidVisible = false" />
    <ExtractLiquid v-if="extractLiquidVisible" @ok="extractLiquidVisible = false" @cancel="extractLiquidVisible = false" />
    <FillSolution v-if="fillSolutionVisible" @ok="fillSolutionVisible = false" @cancel="fillSolutionVisible = false" />
  </div>
</template>

<style scoped lang="scss">
.home-page {
  .page-top{
    height: 65%;
    border-radius: 8px;
    padding: 0 10px 10px;
    display: grid;
    grid-template-columns: repeat(4, 1fr); /* 创建3列等宽轨道 */
    grid-template-rows: repeat(1, auto);   /* 创建2行自动高度 */
    gap: 10px;
    justify-content: center;               /* 水平居中 */
    align-items: center;
  }
  .button-box {
    height: 35%;
    //display: grid;
    //grid-template-columns: repeat(6, 1fr); /* 创建3列等宽轨道 */
    //grid-template-rows: repeat(4, 1fr);   /* 创建2行自动高度 */
    //gap: 10px 20px;
    .ft-button {
      //width: 100px;
      font-weight: bold;
      margin-right: 0;

      .my-button {
        padding: 0 !important;
        border: 3px solid #1989fa !important;
      }
    }
  }

}
.el-col {
  height: 100%;
}
.manual-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.container-box {
  width: 600px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 10px;

}
.manual-button {
  height: 80px;
  line-height: 80px;
  text-align: center;
  border-radius: 10px;
  :deep(.my-button) {
    height: 100%;
  }
}

:deep(.el-card__body){
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  .ft-button {
    box-shadow: 0 0 25px rgba(0,0,0,0.2);
  }
}
</style>
