<template>
  <div>
    <div class="gva-search-box">
      <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
        <el-form-item label="预设名称">
          <el-input v-model="searchInfo.name" placeholder="搜索预设名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
      <div class="gva-btn-list">
        <el-button type="primary" @click="openDialog">新增</el-button>
        <el-button type="success" @click="openImportDialog">导入预设</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="ID" prop="ID" width="80" />
        <el-table-column label="名称" prop="name" width="200" show-overflow-tooltip />
        <el-table-column label="描述" prop="description" min-width="250" show-overflow-tooltip />
        <el-table-column label="Temperature" prop="temperature" width="120" />
        <el-table-column label="Max Tokens" prop="max_tokens" width="120" />
        <el-table-column label="提示词数量" width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.prompts?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="正则脚本" width="100">
          <template #default="scope">
            <el-tag type="warning">{{ scope.row.regex_scripts?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="enabled" width="80">
          <template #default="scope">
            <el-switch v-model="scope.row.enabled" @change="handleStatusChange(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="CreatedAt" width="180">
          <template #default="scope">{{ formatDate(scope.row.CreatedAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button type="primary" link @click="viewPreset(scope.row)">查看</el-button>
            <el-button type="success" link @click="updatePreset(scope.row)">编辑</el-button>
            <el-button type="info" link @click="exportPreset(scope.row)">导出</el-button>
            <el-button type="danger" link @click="deletePreset(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="type === 'create' ? '新增预设' : '编辑预设'"
      width="900px"
    >
      <el-form ref="presetForm" :model="formData" :rules="rules" label-width="140px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入预设名称" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入预设描述"
          />
        </el-form-item>
        <el-form-item label="Temperature" prop="temperature">
          <el-slider v-model="formData.temperature" :min="0" :max="2" :step="0.1" show-input />
        </el-form-item>
        <el-form-item label="Top P" prop="top_p">
          <el-slider v-model="formData.top_p" :min="0" :max="1" :step="0.1" show-input />
        </el-form-item>
        <el-form-item label="Max Tokens" prop="max_tokens">
          <el-input-number v-model="formData.max_tokens" :min="1" :max="200000" />
        </el-form-item>
        <el-form-item label="Frequency Penalty" prop="frequency_penalty">
          <el-slider
            v-model="formData.frequency_penalty"
            :min="-2"
            :max="2"
            :step="0.1"
            show-input
          />
        </el-form-item>
        <el-form-item label="Presence Penalty" prop="presence_penalty">
          <el-slider
            v-model="formData.presence_penalty"
            :min="-2"
            :max="2"
            :step="0.1"
            show-input
          />
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="formData.enabled" />
        </el-form-item>
        <el-form-item label="提示词配置">
          <el-button type="primary" size="small" @click="openPromptEditor">编辑提示词</el-button>
          <span style="margin-left: 10px; color: #909399">
            当前提示词数量: {{ formData.prompts?.length || 0 }}
          </span>
        </el-form-item>
        <el-form-item label="正则脚本">
          <el-button type="warning" size="small" @click="openRegexEditor">编辑正则脚本</el-button>
          <span style="margin-left: 10px; color: #909399">
            当前脚本数量: {{ formData.regex_scripts?.length || 0 }}
          </span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="enterDialog">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入预设对话框 -->
    <el-dialog v-model="importDialogVisible" title="导入预设" width="700px">
      <el-alert
        title="支持导入 SillyTavern 格式的预设 JSON 文件"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-tabs v-model="importTabActive">
        <el-tab-pane label="文件上传" name="file">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :limit="1"
            accept=".json"
            drag
            :on-change="handleFileChange"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将 JSON 文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只支持 .json 格式的预设文件
              </div>
            </template>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="JSON 粘贴" name="json">
          <el-input
            v-model="importJson"
            type="textarea"
            :rows="15"
            placeholder="请粘贴预设 JSON 内容"
          />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImport">导入</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 提示词编辑器 -->
    <PromptEditor
      v-model="promptEditorVisible"
      :prompts="formData.prompts"
      @save="handlePromptSave"
    />

    <!-- 正则脚本编辑器 -->
    <RegexEditor
      v-model="regexEditorVisible"
      :regex-scripts="formData.regex_scripts"
      @save="handleRegexSave"
    />

    <!-- 查看预设对话框 -->
    <el-dialog v-model="viewDialogVisible" title="预设详情" width="900px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="名称">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="viewData.enabled ? 'success' : 'danger'">
            {{ viewData.enabled ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="Temperature">{{ viewData.temperature }}</el-descriptions-item>
        <el-descriptions-item label="Top P">{{ viewData.top_p }}</el-descriptions-item>
        <el-descriptions-item label="Max Tokens">{{ viewData.max_tokens }}</el-descriptions-item>
        <el-descriptions-item label="Frequency Penalty">
          {{ viewData.frequency_penalty }}
        </el-descriptions-item>
        <el-descriptions-item label="Presence Penalty">
          {{ viewData.presence_penalty }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(viewData.CreatedAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="描述" :span="2">
          {{ viewData.description }}
        </el-descriptions-item>
      </el-descriptions>
      <el-divider>提示词列表</el-divider>
      <el-table :data="viewData.prompts" style="width: 100%" max-height="300">
        <el-table-column label="名称" prop="name" width="150" />
        <el-table-column label="角色" prop="role" width="100" />
        <el-table-column label="内容" prop="content" show-overflow-tooltip />
        <el-table-column label="启用" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.enabled ? 'success' : 'info'">
              {{ scope.row.enabled ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-divider>正则脚本</el-divider>
      <el-table :data="viewData.regex_scripts" style="width: 100%" max-height="300">
        <el-table-column label="脚本名称" prop="scriptName" width="150" />
        <el-table-column label="正则表达式" prop="findRegex" show-overflow-tooltip />
        <el-table-column label="替换字符串" prop="replaceString" width="150" />
        <el-table-column label="启用" width="80">
          <template #default="scope">
            <el-tag :type="!scope.row.disabled ? 'success' : 'info'">
              {{ !scope.row.disabled ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import {
  getAiPresetList,
  createAiPreset,
  updateAiPreset,
  deleteAiPreset,
  importAiPreset,
  importAiPresetFile
} from '@/api/aiPreset'
import PromptEditor from './components/PromptEditor.vue'
import RegexEditor from './components/RegexEditor.vue'

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const searchInfo = reactive({ name: '' })

const dialogFormVisible = ref(false)
const importDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const type = ref('')
const presetForm = ref(null)
const importJson = ref('')
const viewData = ref({})
const importTabActive = ref('file')
const uploadRef = ref(null)
const uploadFile = ref(null)
const promptEditorVisible = ref(false)
const regexEditorVisible = ref(false)

const formData = ref({
  name: '',
  description: '',
  temperature: 1.0,
  frequency_penalty: 0,
  presence_penalty: 0,
  top_p: 0.9,
  top_k: 0,
  max_tokens: 4096,
  prompts: [],
  regex_scripts: [],
  extensions: {},
  enabled: true
})

const rules = reactive({
  name: [{ required: true, message: '请输入预设名称', trigger: 'blur' }]
})

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN')
}

const getTableData = async () => {
  const table = await getAiPresetList({
    page: page.value,
    pageSize: pageSize.value,
    ...searchInfo
  })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const onSubmit = () => {
  page.value = 1
  getTableData()
}

const onReset = () => {
  searchInfo.name = ''
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleStatusChange = async (row) => {
  const res = await updateAiPreset(row)
  if (res.code === 0) {
    ElMessage.success('状态更新成功')
  } else {
    row.enabled = !row.enabled
    ElMessage.error('状态更新失败')
  }
}

const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    name: '',
    description: '',
    temperature: 1.0,
    frequency_penalty: 0,
    presence_penalty: 0,
    top_p: 0.9,
    top_k: 0,
    max_tokens: 4096,
    prompts: [],
    regex_scripts: [],
    extensions: {},
    enabled: true
  }
}

const enterDialog = async () => {
  presetForm.value.validate(async (valid) => {
    if (valid) {
      let res
      if (type.value === 'create') {
        res = await createAiPreset(formData.value)
      } else {
        res = await updateAiPreset(formData.value)
      }
      if (res.code === 0) {
        ElMessage.success(type.value === 'create' ? '创建成功' : '更新成功')
        closeDialog()
        getTableData()
      }
    }
  })
}

const updatePreset = (row) => {
  type.value = 'update'
  formData.value = { ...row }
  dialogFormVisible.value = true
}

const viewPreset = (row) => {
  viewData.value = { ...row }
  viewDialogVisible.value = true
}

const deletePreset = (row) => {
  ElMessageBox.confirm('确定要删除该预设吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await deleteAiPreset({ ID: row.ID })
    if (res.code === 0) {
      ElMessage.success('删除成功')
      getTableData()
    }
  })
}

const openImportDialog = () => {
  importJson.value = ''
  uploadFile.value = null
  importTabActive.value = 'file'
  importDialogVisible.value = true
}

const handleFileChange = (file) => {
  uploadFile.value = file.raw
}

const handleImport = async () => {
  try {
    let res
    if (importTabActive.value === 'file') {
      // 文件上传导入
      if (!uploadFile.value) {
        ElMessage.warning('请选择要上传的文件')
        return
      }
      res = await importAiPresetFile(uploadFile.value)
    } else {
      // JSON 粘贴导入
      if (!importJson.value.trim()) {
        ElMessage.warning('请粘贴预设 JSON 内容')
        return
      }
      const data = JSON.parse(importJson.value)
      res = await importAiPreset(data)
    }
    if (res.code === 0) {
      ElMessage.success('导入成功')
      importDialogVisible.value = false
      getTableData()
    }
  } catch (error) {
    ElMessage.error('JSON 格式错误: ' + error.message)
  }
}

const exportPreset = (row) => {
  const dataStr = JSON.stringify(row, null, 2)
  const blob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `${row.name}.json`
  link.click()
  URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

const openPromptEditor = () => {
  promptEditorVisible.value = true
}

const handlePromptSave = (prompts) => {
  formData.value.prompts = prompts
  ElMessage.success('提示词已更新')
}

const openRegexEditor = () => {
  regexEditorVisible.value = true
}

const handleRegexSave = (regexScripts) => {
  formData.value.regex_scripts = regexScripts
  ElMessage.success('正则脚本已更新')
}

getTableData()
</script>

<style scoped>
.gva-search-box {
  padding: 20px;
  background: #fff;
  margin-bottom: 10px;
}

.gva-table-box {
  padding: 20px;
  background: #fff;
}

.gva-btn-list {
  margin-bottom: 10px;
}

.gva-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
