<template>
  <div class="setting-container">
    <!-- 主容器 -->
    <el-card class="main-container" shadow="never">
      <!-- 搜索和操作栏 -->
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="search-form">
            <el-form-item label="配置组">
              <el-select v-model="queryParams.group_id" placeholder="请选择配置组" clearable style="width: 200px" @change="handleQuery">
                <el-option
                  v-for="group in groupList"
                  :key="group.id"
                  :label="group.name"
                  :value="group.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="关键词筛选">
              <el-input v-model="queryParams.key" placeholder="请输入关键词" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增配置
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
          </div>
        </div>
      </div>

      <!-- 配置列表 -->
      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="settingList"
          @selection-change="handleSelectionChange"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="名称" min-width="150" />
          <el-table-column prop="value" label="值" min-width="200" show-overflow-tooltip>
            <template #default="{ row }">
              <span v-if="row.type === 'bool'">{{ row.value ? '是' : '否' }}</span>
              <span v-else>{{ row.value }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeColor(row.type)">
                {{ row.type || '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="settingGroupID" label="配置组" width="150" />
          <el-table-column label="是否开放" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.open"
                @change="handleToggleOpen(row)"
                :disabled="toggleLoading === row.id"
              />
            </template>
          </el-table-column>
          <el-table-column prop="note" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.CreatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.count"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
          class="pagination"
        />
      </div>
    </el-card>

    <!-- 配置表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="settingFormRef"
        :model="settingForm"
        :rules="settingRules"
        label-width="120px"
      >
        <el-form-item label="配置组" prop="settingGroupID">
          <el-select v-model="settingForm.settingGroupID" placeholder="请选择配置组" style="width: 100%">
            <el-option
              v-for="group in groupList"
              :key="group.id"
              :label="group.name"
              :value="group.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="settingForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="settingForm.type" placeholder="请选择类型" style="width: 100%" @change="handleTypeChange">
            <el-option label="字符串 (string)" value="string" />
            <el-option label="整数 (int)" value="int" />
            <el-option label="浮点数 (float)" value="float" />
            <el-option label="布尔值 (bool)" value="bool" />
          </el-select>
        </el-form-item>
        <el-form-item label="值" prop="value">
          <el-input
            v-if="settingForm.type === 'string'"
            v-model="settingForm.value"
            type="textarea"
            :rows="3"
            placeholder="请输入配置值"
          />
          <el-input-number
            v-else-if="settingForm.type === 'int'"
            v-model="settingForm.value"
            :controls="false"
            placeholder="请输入整数"
            style="width: 100%"
          />
          <el-input-number
            v-else-if="settingForm.type === 'float'"
            v-model="settingForm.value"
            :controls="false"
            :precision="2"
            placeholder="请输入浮点数"
            style="width: 100%"
          />
          <el-switch
            v-else-if="settingForm.type === 'bool'"
            v-model="settingForm.value"
          />
          <el-input
            v-else
            v-model="settingForm.value"
            placeholder="请输入配置值"
          />
        </el-form-item>
        <el-form-item label="是否开放访问">
          <el-switch v-model="settingForm.open" />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            开启后允许公开访问
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="settingForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {
  getSettingList,
  getSettingInfo,
  createSetting,
  updateSetting,
  setSettingOpen,
  deleteSetting
} from '@/api/admin/setting'
import { getSettingGroupList } from '@/api/admin/setting'

// 查询参数
const queryParams = reactive({
  group_id: undefined,
  key: '',
  page: 1,
  count: 10
})

// 配置表单
const settingForm = reactive({
  id: undefined,
  name: '',
  value: '',
  type: 'string',
  settingGroupID: undefined,
  open: false,
  note: ''
})

const settingRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  value: [
    { required: true, message: '请输入配置值', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择配置类型', trigger: 'change' }
  ],
  settingGroupID: [
    { required: true, message: '请选择配置组', trigger: 'change' }
  ]
}

// 状态数据
const loading = ref(false)
const settingList = ref([])
const groupList = ref([])
const total = ref(0)
const selectedRows = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新增配置')
const settingFormRef = ref(null)
const toggleLoading = ref(null)

// 格式化日期时间
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取类型颜色
const getTypeColor = (type) => {
  const colorMap = {
    'string': 'primary',
    'int': 'success',
    'float': 'warning',
    'bool': 'info'
  }
  return colorMap[type] || ''
}

// 获取配置组列表
const fetchGroupList = async () => {
  try {
    const res = await getSettingGroupList({ page: 1, count: 1000 })
    if (res.data.code === 200) {
      groupList.value = res.data.data.data || []
    }
  } catch (error) {
    console.error('获取配置组列表失败:', error)
  }
}

// 获取配置列表
const fetchSettingList = async () => {
  loading.value = true
  try {
    const params = { ...queryParams }
    if (!params.group_id) {
      delete params.group_id
    }
    const res = await getSettingList(params)
    console.log('配置列表数据:', res.data)
    if (res.data.code === 200) {
      settingList.value = res.data.data.data || []
      total.value = res.data.data.all_count || 0
    }
  } catch (error) {
    console.error('获取配置列表失败:', error)
    ElMessage.error('获取配置列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  fetchSettingList()
}

// 重置查询
const resetQuery = () => {
  queryParams.group_id = undefined
  queryParams.key = ''
  queryParams.page = 1
  fetchSettingList()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页
const handleSizeChange = (size) => {
  queryParams.count = size
  fetchSettingList()
}

const handleCurrentChange = (page) => {
  queryParams.page = page
  fetchSettingList()
}

// 类型变化
const handleTypeChange = (type) => {
  // 根据类型重置值
  if (type === 'bool') {
    settingForm.value = false
  } else if (type === 'int' || type === 'float') {
    settingForm.value = 0
  } else {
    settingForm.value = ''
  }
}

// 新增配置
const handleAdd = () => {
  dialogTitle.value = '新增配置'
  Object.assign(settingForm, {
    id: undefined,
    name: '',
    value: '',
    type: 'string',
    setting_group_id: undefined,
    open: false,
    note: ''
  })
  dialogVisible.value = true
}

// 编辑配置
const handleEdit = async (row) => {
  dialogTitle.value = '编辑配置'
  try {
    const res = await getSettingInfo({ id: row.id })
    console.log('配置详情数据:', res)
    if (res.data.code === 200) {
      const data = res.data.data
      Object.assign(settingForm, {
        id: data.id,
        name: data.name || '',
        value: data.value,
        type: data.type || 'string',
        settingGroupID: data.settingGroupID,
        open: data.open || false,
        note: data.note || ''
      })
      console.log('配置详情数据:', settingForm)
      // 根据类型转换值
      if (data.type === 'bool') {
        settingForm.value = data.value === true || data.value === 'true' || data.value === 1
      } else if (data.type === 'int') {
        settingForm.value = parseInt(data.value) || 0
      } else if (data.type === 'float') {
        settingForm.value = parseFloat(data.value) || 0
      }
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取配置详情失败:', error)
    ElMessage.error('获取配置详情失败')
  }
}

// 切换开放状态
const handleToggleOpen = async (row) => {
  toggleLoading.value = row.id
  try {
    const res = await setSettingOpen({
      id: row.id,
      open: row.open
    })
    if (res.data.code === 200) {
      ElMessage.success('修改成功')
    } else {
      // 恢复原状态
      row.open = !row.open
      ElMessage.error(res.data.message || '修改失败')
    }
  } catch (error) {
    // 恢复原状态
    row.open = !row.open
    console.error('修改失败:', error)
    ElMessage.error(error.response?.data?.message || '修改失败')
  } finally {
    toggleLoading.value = null
  }
}

// 删除配置
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除配置 "${row.name}" 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteSetting({ id: row.id })
      console.log('删除配置响应:', res.data)
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchSettingList()
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const deletePromises = selectedRows.value.map(row => 
        deleteSetting({ id: row.id })
      )
      await Promise.all(deletePromises)
      ElMessage.success('批量删除成功')
      fetchSettingList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  settingFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          name: settingForm.name,
          value: String(settingForm.value),
          type: settingForm.type,
          setting_group_id: settingForm.settingGroupID,
          open: settingForm.open,
          note: settingForm.note
        }
        if (settingForm.id) {
          submitData.id = settingForm.id
        }
        console.log('提交配置数据:', submitData)
        const res = settingForm.id 
          ? await updateSetting(submitData)
          : await createSetting(submitData)
        if (res.data.code === 200) {
          ElMessage.success(settingForm.id ? '修改成功' : '创建成功')
          dialogVisible.value = false
          fetchSettingList()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error(error.response?.data?.message || '提交失败')
      }
    }
  })
}

// 初始化
onMounted(() => {
  fetchGroupList()
  fetchSettingList()
})
</script>

<style scoped>
.setting-container {
  padding: 0;
}

.main-container {
  border: 1px solid #e1e8ed;
  background: #ffffff;
}

.filter-section {
  padding: 0;
  border-bottom: 1px solid #e1e8ed;
  background: #fafbfc;
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  gap: 20px;
  flex-wrap: wrap;
}

.search-form {
  margin: 0;
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 12px;
}

.action-bar {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-section {
  padding: 0;
}

.pagination {
  margin-top: 20px;
  padding: 16px 20px;
  border-top: 1px solid #e1e8ed;
  background: #fafbfc;
  justify-content: flex-end;
}

/* 表格样式优化 */
:deep(.el-table) {
  border: none;
  color: #2c3e50;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa !important;
  border-bottom: 2px solid #e1e8ed;
  color: #2c3e50;
  font-weight: 600;
  font-size: 13px;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f2f5;
  color: #34495e;
}

:deep(.el-table tr:hover > td) {
  background-color: #f8f9fa !important;
}

:deep(.el-card__body) {
  padding: 0;
}
</style>
