<template>
  <div class="tag-list">
    <el-card>
      <!-- 搜索区域 -->
      <template #header>
        <div class="search-section">
        <div class="search-row">
          <el-form :model="searchForm" label-width="90px" inline>
            <el-form-item label="标签名称:">
              <el-input v-model="searchForm.name" placeholder="请输入" clearable style="width: 160px" />
            </el-form-item>
            <el-form-item label="标签 ID:">
              <el-input v-model="searchForm.id" placeholder="请输入" clearable style="width: 180px" />
            </el-form-item>
            <el-form-item label="状态:">
              <el-select v-model="searchForm.status" clearable placeholder="全部" style="width: 120px">
                <el-option label="启用" value="enabled" />
                <el-option label="停用" value="disabled" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建人:">
              <el-input v-model="searchForm.creator" placeholder="请输入" clearable style="width: 140px" />
            </el-form-item>
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="searchForm.createdRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 260px"
              />
            </el-form-item>
            <div class="button-group">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-form>
        </div>
        <div class="action-row">
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>新建标签
          </el-button>
        </div>
        </div>
      </template>

      <!-- 表格 -->
      <el-table :data="pagedData" stripe style="width: 100%" border>
        <el-table-column label="操作" width="200" fixed="left">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              type="text"
              size="small"
              @click="handleToggle(scope.row)"
            >{{ scope.row.status === 'enabled' ? '停用' : '启用' }}</el-button>
            <el-button
              type="text"
              size="small"
              style="color: #F56C6C"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="标签 ID" width="160" />
        <el-table-column prop="name" label="标签名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="description" label="标签描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="规则摘要" width="110">
          <template #default="scope">
            {{ ruleSummary(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'info'" size="small">
              {{ scope.row.status === 'enabled' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="referenceCount" label="引用数" width="80" align="center" />
        <el-table-column prop="creator" label="创建人" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column prop="updater" label="最后更新人" width="110" />
        <el-table-column prop="updatedAt" label="更新时间" width="160" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <span class="total">共 {{ filteredData.length }} 条</span>
        <el-pagination
          layout="prev, pager, next, sizes, jumper"
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :page-sizes="[10, 20, 50]"
          :total="filteredData.length"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import tagStore from '@/store/tagStore'

export default {
  name: 'TagList',
  data() {
    return {
      searchForm: {
        name: '',
        id: '',
        status: '',
        creator: '',
        createdRange: []
      },
      page: { current: 1, size: 10 }
    }
  },
  computed: {
    filteredData() {
      return tagStore.query(this.searchForm)
    },
    pagedData() {
      const start = (this.page.current - 1) * this.page.size
      return this.filteredData.slice(start, start + this.page.size)
    }
  },
  methods: {
    ruleSummary(row) {
      const g = (row.groups || []).length
      const r = (row.groups || []).reduce((sum, gr) => sum + (gr.rules ? gr.rules.length : 0), 0)
      return `${g} 组 / ${r} 条`
    },
    handleSearch() {
      this.page.current = 1
    },
    handleReset() {
      this.searchForm = { name: '', id: '', status: '', creator: '', createdRange: [] }
      this.page.current = 1
    },
    handleCreate() {
      this.$router.push('/customization/hsbc/tags/add')
    },
    handleView(row) {
      this.$router.push(`/customization/hsbc/tags/view/${row.id}`)
    },
    handleEdit(row) {
      this.$router.push(`/customization/hsbc/tags/edit/${row.id}`)
    },
    handleToggle(row) {
      if (row.status === 'enabled') {
        ElMessageBox.confirm('停用后，引用该标签的业务将视为该客群不命中，确认停用？', '提示', { type: 'warning' })
          .then(() => {
            tagStore.toggleStatus(row.id)
            ElMessage.success('已停用')
          }).catch(() => {})
      } else {
        tagStore.toggleStatus(row.id)
        ElMessage.success('已启用')
      }
    },
    handleDelete(row) {
      if (row.referenceCount > 0) {
        ElMessageBox.alert(
          `该标签已被 ${row.referenceCount} 个权益/活动引用，请先在对应业务中解除引用后再删除`,
          '无法删除',
          { confirmButtonText: '我知道了', type: 'warning' }
        )
        return
      }
      ElMessageBox.confirm(`确定要删除标签「${row.name}」吗？删除后无法恢复`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        tagStore.remove(row.id)
        ElMessage.success('删除成功')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.tag-list { padding: 0; }

.search-section { display: flex; flex-direction: column; }
.search-row .el-form { display: flex; flex-wrap: wrap; gap: 8px 0; }
.search-row .el-form-item { margin-right: 8px; margin-bottom: 8px; }

.button-group { display: flex; gap: 5px; margin-top: 2px; }
.action-row { margin-top: 12px; }

.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}
.pagination-section .total { color: #606266; font-size: 13px; }
</style>
