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

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

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

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

const swaggerFileInfo = ref<SwaggerFileInfo | null>(null)
const fileContent = ref('')
const isLoading = ref(false)
const serverURL = ref('')
const isServerRunning = ref(false)

async function selectSwaggerFile() {
  try {
    const path = await SelectFile('选择 Swagger 文件', settings.swaggerFilePath, '*.json')
    if (path) {
      settings.swaggerFilePath = path
      const fileInfo = await GetSwaggerFileInfo(path)
      if (fileInfo) {
        swaggerFileInfo.value = fileInfo
      }
      await saveSettings()
    }
  } catch (error) {
    console.error('Failed to select swagger file:', error)
  }
}

async function loadSwaggerFiles() {
  return
}

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

async function viewFile(file: SwaggerFileInfo) {
  swaggerFileInfo.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.swaggerFilePath) {
    ElMessage.warning('请先配置 Swagger 文件')
    return
  }

  try {
    const url = await StartSwaggerServer(settings.swaggerFilePath)
    serverURL.value = url
    isServerRunning.value = true
    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 && swaggerFileInfo.value) {
    const baseUrl = serverURL.value.split('?')[0]
    serverURL.value = `${baseUrl}?file=${encodeURIComponent(swaggerFileInfo.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.swaggerFilePath = loadedSettings.swaggerFilePath || ''
    if (settings.swaggerFilePath) {
      const fileInfo = await GetSwaggerFileInfo(settings.swaggerFilePath)
      if (fileInfo) {
        swaggerFileInfo.value = fileInfo
      }
    }
    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.swaggerFilePath"
              placeholder="请输入或选择 Swagger 文件"
              clearable
          >
            <template #append>
              <el-button @click="selectSwaggerFile">选择文件</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-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="content-card" v-if="swaggerFileInfo">
      <template #header>
        <div class="card-header">
          <span>{{ swaggerFileInfo.name }}</span>
          <el-button size="small" @click="swaggerFileInfo = null">关闭</el-button>
        </div>
      </template>
      <div class="info-content">
        <div class="file-info">
          <p><strong>文件路径：</strong>{{ swaggerFileInfo.path }}</p>
          <p><strong>文件大小：</strong>{{ formatFileSize(swaggerFileInfo.size) }}</p>
          <p><strong>修改时间：</strong>{{ swaggerFileInfo.modifiedTime }}</p>
        </div>
      </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>
