<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

// Active tab
const activeTab = ref('restart')

// Service data for restart tab
interface ServiceItem {
  name: string
  type: 'PYTHON' | 'JAVA' | 'DOCKER' | 'NGINX'
  upgradePath: string
  restartScript: string
}

const restartServices = ref<ServiceItem[]>([
  {
    name: '运维系统',
    type: 'PYTHON',
    upgradePath: '/data/services/api/python-cmdb/cmdb',
    restartScript: '/var/www/html/start.sh',
  },
  {
    name: '预定系统2.0',
    type: 'JAVA',
    upgradePath: '/data/services/api/java-meeting/java-meeting2.0/ubains-meeting-inner-api-1.0-SNAPSHOT.jar',
    restartScript: '/var/www/java/api/java-meeting/java-meeting2.0/run.sh',
  },
  {
    name: '消息调度服务',
    type: 'JAVA',
    upgradePath: '/data/services/api/java-meeting/java-message-scheduling/ubains-meeting-message-scheduling-1.0-SNAPSHOT.jar',
    restartScript: '/var/www/java/api/java-meeting/java-message-scheduling/run.sh',
  },
])

// Service data for rollback tab
interface RollbackItem {
  name: string
  type: 'PYTHON' | 'JAVA' | 'DOCKER' | 'NGINX'
  currentVersion: string
  rollbackVersion: string
}

const rollbackServices = ref<RollbackItem[]>([
  { name: '运维系统', type: 'PYTHON', currentVersion: 'v2.3.1', rollbackVersion: 'v2.3.0' },
  { name: '预定系统2.0', type: 'JAVA', currentVersion: 'v1.5.2', rollbackVersion: 'v1.5.1' },
])

// Selection
const selectedRestart = ref<string[]>([])
const selectedRollback = ref<string[]>([])

const hasRestartSelection = computed(() => selectedRestart.value.length > 0)
const hasRollbackSelection = computed(() => selectedRollback.value.length > 0)

function toggleRestartSelection(name: string) {
  const idx = selectedRestart.value.indexOf(name)
  if (idx >= 0) selectedRestart.value.splice(idx, 1)
  else selectedRestart.value.push(name)
}

function toggleAllRestart(checked: string | number | boolean) {
  selectedRestart.value = checked ? restartServices.value.map(s => s.name) : []
}

function isRestartSelected(name: string) {
  return selectedRestart.value.includes(name)
}

const isAllRestartSelected = computed(() =>
  restartServices.value.length > 0 && selectedRestart.value.length === restartServices.value.length
)

function toggleRollbackSelection(name: string) {
  const idx = selectedRollback.value.indexOf(name)
  if (idx >= 0) selectedRollback.value.splice(idx, 1)
  else selectedRollback.value.push(name)
}

function toggleAllRollback(checked: string | number | boolean) {
  selectedRollback.value = checked ? rollbackServices.value.map(s => s.name) : []
}

function isRollbackSelected(name: string) {
  return selectedRollback.value.includes(name)
}

const isAllRollbackSelected = computed(() =>
  rollbackServices.value.length > 0 && selectedRollback.value.length === rollbackServices.value.length
)

// Type badge
function typeClass(type: string) {
  return `type-${type.toLowerCase()}`
}

// Actions
function handleAction(action: string, serviceName?: string) {
  ElMessage.info(`${action} 功能开发中，敬请期待${serviceName ? ' - ' + serviceName : ''}`)
}
</script>

<template>
  <div class="page-upgrade">
    <div class="section-head">
      <h1 class="section-title">⬆️ 服务升级</h1>
    </div>

    <!-- Tabs -->
    <el-tabs v-model="activeTab">
      <!-- Tab: 服务重启 -->
      <el-tab-pane label="服务重启" name="restart">
        <div class="toolbar">
          <el-button @click="handleAction('download-config')">📥 下载配置</el-button>
          <el-button @click="handleAction('backup-db')">💾 备份数据库文件</el-button>
          <el-button type="primary" @click="handleAction('upload-update')">📤 上传更新服务</el-button>
          <el-button
            type="success"
            :disabled="!hasRestartSelection"
            @click="handleAction('restart-selected')"
          >
            🔄 重启已选服务
          </el-button>
          <el-button
            :disabled="!hasRestartSelection"
            @click="handleAction('download-logs')"
          >
            📋 下载日志
          </el-button>
        </div>

        <el-card class="table-card">
          <el-table :data="restartServices" style="width: 100%;">
            <el-table-column width="40">
              <template #header>
                <el-checkbox
                  :model-value="isAllRestartSelected"
                  @change="toggleAllRestart"
                />
              </template>
              <template #default="{ row }">
                <el-checkbox
                  :model-value="isRestartSelected(row.name)"
                  @change="toggleRestartSelection(row.name)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="服务名称" min-width="120">
              <template #default="{ row }">
                <span class="name-cell">{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="服务类型" width="120">
              <template #default="{ row }">
                <span class="service-type" :class="typeClass(row.type)">{{ row.type }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="upgradePath" label="升级路径" min-width="200">
              <template #default="{ row }">
                <span class="path-text">{{ row.upgradePath }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="restartScript" label="重启脚本路径" min-width="200">
              <template #default="{ row }">
                <span class="path-text">{{ row.restartScript }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160" fixed="right">
              <template #default="{ row }">
                <el-button size="small" class="btn-restart" @click="handleAction('restart', row.name)">重启</el-button>
                <el-button size="small" @click="handleAction('log', row.name)">下载日志</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- Tab: 服务回滚 -->
      <el-tab-pane label="服务回滚" name="rollback">
        <div class="toolbar">
          <el-button @click="handleAction('download-config')">📥 下载配置</el-button>
          <el-button
            type="primary"
            :disabled="!hasRollbackSelection"
            @click="handleAction('rollback-selected')"
          >
            ⏪ 回滚已选服务
          </el-button>
        </div>

        <el-card class="table-card">
          <el-table :data="rollbackServices" style="width: 100%;">
            <el-table-column width="40">
              <template #header>
                <el-checkbox
                  :model-value="isAllRollbackSelected"
                  @change="toggleAllRollback"
                />
              </template>
              <template #default="{ row }">
                <el-checkbox
                  :model-value="isRollbackSelected(row.name)"
                  @change="toggleRollbackSelection(row.name)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="服务名称" min-width="120">
              <template #default="{ row }">
                <span class="name-cell">{{ row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="服务类型" width="120">
              <template #default="{ row }">
                <span class="service-type" :class="typeClass(row.type)">{{ row.type }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="currentVersion" label="当前版本" width="120" />
            <el-table-column prop="rollbackVersion" label="回滚版本" width="120" />
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="{ row }">
                <el-button size="small" class="btn-restart" @click="handleAction('rollback', row.name)">回滚</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.page-upgrade {
  padding: 0 0 40px;
}

.section-head {
  margin-bottom: 20px;
}

.section-title {
  font-size: 20px;
  font-weight: 700;
  color: $gray-900;
}

.toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.name-cell {
  font-weight: 600;
  color: $gray-900;
}

.service-type {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.type-python { background: #e0f2fe; color: #0369a1; }
.type-java { background: #fef3c7; color: #92400e; }
.type-docker { background: #dbeafe; color: #1d4ed8; }
.type-nginx { background: #dcfce7; color: #166534; }

.path-text {
  font-family: monospace;
  font-size: 12px;
  color: $gray-600;
  word-break: break-all;
}

.btn-restart {
  background: #fef3c7;
  color: #d97706;
  border-color: #fef3c7;

  &:hover {
    background: #fde68a;
    color: #b45309;
    border-color: #fde68a;
  }
}

@media screen and (max-width: 768px) {
  .toolbar {
    gap: 8px;
  }

  .path-text {
    font-size: 11px;
  }
}
</style>