<template>
  <div class="remote-control">
    <!-- 顶部栏 -->
    <div class="header">
      <div class="header-left">
        <span class="title">{{ record.name || '远程控制' }}</span>
        <a-tag :color="getStatusColor(record.status)" size="small">{{ getStatusText(record.status) }}</a-tag>
      </div>
      <a-button size="small" @click="handleClose">
        <template #icon><icon-close /></template>
        关闭
      </a-button>
    </div>

    <!-- 登录界面 -->
    <div v-if="!isConnected" class="login-box">
      <a-card title="SSH 登录" class="login-card">
        <a-form :model="loginForm" layout="vertical">
          <a-form-item label="连接协议">
            <a-radio-group v-model="loginForm.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="loginForm.host" placeholder="IP或域名" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="端口">
                <a-input-number v-model="loginForm.port" :min="1" :max="65535" style="width: 100%" />
              </a-form-item>
            </a-col>
          </a-row>

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

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

          <a-space>
            <a-button type="primary" @click="handleLogin" :loading="loginLoading">连接</a-button>
            <a-button @click="handleClose">取消</a-button>
          </a-space>
        </a-form>
      </a-card>
    </div>

    <!-- 终端界面 -->
    <div v-else class="terminal-box">
      <div class="terminal-toolbar">
        <span class="terminal-info">已连接: {{ loginForm.username }}@{{ loginForm.host }}:{{ loginForm.port }}</span>
        <a-space>
          <a-button size="small" @click="handleDisconnect">断开</a-button>
          <a-button size="small" @click="handleFullscreen">全屏</a-button>
        </a-space>
      </div>
      <div class="terminal-content" ref="terminalRef">
        <div v-for="(line, index) in terminalLines" :key="index" class="terminal-line">
          <span v-if="line.type === 'input'" class="prompt">{{ line.prompt }}</span>
          <span :class="line.type">{{ line.content }}</span>
        </div>
        <div class="terminal-input">
          <span class="prompt">{{ prompt }}</span>
          <input ref="inputRef" v-model="currentInput" @keyup.enter="handleCommand" class="command-input" spellcheck="false" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconClose } from '@arco-design/web-vue/es/icon'

interface Props {
  record: any
}

const props = defineProps<Props>()
const emit = defineEmits(['close'])

const isConnected = ref(false)
const loginLoading = ref(false)
const terminalRef = ref<HTMLElement>()
const inputRef = ref<HTMLInputElement>()

const loginForm = ref({
  protocol: 'ssh',
  host: props.record?.ip || '',
  port: 22,
  username: 'root',
  password: '',
})

const terminalLines = ref<Array<{ type: string; content: string; prompt?: string }>>([
  { type: 'output', content: `Welcome to ${props.record?.name || 'Server'}!` },
  { type: 'output', content: `Last login: ${new Date().toLocaleString()}` },
])

const currentInput = ref('')
const prompt = computed(() => `${loginForm.value.username}@${loginForm.value.host}:~# `)

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 handleLogin = async () => {
  if (!loginForm.value.host || !loginForm.value.username) {
    Message.warning('请填写完整信息')
    return
  }
  loginLoading.value = true
  await new Promise((r) => setTimeout(r, 1000))
  isConnected.value = true
  loginLoading.value = false
  Message.success('连接成功')
  nextTick(() => inputRef.value?.focus())
}

const handleCommand = () => {
  const cmd = currentInput.value.trim()
  if (!cmd) return

  terminalLines.value.push({ type: 'input', content: cmd, prompt: prompt.value })

  const commands: Record<string, string> = {
    help: '可用命令: help, ls, pwd, whoami, date, clear, exit',
    ls: 'bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var',
    pwd: '/root',
    whoami: loginForm.value.username,
    date: new Date().toString(),
  }

  if (cmd === 'clear') {
    terminalLines.value = []
  } else if (cmd === 'exit') {
    handleDisconnect()
  } else {
    terminalLines.value.push({ type: 'output', content: commands[cmd] || `命令未找到: ${cmd}` })
  }

  currentInput.value = ''
  nextTick(() => {
    terminalRef.value?.scrollTo(0, terminalRef.value.scrollHeight)
  })
}

const handleDisconnect = () => {
  isConnected.value = false
  terminalLines.value = [
    { type: 'output', content: `Welcome to ${props.record?.name || 'Server'}!` },
    { type: 'output', content: `Last login: ${new Date().toLocaleString()}` },
  ]
  Message.info('已断开连接')
}

const handleFullscreen = () => {
  if (!document.fullscreenElement) {
    terminalRef.value?.requestFullscreen()
  } else {
    document.exitFullscreen()
  }
}

const handleClose = () => {
  emit('close')
}

onMounted(() => {
  if (props.record?.ip) {
    loginForm.value.host = props.record.ip
  }
})
</script>

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

  .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;

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

  .login-box {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24px;

    .login-card {
      width: 480px;
    }
  }

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

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

      .terminal-info {
        color: #c9cdd4;
        font-size: 13px;
      }
    }

    .terminal-content {
      flex: 1;
      padding: 16px;
      overflow-y: auto;
      font-family: 'Consolas', 'Monaco', monospace;
      font-size: 14px;
      line-height: 1.6;

      .terminal-line {
        margin-bottom: 4px;
        color: #fff;

        .prompt {
          color: #00ff00;
          margin-right: 8px;
        }

        &.input {
          color: #fff;
        }

        &.output {
          color: #c9cdd4;
        }
      }

      .terminal-input {
        display: flex;
        align-items: center;

        .prompt {
          color: #00ff00;
          margin-right: 8px;
          white-space: nowrap;
        }

        .command-input {
          flex: 1;
          background: transparent;
          border: none;
          outline: none;
          color: #fff;
          font-family: inherit;
          font-size: inherit;
          caret-color: #00ff00;
        }
      }
    }
  }
}
</style>
