<template>
  <!-- 通信管理弹框 -->
  <DSDialog
    title="通信管理"
    v-model="show"
    width="1200"
    class="commManagement-dialog ds-dialog"
    @close="handleClose"
  >
    <div class="commManagement-container">
      <div class="commManagement-siderBar">
        <div
          class="commManagement-sidebar-item"
          :class="{ active: activeTab === v.value }"
          @click="setActiveTab(v)"
          v-for="(v, k) in commBars"
          :key="k"
        >
          <!-- // TODO 替换icon  -->
          <img :src="activeTab === v.value ? v.iconSelected : v.icon" alt="" class="w-[32px]" />
          <span>{{ v.label }}</span>
        </div>
      </div>
      <div class="commManagement-line-first" />
      <div
        class="commManagement-infoList"
        v-if="activeTab != 'heartbeat' && activeTab != 'response'"
      >
        <div class="commManagement-infoList-title">
          <span>{{ currentTabLabel }}</span>
          <div class="infoList-title-btn" @click="addDevice">+</div>
        </div>
        <div class="commManagement-infoList-content">
          <div
            class="commManagement-infoList-item"
            :class="{ active: deviceTab === item.name }"
            v-for="(item, index) in deviceBars"
            :key="index"
            @click="selectDevice(item)"
          >
            <span>{{ item.name }}</span>
            <el-switch v-model="item.enabled" size="small" />
          </div>
          <el-empty
            :image-size="54"
            :image="NoDataIcon"
            style="margin-top: 130px"
            v-if="deviceBars.length === 0"
          />
        </div>
      </div>
      <div
        class="commManagement-line-second"
        v-if="activeTab != 'heartbeat' && activeTab != 'response'"
      />
      <div class="commManagement-content">
        <!-- 设备表单 -->
        <DeviceForm v-if="activeTab === 'device'" :form-data="formDeviceInfo" :options="options" />
        <!-- 接收事件表单 -->
        <ReceiveEventForm
          v-if="activeTab === 'receive'"
          :form-data="formEventInfo"
          :receive-event-type="receiveEventType"
          :options="options"
          @addRow="handleTableAdd"
        />
        <!-- 发送事件表单 -->
        <SendEventForm
          v-if="activeTab === 'send'"
          :form-data="formSendEventInfo"
          :send-event-type="sendEventType"
          :options="options"
          @addRow="handleTableAdd"
        />
        <!-- 心跳管理表单 -->
        <HeartBeatForm
          v-if="activeTab === 'heartbeat'"
          :form-data="formHeartBeatInfo"
          :options="options"
          @addRow="handleTableAdd"
        />
        <!-- 响应配置表单 -->
        <ResponseForm
          v-if="activeTab === 'response'"
          :form-data="formResponseInfo"
          :options="options"
          @addRow="handleTableAdd"
        />
      </div>
    </div>
  </DSDialog>
  <DeviceDialog v-model:value="isDeviceDialog" />
  <EventDialog v-model:value="isEventDialog" :title="eventDialogTitle" />
</template>

<script setup lang="ts">
defineOptions({
  name: 'CommManagement'
})
import { DSButton } from '@/components/Button'
import { DSDialog } from '@/components/Dialog'
import DeviceDialog from './deviceDialog.vue'
import EventDialog from './eventDialog.vue'
import DeviceForm from './deviceForm.vue'
import ReceiveEventForm from './receiveEventForm.vue'
import SendEventForm from './sendEventForm.vue'
import HeartBeatForm from './heartBeatForm.vue'
import ResponseForm from './responseForm.vue'
import DeviceIcon from '@/assets/images/common/device.png'
import DeviceSelectedIcon from '@/assets/images/common/device_selected.png'
import SendIcon from '@/assets/images/common/send.png'
import SendSelectedIcon from '@/assets/images/common/send_selected.png'
import ReceiveIcon from '@/assets/images/common/receive.png'
import ReceiveSelectedIcon from '@/assets/images/common/receive_selected.png'
import HeartbeatIcon from '@/assets/images/common/heartbeat.png'
import HeartbeatSelectedIcon from '@/assets/images/common/heartbeat_selected.png'
import ResponseIcon from '@/assets/images/common/response.png'
import ResponseSelectedIcon from '@/assets/images/common/response_selected.png'
import NoDataIcon from '@/assets/images/common/no_data.png'
interface Props {
  /** import DeviceDialog from './deviceDialog.vue';
弹窗显隐 */
  value: boolean
}
interface Emits {
  (e: 'update:value', val: boolean): void
}
const props = withDefaults(defineProps<Props>(), {
  value: false
})
const emit = defineEmits<Emits>()

const show = computed({
  get() {
    Object.assign(deviceBars, deviceList)
    activeTab.value = 'device'
    return props.value
  },
  set(val: boolean) {
    emit('update:value', val)
  }
})
const isDeviceDialog = ref(false)
const isEventDialog = ref(false)
const eventDialogTitle = ref('')
// 左侧菜单激活状态
const activeTab = ref('device') // device/receive/send/heartbeat/response
// 中间tab
const deviceTab = ref('') // device/receive/send/heartbeat/response
const deviceBars = ref([])

// 根据 activeTab 匹配对应的中文 label
const currentTabLabel = computed(() => {
  // 在 commBars 中找到 value 与 activeTab 匹配的项，返回其 label
  const matched = commBars.find((item) => item.value === activeTab.value)
  // 如果找不到匹配项，默认显示空或提示文字
  return matched ? matched.label : ''
})

const options = [
  {
    value: 'Option1',
    label: 'Option1'
  },
  {
    value: 'Option2',
    label: 'Option2'
  },
  {
    value: 'Option3',
    label: 'Option3'
  },
  {
    value: 'Option4',
    label: 'Option4'
  },
  {
    value: 'Option5',
    label: 'Option5'
  }
]
// 设备列表
const deviceList = ref([
  {
    name: '1.TCP客户端',
    enabled: false,
    info: {
      protocol: '1',
      deviceName: '1',
      IP: '1',
      targetPort: '1',
      dataUpload: false,
      reconnect: false,
      acceptEnd: false,
      endInfo: '1'
    }
  },
  { name: '2.UDP客户端', enabled: false }
])
// 接收事件列表
const receiveList = ref([
  {
    name: '文本-协议解析',
    enabled: false,
    info: {
      protocol: '1',
      deviceName: '1',
      IP: '1',
      targetPort: '1',
      dataUpload: false,
      reconnect: false,
      acceptEnd: false,
      endInfo: '1'
    }
  },
  { name: '文本-协议组装', enabled: false },
  { name: '字节-协议组装', enabled: false },
  { name: '脚本', enabled: false }
])
// 发送事件列表
const sendList = ref([
  {
    name: '文本-直接输出',
    enabled: false,
    info: {
      protocol: '1',
      deviceName: '1',
      IP: '1',
      targetPort: '1',
      dataUpload: false,
      reconnect: false,
      acceptEnd: false,
      endInfo: '1'
    }
  },
  { name: '文本-组装输出', enabled: false },
  { name: '脚本', enabled: false }
])

// 事件类型
const receiveEventType = ref('')
const sendEventType = ref('')
// 设备信息表单
const formDeviceInfo = reactive({
  protocol: '',
  deviceName: '',
  IP: '',
  targetPort: '',
  dataUpload: false,
  reconnect: false,
  acceptEnd: false,
  endInfo: ''
})
// 接收事件信息表单
const formEventInfo = reactive({
  deviceName: '',
  separator: '',
  lengthCompare: false,
  characterLength: '',
  tableData: []
})

// 发送事件信息表单
const formSendEventInfo = reactive({
  deviceName: '',
  separator: '',
  lengthCompare: false,
  characterLength: '',
  tableData: []
})

// 心跳管理信息表单
const formHeartBeatInfo = reactive({
  deviceName: '',
  separator: '',
  lengthCompare: false,
  characterLength: '',
  tableData: []
})

// 响应配置信息表单
const formResponseInfo = reactive({
  deviceName: '',
  separator: '',
  lengthCompare: false,
  characterLength: '',
  tableData: []
})

interface CommBar {
  label: string
  value: 'device' | 'receive' | 'send' | 'heartbeat' | 'response'
  icon: string
  iconSelected: string
}
const commBars: CommBar[] = [
  { label: '设备列表', value: 'device', icon: DeviceIcon, iconSelected: DeviceSelectedIcon },
  { label: '接收事件', value: 'receive', icon: ReceiveIcon, iconSelected: ReceiveSelectedIcon },
  { label: '发送事件', value: 'send', icon: SendIcon, iconSelected: SendSelectedIcon },
  {
    label: '心跳管理',
    value: 'heartbeat',
    icon: HeartbeatIcon,
    iconSelected: HeartbeatSelectedIcon
  },
  { label: '响应配置', value: 'response', icon: ResponseIcon, iconSelected: ResponseSelectedIcon }
]
const setActiveTab = (tab: SettingItem) => {
  deviceTab.value = ''
  activeTab.value = tab.value
  console.log(activeTab.value)
  if (activeTab.value === 'device') {
    Object.assign(deviceBars, deviceList)
  } else if (activeTab.value === 'receive') {
    Object.assign(deviceBars, receiveList)
  } else if (activeTab.value === 'send') {
    Object.assign(deviceBars, sendList)
  }
}

const selectDevice = (device: Device) => {
  deviceTab.value = device.name
  if (activeTab.value === 'device') {
    Object.assign(formDeviceInfo, device.info)
  } else if (activeTab.value === 'receive') {
    switch (device.name) {
      case '文本-协议解析':
        receiveEventType.value = 'textParse'
        break
      case '文本-协议组装':
        receiveEventType.value = 'textMake'
        break
      case '字节-协议组装':
        receiveEventType.value = 'byteMake'
        break
      case '脚本':
        receiveEventType.value = 'script'
        break
    }
  } else if (activeTab.value === 'send') {
    switch (device.name) {
      case '文本-直接输出':
        sendEventType.value = 'textParse'
        break
      case '文本-组装输出':
        sendEventType.value = 'textMake'
        break
      case '脚本':
        sendEventType.value = 'script'
        break
    }
  }
}

// 添加设备
const addDevice = () => {
  if (activeTab.value === 'device') {
    isDeviceDialog.value = !isDeviceDialog.value
  } else if (activeTab.value === 'receive') {
    isEventDialog.value = !isEventDialog.value
    eventDialogTitle.value = '接收事件'
  } else if (activeTab.value === 'send') {
    isEventDialog.value = !isEventDialog.value
    eventDialogTitle.value = '发送事件'
  }
  console.log(isDeviceDialog.value, 'isDeviceDialog.value')
}

const handleTableAdd = () => {
  if (activeTab.value === 'receive') {
    formEventInfo.tableData.push({
      num: formEventInfo.tableData.length + 1,
      name: 'output1',
      type: 'int',
      result: ''
    })
  } else if (activeTab.value === 'send') {
    formSendEventInfo.tableData.push({
      num: formSendEventInfo.tableData.length + 1,
      name: 'input',
      type: 'int',
      result: ''
    })
  } else if (activeTab.value === 'heartbeat') {
    formHeartBeatInfo.tableData.push({
      num: formHeartBeatInfo.tableData.length + 1,
      name: 'input',
      type: 'int',
      result: ''
    })
  }
}

// 接收事件内容
const receiveData = ref('')
// 发送事件内容
const sendData = ref('')
// 16进制显示
const hexDisplay = ref(true)

// 处理对话框关闭事件
const handleClose = () => {
  activeTab.value = ''
}
</script>

<style scoped lang="scss">
/* 弹框整体样式 */
.commManagement-container {
  position: relative;
  width: 100%;
  height: 766px;
  box-sizing: border-box;
  display: flex;
  .commManagement-siderBar {
    box-sizing: border-box;
    width: 120px;
    height: 100%;
    padding: 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .commManagement-sidebar-item {
      margin-bottom: 16px;
      height: 62px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-between;
    }
  }
  .commManagement-infoList {
    box-sizing: border-box;
    width: 252px;
    .commManagement-infoList-title {
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 50px;
      padding: 0 16px;
      font-size: 14px;
      font-weight: bold;
      .infoList-title-btn {
        width: 24px;
        height: 24px;
        background: #154ddd;
        border: none;
        color: #fff;
        font-size: 24px;
        text-align: center;
        line-height: 20px;
        border-radius: 50%;
        cursor: pointer;
      }
    }
    .commManagement-infoList-content {
      .commManagement-infoList-item {
        box-sizing: border-box;
        width: 100%;
        height: 32px;
        padding: 0 16px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;
      }
      .commManagement-infoList-item.active {
        background: #f2f2f7;
        span {
          color: #154ddd;
        }
      }
    }
  }
  .commManagement-content {
    flex: 1;
    box-sizing: border-box;
    padding: 16px 24px 24px;
    .device-select {
      color: #fff;
      :deep(.el-select__wrapper) {
        background: #303136;
        .el-select__selected-item {
          color: #fff;
        }
      }
    }
    .data-tabs {
      width: 100%;
      :deep(.el-tabs__item) {
        color: #fff;
      }
      :deep(.fixed-height-textarea) {
        margin-bottom: 8px;
        height: 110px !important;
        min-height: 110px !important;
        max-height: 110px !important;
        .el-textarea__inner {
          height: 110px !important;
          background: #303136;
          color: #fff;
        }
      }
    }
    .form-device-btn {
      width: 80px;
      padding: 0 12px;
    }
    .event-table {
      .eventList-table {
        width: 100%;
        height: 224px;
        background: #363940;
      }
      .table-add-btn {
        box-sizing: border-box;
        width: 128px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    }
  }
  .commManagement-line-first,
  .commManagement-line-second {
    position: absolute;
    left: 120px;
    width: 1px;
    height: 100vh;
    background-color: #fff;
    opacity: 0.3;
  }
  .commManagement-line-second {
    left: 372px;
  }
}
</style>
