<template>
  <PageCard>
    <template #toolbar-left>
      <el-input
        v-model="searchQuery"
        placeholder="搜索标签名称"
        clearable
        style="width: 260px"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </template>
    <template #toolbar-right>
      <el-button type="primary" @click="openCreateDialog">新增标签</el-button>
    </template>

    <el-table :data="pagedTags" class="sino-table" @row-click="openDrawer">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="tagName" label="名称" />
      <el-table-column prop="tagPath" label="路径" show-overflow-tooltip />
      <el-table-column prop="level" label="层级" width="100">
        <template #default="{ row }">
          {{ formatLevel(row.level) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <div class="status-cell" @click.stop>
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val: any) => handleStatusChange(row, val)"
            />
            <span class="status-text">{{ row.status === 1 ? '启用' : '禁用' }}</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #pagination>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="filteredTags.length"
        layout="total, prev, pager, next"
        background
      />
    </template>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑标签' : '新增标签'" width="600px">
      <el-form :model="dialogForm" label-width="100px">
        <el-form-item label="标签名">
          <el-input v-model="dialogForm.tagName" placeholder="标签名" />
        </el-form-item>
        <el-form-item label="父标签">
          <el-select v-model="dialogForm.parentId" placeholder="选择父标签" style="width: 100%">
            <el-option label="无" :value="0" />
            <el-option
              v-for="t in tags"
              :key="t.id"
              :label="t.tagName"
              :value="t.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="dialogForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="drawerVisible" title="标签详情" size="480px">
      <el-form :model="dialogForm" label-width="100px">
        <el-form-item label="标签名">
          <el-input v-model="dialogForm.tagName" placeholder="标签名" />
        </el-form-item>
        <el-form-item label="父标签">
          <el-select v-model="dialogForm.parentId" placeholder="选择父标签" style="width: 100%">
            <el-option label="无" :value="0" />
            <el-option
              v-for="t in tags"
              :key="t.id"
              :label="t.tagName"
              :value="t.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="dialogForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="drawerVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete(currentRow)">删除</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-drawer>
  </PageCard>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { createTag, deleteTag, listTags, updateTag } from '@/api/crm'
import PageCard from '@/components/PageCard.vue'

const tags = ref<any[]>([])

const dialogVisible = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)

const dialogForm = reactive({
  tagName: '',
  parentId: 0,
  status: 1,
})

const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const drawerVisible = ref(false)
const currentRow = ref<any>({})

const filteredTags = computed(() => {
  const q = searchQuery.value.trim().toLowerCase()
  if (!q) return tags.value
  return tags.value.filter(
    (t) =>
      String(t.tagName || '').toLowerCase().includes(q) ||
      String(t.tagPath || '').toLowerCase().includes(q)
  )
})

const pagedTags = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredTags.value.slice(start, start + pageSize.value)
})

watch(searchQuery, () => {
  currentPage.value = 1
})

function resetDialogForm() {
  dialogForm.tagName = ''
  dialogForm.parentId = 0
  dialogForm.status = 1
}

function fillDialogForm(row: any) {
  dialogForm.tagName = row.tagName ?? ''
  dialogForm.parentId = row.parentId ?? 0
  dialogForm.status = row.status ?? 1
}

function openCreateDialog() {
  isEdit.value = false
  editingId.value = null
  resetDialogForm()
  dialogVisible.value = true
}

function openDrawer(row: any) {
  currentRow.value = row
  isEdit.value = true
  editingId.value = row.id
  fillDialogForm(row)
  drawerVisible.value = true
}

function formatLevel(level: number | undefined) {
  if (level == null) return '-'
  return `第 ${level} 级`
}

async function loadTags() {
  try {
    const res: any = await listTags()
    tags.value = res.data || []
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleSave() {
  if (!dialogForm.tagName) {
    ElMessage.warning('请填写标签名')
    return
  }
  try {
    const payload = {
      tagName: dialogForm.tagName,
      parentId: dialogForm.parentId,
      status: dialogForm.status,
    }
    if (isEdit.value && editingId.value != null) {
      await updateTag(editingId.value, payload)
      ElMessage.success('更新成功')
    } else {
      const res: any = await createTag(payload)
      tags.value.unshift(res.data)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    drawerVisible.value = false
    await loadTags()
  } catch (e: any) {
    ElMessage.error(e.message)
  }
}

async function handleStatusChange(row: any, val: any) {
  try {
    await updateTag(row.id, {
      tagName: row.tagName,
      parentId: row.parentId,
      status: val,
    })
    ElMessage.success('状态更新成功')
    await loadTags()
  } catch (e: any) {
    ElMessage.error(e.message)
    await loadTags()
  }
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm(
      `确定删除标签「${row.tagName}」吗？`,
      '删除确认',
      { confirmButtonText: '删除', cancelButtonText: '取消', type: 'warning' }
    )
    await deleteTag(row.id)
    ElMessage.success('删除成功')
    drawerVisible.value = false
    await loadTags()
  } catch (e: any) {
    if (e !== 'cancel') {
      ElMessage.error(e.message || '删除失败')
    }
  }
}

onMounted(loadTags)
</script>
