<template>
  <div class="remote-control-page">
    <!-- 顶部导航栏 -->
    <div class="page-header">
      <div class="header-left">
        <!-- <a-button type="text" @click="goBack">
          <template #icon><icon-left /></template>
          返回
        </a-button> -->
        <!-- <a-divider direction="vertical" /> -->
        <span class="server-name">{{ serverName }}</span>
        <a-tag :color="getStatusColor(serverStatus)" size="small">{{ getStatusText(serverStatus) }}</a-tag>
      </div>
      <div class="header-right">
        <a-button v-if="isConnected" size="small" @click="handleDisconnect">
          <template #icon><icon-poweroff /></template>
          断开连接
        </a-button>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="page-body">
      <!-- 左侧连接信息 -->
      <div v-if="!isConnected" class="connection-panel">
        <a-card title="SSH 远程连接" class="connection-card">
          <a-form :model="connectionForm" layout="vertical">
            <a-form-item label="连接协议">
              <a-radio-group v-model="connectionForm.protocol" type="button">
                <a-radio value="ssh">SSH</a-radio>
                <a-radio value="tat">免密连接</a-radio>
              </a-radio-group>
            </a-form-item>

            <a-row :gutter="16">
              <a-col :span="16">
                <a-form-item label="主机地址">
                  <a-input v-model="connectionForm.host" placeholder="IP或域名" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="端口">
                  <a-input-number v-model="connectionForm.port" :min="1" :max="65535" style="width: 100%" />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item label="用户名">
              <a-input v-model="connectionForm.username" placeholder="请输入用户名" />
            </a-form-item>

            <a-form-item label="密码">
              <a-input-password v-model="connectionForm.password" placeholder="请输入密码" />
            </a-form-item>

            <a-form-item>
              <a-button type="primary" long @click="handleConnect" :loading="connectLoading">
                <template #icon><icon-play-circle /></template>
                开始连接
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>

        <!-- 连接历史 -->
        <a-card title="连接历史" class="history-card">
          <a-list :bordered="false">
            <a-list-item v-for="(item, index) in connectionHistory" :key="index" @click="loadConnection(item)">
              <a-list-item-meta :title="item.name" :description="`${item.username}@${item.host}:${item.port}`" />
              <template #actions>
                <a-button type="text" size="small" @click.stop="removeHistory(index)">
                  <icon-delete />
                </a-button>
              </template>
            </a-list-item>
            <a-empty v-if="connectionHistory.length === 0" description="暂无连接记录" />
          </a-list>
        </a-card>
      </div>

      <!-- 右侧终端 -->
      <div class="terminal-panel" :class="{ 'full-width': isConnected }">
        <div class="terminal-header">
          <div class="terminal-info">
            <icon-desktop v-if="isConnected" style="color: #00b42a; margin-right: 8px;" />
            <icon-desktop v-else style="color: #86909c; margin-right: 8px;" />
            <span>{{ isConnected ? `已连接: ${connectionForm.username}@${connectionForm.host}` : '未连接' }}</span>
          </div>
          <a-space v-if="isConnected">
            <a-button size="small" @click="clearTerminal">
              <template #icon><icon-eraser /></template>
              清屏
            </a-button>
            <a-button size="small" @click="toggleFullscreen">
              <template #icon><icon-fullscreen /></template>
              {{ isFullscreen ? '退出全屏' : '全屏' }}
            </a-button>
          </a-space>
        </div>

        <div class="terminal-content" v-if="isConnected">
          <Terminal
            ref="terminalRef"
            :name="terminalName"
            :show-log-data="showLogData"
            @execCmd="onExecCmd"
            @onKeydown="onKeydown"
          />
        </div>
        <div v-else class="terminal-placeholder">
          <a-empty description="请先配置连接信息">
            <template #image>
              <icon-desktop style="font-size: 48px; color: #86909c;" />
            </template>
          </a-empty>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { Terminal } from 'vue-web-terminal'
import {
  IconLeft,
  IconPlayCircle,
  IconDelete,
  IconDesktop,
  IconPoweroff,
  IconEraser,
  IconFullscreen,
} from '@arco-design/web-vue/es/icon'

const route = useRoute()
const router = useRouter()

// 服务器信息
const serverId = computed(() => route.query.id as string)
const serverName = computed(() => route.query.name as string || '远程控制')
const serverStatus = computed(() => route.query.status as string || 'offline')

// 连接状态
const isConnected = ref(false)
const connectLoading = ref(false)
const isFullscreen = ref(false)
const terminalRef = ref()

// 终端配置
const terminalName = ref('ssh-terminal')
const showLogData = ref(false)

// 连接表单
const connectionForm = ref({
  protocol: 'ssh',
  host: (route.query.ip as string) || '',
  port: 22,
  username: 'root',
  password: '',
})

// 连接历史（从 localStorage 读取）
const connectionHistory = ref<Array<{name: string, host: string, port: number, username: string}>>([])

onMounted(() => {
  const history = localStorage.getItem('ssh_connection_history')
  if (history) {
    connectionHistory.value = JSON.parse(history)
  }
})

const getStatusColor = (status?: string) => {
  const map: Record<string, string> = { online: 'green', offline: 'red', maintenance: 'orange' }
  return map[status || ''] || 'gray'
}

const getStatusText = (status?: string) => {
  const map: Record<string, string> = { online: '在线', offline: '离线', maintenance: '维护中' }
  return map[status || ''] || '-'
}

const handleConnect = async () => {
  if (!connectionForm.value.host || !connectionForm.value.username) {
    Message.warning('请填写完整信息')
    return
  }

  connectLoading.value = true

  // 模拟连接
  await new Promise(r => setTimeout(r, 1500))

  isConnected.value = true
  connectLoading.value = false

  // 显示欢迎信息
  if (terminalRef.value) {
    terminalRef.value.pushMessage({
      class: 'success',
      content: `Welcome to ${serverName.value}!`
    })
    terminalRef.value.pushMessage({
      class: 'success',
      content: `Connected to ${connectionForm.value.host}`
    })
    terminalRef.value.pushMessage({
      class: 'info',
      content: `Last login: ${new Date().toLocaleString()}`
    })
    terminalRef.value.pushMessage({
      class: 'info',
      content: ''
    })
    terminalRef.value.pushMessage({
      class: 'info',
      content: 'Type "help" for available commands.'
    })
  }

  // 保存连接历史
  saveConnectionHistory()

  Message.success('连接成功')
}

const saveConnectionHistory = () => {
  const newItem = {
    name: serverName.value,
    host: connectionForm.value.host,
    port: connectionForm.value.port,
    username: connectionForm.value.username,
  }

  // 去重并添加到开头
  connectionHistory.value = connectionHistory.value.filter(
    item => !(item.host === newItem.host && item.username === newItem.username)
  )
  connectionHistory.value.unshift(newItem)

  // 最多保存10条
  if (connectionHistory.value.length > 10) {
    connectionHistory.value = connectionHistory.value.slice(0, 10)
  }

  localStorage.setItem('ssh_connection_history', JSON.stringify(connectionHistory.value))
}

const loadConnection = (item: any) => {
  connectionForm.value.host = item.host
  connectionForm.value.port = item.port
  connectionForm.value.username = item.username
}

const removeHistory = (index: number) => {
  connectionHistory.value.splice(index, 1)
  localStorage.setItem('ssh_connection_history', JSON.stringify(connectionHistory.value))
}

// 终端命令处理
const onExecCmd = (key: string, command: string, success: boolean, terminalName: string) => {
  const cmd = command.trim()
  if (!cmd) return

  // 执行命令
  const commands: Record<string, () => void> = {
    help: () => {
      terminalRef.value.pushMessage({
        class: 'info',
        content: 'Available commands:'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  help    - Show this help message'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  ls      - List directory contents'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  pwd     - Print working directory'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  whoami  - Print current user'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  date    - Print system date'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  clear   - Clear terminal screen'
      })
      terminalRef.value.pushMessage({
        class: 'info',
        content: '  exit    - Disconnect from server'
      })
    },
    ls: () => {
      terminalRef.value.pushMessage({
        class: 'success',
        content: 'bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var'
      })
    },
    pwd: () => {
      terminalRef.value.pushMessage({
        class: 'success',
        content: '/root'
      })
    },
    whoami: () => {
      terminalRef.value.pushMessage({
        class: 'success',
        content: connectionForm.value.username
      })
    },
    date: () => {
      terminalRef.value.pushMessage({
        class: 'success',
        content: new Date().toString()
      })
    },
    clear: () => {
      terminalRef.value.clear()
    },
    exit: () => {
      handleDisconnect()
    }
  }

  if (commands[cmd]) {
    commands[cmd]()
  } else {
    terminalRef.value.pushMessage({
      class: 'error',
      content: `bash: ${cmd}: command not found`
    })
  }
}

const onKeydown = (key: string, event: KeyboardEvent) => {
  // 可以在这里处理特殊按键事件
}

const handleDisconnect = () => {
  isConnected.value = false
  Message.info('已断开连接')
}

const clearTerminal = () => {
  if (terminalRef.value) {
    terminalRef.value.clear()
  }
}

const toggleFullscreen = () => {
  const terminalContent = document.querySelector('.terminal-content')
  if (!document.fullscreenElement) {
    terminalContent?.requestFullscreen()
    isFullscreen.value = true
  } else {
    document.exitFullscreen()
    isFullscreen.value = false
  }
}

const goBack = () => {
  router.back()
}
</script>

<style scoped lang="less">
.remote-control-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f0f2f5;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 24px;
    background: #fff;
    border-bottom: 1px solid #e5e6eb;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .server-name {
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .page-body {
    flex: 1;
    display: flex;
    overflow: hidden;
    padding: 16px;
    gap: 16px;

    .connection-panel {
      width: 400px;
      display: flex;
      flex-direction: column;
      gap: 16px;
      overflow-y: auto;

      .connection-card {
        :deep(.arco-card-body) {
          padding: 20px;
        }
      }

      .history-card {
        flex: 1;

        :deep(.arco-list-item) {
          cursor: pointer;

          &:hover {
            background: #f7f8fa;
          }
        }
      }
    }

    .terminal-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      background: #1e1e1e;
      border-radius: 4px;
      overflow: hidden;

      &.full-width {
        width: 100%;
      }

      .terminal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        background: #2d2d2d;
        border-bottom: 1px solid #3a3a3a;

        .terminal-info {
          display: flex;
          align-items: center;
          color: #c9cdd4;
          font-size: 13px;
        }
      }

      .terminal-content {
        flex: 1;
        overflow: hidden;

        :deep(.t-window) {
          height: 100%;
        }

        .terminal-placeholder {
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }
  }
}
</style>
