<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {
  GetSettings,
  GetSwaggerFiles,
  GetSwaggerServerURL,
  IsSwaggerServerRunning,
  ReadSwaggerFile,
  SaveSettings,
  SelectDirectory,
  StartSwaggerServer,
  StopSwaggerServer
} from '../../wailsjs/go/backend/App'

interface SwaggerFile {
  name: string
  path: string
  size: number
  modifiedTime: string
}

interface AppSettings {
  theme: string
  language: string
  notifications: boolean
  autoStart: boolean
  swaggerDir: string
}

const settings = reactive<AppSettings>({
  theme: 'light',
  language: 'zh-CN',
  notifications: true,
  autoStart: false,
  swaggerDir: ''
})

const swaggerFiles = ref<SwaggerFile[]>([])
const selectedFile = ref<SwaggerFile | null>(null)
const selectedSwaggerFile = ref<SwaggerFile | null>(null)
const fileContent = ref('')
const isLoading = ref(false)
const serverURL = ref('')
const isServerRunning = ref(false)

async function selectSwaggerDir() {
  try {
    const path = await SelectDirectory('选择 Swagger 目录', settings.swaggerDir)
    if (path) {
      settings.swaggerDir = path
      await loadSwaggerFiles()
      await saveSettings()
    }
  } catch (error) {
    console.error('Failed to select directory:', error)
  }
}

async function loadSwaggerFiles() {
  if (!settings.swaggerDir) {
    return
  }

  isLoading.value = true
  try {
    const files = await GetSwaggerFiles(settings.swaggerDir)
    swaggerFiles.value = files
  } catch (error) {
    console.error('Failed to load swagger files:', error)
    ElMessage.error('加载 Swagger 文件失败')
  } finally {
    isLoading.value = false
  }
}

async function saveSettings() {
  try {
    const currentSettings = await GetSettings() as any
    currentSettings.swaggerDir = settings.swaggerDir
    await SaveSettings(currentSettings)
    ElMessage.success('设置保存成功')
  } catch (error) {
    console.error('Failed to save settings:', error)
    ElMessage.error('设置保存失败')
  }
}

async function viewFile(file: SwaggerFile) {
  selectedFile.value = file
  isLoading.value = true
  try {
    const content = await ReadSwaggerFile(file.path)
    fileContent.value = content
  } catch (error) {
    console.error('Failed to read swagger file:', error)
    ElMessage.error('读取文件失败')
  } finally {
    isLoading.value = false
  }
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) {
    return bytes + ' B'
  } else if (bytes < 1024 * 1024) {
    return (bytes / 1024).toFixed(2) + ' KB'
  } else {
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

async function startSwaggerServer() {
  if (!settings.swaggerDir) {
    ElMessage.warning('请先配置 Swagger 目录')
    return
  }

  try {
    const url = await StartSwaggerServer(settings.swaggerDir)
    serverURL.value = url
    isServerRunning.value = true
    if (swaggerFiles.value.length > 0) {
      selectedSwaggerFile.value = swaggerFiles.value[0]
    }
    ElMessage.success(`Swagger 服务已启动: ${url}`)
  } catch (error) {
    console.error('Failed to start swagger server:', error)
    ElMessage.error('启动 Swagger 服务失败')
  }
}

async function stopSwaggerServer() {
  try {
    await StopSwaggerServer()
    serverURL.value = ''
    isServerRunning.value = false
    ElMessage.success('Swagger 服务已停止')
  } catch (error) {
    console.error('Failed to stop swagger server:', error)
    ElMessage.error('停止 Swagger 服务失败')
  }
}

async function checkServerStatus() {
  try {
    const running = await IsSwaggerServerRunning()
    isServerRunning.value = running
    if (running) {
      const url = await GetSwaggerServerURL()
      serverURL.value = url
    }
  } catch (error) {
    console.error('Failed to check server status:', error)
  }
}

function openSwaggerURL() {
  if (serverURL.value) {
    window.open(serverURL.value, '_blank')
  }
}

function updateServerURL() {
  if (serverURL.value && selectedSwaggerFile.value) {
    const baseUrl = serverURL.value.split('?')[0]
    serverURL.value = `${baseUrl}?file=${encodeURIComponent(selectedSwaggerFile.value.name)}`
  }
}

onMounted(async () => {
  try {
    const loadedSettings = await GetSettings() as any
    settings.theme = loadedSettings.theme
    settings.language = loadedSettings.language
    settings.notifications = loadedSettings.notifications
    settings.autoStart = loadedSettings.autoStart
    settings.swaggerDir = loadedSettings.swaggerDir || ''
    if (settings.swaggerDir) {
      await loadSwaggerFiles()
    }
    await checkServerStatus()
  } catch (error) {
    console.error('Failed to load settings:', error)
  }
})
</script>

<template>
  <div class="swagger-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>Swagger 设置</span>
        </div>
      </template>
      <el-form label-width="140px" class="settings-form">
        <el-form-item label="Swagger 目录">
          <el-input
              v-model="settings.swaggerDir"
              placeholder="请输入或选择 Swagger 文件目录"
              clearable
          >
            <template #append>
              <el-button @click="selectSwaggerDir">选择文件夹</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="Swagger 服务">
          <div class="server-controls">
            <el-button
                v-if="!isServerRunning"
                type="primary"
                @click="startSwaggerServer"
            >
              启动服务
            </el-button>
            <el-button
                v-else
                type="danger"
                @click="stopSwaggerServer"
            >
              停止服务
            </el-button>
            <el-select
                v-if="isServerRunning && swaggerFiles.length > 1"
                v-model="selectedSwaggerFile"
                placeholder="选择 Swagger 文件"
                class="file-select"
                @change="updateServerURL"
            >
              <el-option
                  v-for="file in swaggerFiles"
                  :key="file.name"
                  :label="file.name"
                  :value="file"
              />
            </el-select>
            <el-input
                v-if="serverURL"
                v-model="serverURL"
                readonly
                class="server-url-input"
            >
              <template #append>
                <el-button @click="openSwaggerURL">打开</el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="files-card">
      <template #header>
        <div class="card-header">
          <span>Swagger 文件列表</span>
          <el-button type="primary" size="small" @click="loadSwaggerFiles" :loading="isLoading">刷新</el-button>
        </div>
      </template>
      <el-table :data="swaggerFiles" style="width: 100%" v-loading="isLoading">
        <el-table-column prop="name" label="文件名" show-overflow-tooltip/>
        <el-table-column prop="size" label="大小" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="modifiedTime" label="修改时间" width="180"/>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="viewFile(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-if="swaggerFiles.length === 0 && !isLoading" description="暂无 Swagger 文件"/>
    </el-card>

    <el-card class="content-card" v-if="selectedFile">
      <template #header>
        <div class="card-header">
          <span>{{ selectedFile.name }}</span>
          <el-button size="small" @click="selectedFile = null">关闭</el-button>
        </div>
      </template>
      <div class="file-content" v-loading="isLoading">
        <pre>{{ fileContent }}</pre>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.swagger-container {
  padding: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.files-card {
  margin-bottom: 20px;
}

.content-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.settings-form {
  margin-top: 10px;
}

.server-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.server-url-input {
  width: 100%;
}

.file-select {
  width: 100%;
}

.file-content {
  max-height: 600px;
  overflow-y: auto;
}

.file-content pre {
  margin: 0;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
