<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {
  AddDatabaseConfig,
  CheckGenPs1Exists,
  ExecuteGenPs1,
  GetSettings,
  ReadGoModModule,
  RemoveDatabaseConfig,
  SaveSettings,
  SelectDirectory,
  SelectFile,
  UpdateDatabaseConfig
} from '../../wailsjs/go/backend/App'

interface DatabaseConfig {
  name: string
  targetPath: string
  modelPackagePath: string
}

interface AppSettings {
  theme: string
  language: string
  notifications: boolean
  autoStart: boolean
  mysqlModelPath: string
  defaultQueryPackagePath: string
  databases: DatabaseConfig[]
}

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

const dbForm = reactive<DatabaseConfig>({
  name: '',
  targetPath: '',
  modelPackagePath: ''
})

const scriptForm = reactive({
  selectedDbName: '',
  output: ''
})

const isExecuting = ref(false)
const dialogVisible = ref(false)
const editingIndex = ref(-1)

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.mysqlModelPath = loadedSettings.mysqlModelPath
    settings.defaultQueryPackagePath = loadedSettings.defaultQueryPackagePath || ''
    if (loadedSettings.databases) {
      settings.databases = loadedSettings.databases
    }
  } catch (error) {
    console.error('Failed to load settings:', error)
  }
})

async function validatePath(path: string): Promise<boolean> {
  if (!path) {
    return false
  }

  try {
    const exists = await CheckGenPs1Exists(path)
    if (!exists) {
      ElMessage.warning('所选文件不是有效的 gen.ps1 文件')
    }
    return exists
  } catch (error) {
    console.error('Failed to check gen.ps1:', error)
    ElMessage.error('检查文件时出错')
    return false
  }
}

async function selectMysqlModelPath() {
  try {
    const path = await SelectFile('选择 gen.ps1 文件', settings.mysqlModelPath, '*.ps1')
    if (path) {
      const isValid = await validatePath(path)
      if (isValid) {
        settings.mysqlModelPath = path
        
        try {
          const modulePath = await ReadGoModModule(path)
          if (modulePath) {
            settings.defaultQueryPackagePath = modulePath
            ElMessage.success(`已自动读取 go.mod 中的 module: ${modulePath}`)
          }
        } catch (error) {
          console.error('Failed to read go.mod:', error)
        }
      }
    }
  } catch (error) {
    console.error('Failed to select file:', error)
  }
}

async function handlePathChange() {
  if (settings.mysqlModelPath) {
    await validatePath(settings.mysqlModelPath)
  }
}

async function saveSettings() {
  if (!settings.mysqlModelPath) {
    ElMessage.warning('请先设置 MySQL Model 路径')
    return
  }

  const isValid = await validatePath(settings.mysqlModelPath)
  if (!isValid) {
    return
  }

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

async function selectTargetPath() {
  try {
    const path = await SelectDirectory('选择生成文件目标路径', dbForm.targetPath)
    if (path) {
      dbForm.targetPath = path
    }
  } catch (error) {
    console.error('Failed to select directory:', error)
  }
}

function openAddDialog() {
  editingIndex.value = -1
  dbForm.name = ''
  dbForm.targetPath = ''
  dbForm.modelPackagePath = ''
  dialogVisible.value = true
}

function openEditDialog(index: number) {
  editingIndex.value = index
  const db = settings.databases[index]
  dbForm.name = db.name
  dbForm.targetPath = db.targetPath
  dbForm.modelPackagePath = db.modelPackagePath || ''
  dialogVisible.value = true
}

async function handleAddDb() {
  if (!dbForm.name) {
    ElMessage.warning('请输入数据库名称')
    return
  }

  if (!dbForm.targetPath) {
    ElMessage.warning('请选择目标路径')
    return
  }

  try {
    if (editingIndex.value === -1) {
      await AddDatabaseConfig(dbForm.name, dbForm.targetPath, dbForm.modelPackagePath)
      ElMessage.success('添加成功')
    } else {
      await UpdateDatabaseConfig(settings.databases[editingIndex.value].name, dbForm.name, dbForm.targetPath, dbForm.modelPackagePath)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false

    const loadedSettings = await GetSettings() as any
    settings.theme = loadedSettings.theme
    settings.language = loadedSettings.language
    settings.notifications = loadedSettings.notifications
    settings.autoStart = loadedSettings.autoStart
    settings.mysqlModelPath = loadedSettings.mysqlModelPath
    settings.defaultQueryPackagePath = loadedSettings.defaultQueryPackagePath || ''
    if (loadedSettings.databases) {
      settings.databases = loadedSettings.databases
    }
  } catch (error) {
    console.error('Failed to save database config:', error)
    ElMessage.error('保存失败')
  }
}

async function handleDeleteDb(index: number) {
  const db = settings.databases[index]
  try {
    await RemoveDatabaseConfig(db.name)
    ElMessage.success('删除成功')

    const loadedSettings = await GetSettings() as any
    settings.theme = loadedSettings.theme
    settings.language = loadedSettings.language
    settings.notifications = loadedSettings.notifications
    settings.autoStart = loadedSettings.autoStart
    settings.mysqlModelPath = loadedSettings.mysqlModelPath
    if (loadedSettings.databases) {
      settings.databases = loadedSettings.databases
    }
  } catch (error) {
    console.error('Failed to delete database config:', error)
    ElMessage.error('删除失败')
  }
}

async function executeScript() {
  if (!settings.mysqlModelPath) {
    ElMessage.warning('请先设置 MySQL Model 路径')
    return
  }

  if (!scriptForm.selectedDbName) {
    ElMessage.warning('请选择要执行的数据库')
    return
  }

  const isValid = await validatePath(settings.mysqlModelPath)
  if (!isValid) {
    return
  }

  const selectedDb = settings.databases.find(db => db.name === scriptForm.selectedDbName)
  if (!selectedDb) {
    ElMessage.warning('未找到数据库配置')
    return
  }

  isExecuting.value = true
  scriptForm.output = '正在执行脚本...'

  try {
    const output = await ExecuteGenPs1(settings.mysqlModelPath, scriptForm.selectedDbName, selectedDb.targetPath, selectedDb.modelPackagePath || '')
    scriptForm.output = output + '\n\n文件已复制到目标路径: ' + selectedDb.targetPath
    ElMessage.success('脚本执行成功')
  } catch (error) {
    console.error('Failed to execute script:', error)
    scriptForm.output = `执行失败: ${error}`
    ElMessage.error('脚本执行失败')
  } finally {
    isExecuting.value = false
  }
}
</script>

<template>
  <div class="mysql-model-container">
    <el-card class="script-card">
      <template #header>
        <div class="card-header">
          <span>生成 model&query 文件</span>
        </div>
      </template>
      <el-form label-width="140px" class="script-form">
        <el-form-item label="选择数据库">
          <el-select
              v-model="scriptForm.selectedDbName"
              placeholder="请选择要执行的数据库"
              clearable
          >
            <el-option
                v-for="db in settings.databases"
                :key="db.name"
                :label="db.name"
                :value="db.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="executeScript"
              :loading="isExecuting"
          >
            执行脚本
          </el-button>
        </el-form-item>
        <el-form-item label="执行输出">
          <el-input
              v-model="scriptForm.output"
              type="textarea"
              :rows="10"
              placeholder="脚本执行结果将显示在这里"
              readonly
          />
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="mysql-model-card">
      <template #header>
        <div class="card-header">
          <span>MySQL Model 设置</span>
        </div>
      </template>
      <el-form label-width="140px" class="settings-form">
        <el-form-item label="gen.ps1 路径">
          <el-input
              v-model="settings.mysqlModelPath"
              placeholder="请输入或选择 gen.ps1 文件路径"
              clearable
              @change="handlePathChange"
          >
            <template #append>
              <el-button @click="selectMysqlModelPath">选择文件</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="Query包名">
          <el-input
              v-model="settings.defaultQueryPackagePath"
              placeholder="请输入默认 Query 包名，例如：git.hlsq.asia/mmorpg/service-user/internal/dao/model"
              clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveSettings">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="database-card">
      <template #header>
        <div class="card-header">
          <span>数据库配置管理</span>
          <el-button type="primary" size="small" @click="openAddDialog">添加配置</el-button>
        </div>
      </template>
      <el-table :data="settings.databases" style="width: 100%">
        <el-table-column prop="name" label="数据库名称"/>
        <el-table-column prop="targetPath" label="目标路径" show-overflow-tooltip/>
        <el-table-column prop="modelPackagePath" label="Query包名" show-overflow-tooltip/>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.$index)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteDb(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
        v-model="dialogVisible"
        :title="editingIndex === -1 ? '添加数据库配置' : '编辑数据库配置'"
        width="500px"
    >
      <el-form label-width="120px">
        <el-form-item label="数据库名称">
          <el-input
              v-model="dbForm.name"
              placeholder="请输入数据库名称，例如：user_db"
              clearable
          />
        </el-form-item>
        <el-form-item label="目标路径">
          <el-input
              v-model="dbForm.targetPath"
              placeholder="请输入或选择生成文件的目标路径"
              clearable
          >
            <template #append>
              <el-button @click="selectTargetPath">选择文件夹</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="Query包名">
          <el-input
              v-model="dbForm.modelPackagePath"
              placeholder="请输入package name，例如：git.hlsq.asia/mmorpg/service-user/internal/dao/model"
              clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddDb">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

.mysql-model-card,
.database-card,
.script-card {
  max-width: 900px;
  margin: 20px auto;
}

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

.settings-form,
.script-form {
  padding: 20px 0;
}
</style>
