<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>
      </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" />
        <el-table-column label="预设" width="200">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.preset?.name || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提供商" width="200">
          <template #default="scope">
            <el-tag type="primary">{{ scope.row.provider?.name || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提供商类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeColor(scope.row.provider?.type)">
              {{ scope.row.provider?.type || '-' }}
            </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="200">
          <template #default="scope">
            <el-button type="primary" link @click="updateBinding(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="deleteBinding(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="600px"
    >
      <el-form ref="bindingForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="绑定名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入绑定名称" clearable />
        </el-form-item>
        <el-form-item label="选择预设" prop="preset_id">
          <el-select
            v-model="formData.preset_id"
            placeholder="请选择预设"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="preset in presetList"
              :key="preset.ID"
              :label="preset.name"
              :value="preset.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择提供商" prop="provider_id">
          <el-select
            v-model="formData.provider_id"
            placeholder="请选择提供商"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="provider in providerList"
              :key="provider.ID"
              :label="`${provider.name} (${provider.type})`"
              :value="provider.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="启用" prop="enabled">
          <el-switch v-model="formData.enabled" />
        </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>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAiPresetBindingList,
  createAiPresetBinding,
  updateAiPresetBinding,
  deleteAiPresetBinding
} from '@/api/aiPresetBinding'
import { getAiPresetList } from '@/api/aiPreset'
import { getAiProviderList } from '@/api/aiProvider'

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

const dialogFormVisible = ref(false)
const type = ref('')
const bindingForm = ref(null)
const formData = ref({
  name: '',
  preset_id: null,
  provider_id: null,
  enabled: true
})

const rules = reactive({
  name: [{ required: true, message: '请输入绑定名称', trigger: 'blur' }],
  preset_id: [{ required: true, message: '请选择预设', trigger: 'change' }],
  provider_id: [{ required: true, message: '请选择提供商', trigger: 'change' }]
})

const getTypeColor = (type) => {
  const colors = {
    openai: 'success',
    claude: 'warning',
    gemini: 'primary',
    other: 'info'
  }
  return colors[type] || 'info'
}

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

const getTableData = async () => {
  const table = await getAiPresetBindingList({
    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 loadPresetList = async () => {
  const res = await getAiPresetList({ page: 1, pageSize: 999 })
  if (res.code === 0) {
    presetList.value = res.data.list
  }
}

const loadProviderList = async () => {
  const res = await getAiProviderList({ page: 1, pageSize: 999 })
  if (res.code === 0) {
    providerList.value = res.data.list
  }
}

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 updateAiPresetBinding(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: '',
    preset_id: null,
    provider_id: null,
    enabled: true
  }
}

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

const updateBinding = (row) => {
  type.value = 'update'
  formData.value = {
    ID: row.ID,
    name: row.name,
    preset_id: row.preset_id,
    provider_id: row.provider_id,
    enabled: row.enabled
  }
  dialogFormVisible.value = true
}

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

onMounted(() => {
  getTableData()
  loadPresetList()
  loadProviderList()
})
</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>
