<template>
  <div class="channel-management">
    <el-card>
      <template #header>
        <div class="search-section">
        <el-form :model="searchForm" label-width="120px" inline class="search-form">
          <div class="search-row">
            <el-form-item label="Channel ID:">
              <el-input v-model="searchForm.id" placeholder="支持精确查询" clearable style="width:160px" />
            </el-form-item>
            <el-form-item label="Channel 类型:">
              <el-select v-model="searchForm.type" clearable placeholder="全部" style="width:160px">
                <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t" />
              </el-select>
            </el-form-item>
            <el-form-item label="Channel 类别:">
              <el-input v-model="searchForm.category" placeholder="关键字" clearable style="width:160px" />
            </el-form-item>
            <el-form-item label="Channel 名称:">
              <el-input v-model="searchForm.name" placeholder="关键字" clearable style="width:160px" />
            </el-form-item>
          </div>
          <div class="search-row">
            <el-form-item label="Channel 子名称:">
              <el-input v-model="searchForm.subName" placeholder="关键字" clearable style="width:160px" />
            </el-form-item>
            <el-form-item label="跟进员工:">
              <el-input v-model="searchForm.owner" placeholder="员工姓名" clearable style="width:160px" />
            </el-form-item>
            <el-form-item label=" ">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </div>
        </el-form>
        <div class="action-row">
          <el-button type="primary" @click="openModal('create')"><el-icon><Plus /></el-icon>新建 Channel</el-button>
        </div>
        </div>
      </template>

      <el-table :data="tableData" stripe border style="width:100%">
        <el-table-column label="操作" width="200" fixed="left">
          <template #default="scope">
            <el-button type="text" size="small" @click="openModal('edit', scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="openModal('view', scope.row)">查看</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="Channel ID" width="120" align="center" />
        <el-table-column prop="type" label="类型" width="150" align="center" />
        <el-table-column prop="category" label="类别" width="190" />
        <el-table-column prop="name" label="名称" width="190" />
        <el-table-column label="子名称" width="160">
          <template #default="scope">
            <span :class="{ 'empty-text': !scope.row.subName }">{{ scope.row.subName || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="跟进员工" width="120" align="center">
          <template #default="scope">
            <span :class="{ 'empty-text': !scope.row.owner }">{{ scope.row.owner || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column prop="updateTime" label="更新时间" width="180" align="center" />
      </el-table>
    </el-card>

    <!-- 新建/编辑/查看弹窗 -->
    <el-dialog :title="modalTitle" v-model="modalVisible" width="560px" :close-on-click-modal="false">
      <el-form label-width="130px">
        <el-form-item v-if="modalMode !== 'create'" label="Channel ID">
          <el-input :value="form.id" disabled />
        </el-form-item>

        <!-- Channel 类型 -->
        <el-form-item label="Channel 类型" required>
          <div class="inline-field">
            <el-select v-model="form.type" placeholder="请选择类型" :disabled="isViewMode" @change="onTypeChange" style="flex:1">
              <el-option v-for="t in typeOptions" :key="t" :label="t" :value="t" />
            </el-select>
            <template v-if="!isViewMode">
              <el-button size="small" @click="openPanel('type', 'add')">新增</el-button>
              <el-button size="small" @click="openPanel('type', 'edit')">编辑</el-button>
            </template>
          </div>
          <div v-if="activePanel === 'type'" class="quick-panel">
            <el-input v-model="panelInput" :placeholder="panelMode === 'edit' ? '请输入新的内容' : '请输入新的类型'" size="small" />
            <el-button size="small" type="primary" @click="savePanel('type')">保存</el-button>
            <el-button size="small" @click="activePanel = ''">取消</el-button>
          </div>
        </el-form-item>

        <!-- Channel 类别 -->
        <el-form-item label="Channel 类别" required>
          <div class="inline-field">
            <el-select v-model="form.category" placeholder="请先选择类型" :disabled="isViewMode || !form.type" @change="onCategoryChange" style="flex:1">
              <el-option v-for="c in categoryOptions" :key="c" :label="c" :value="c" />
            </el-select>
            <template v-if="!isViewMode">
              <el-button size="small" @click="openPanel('category', 'add')">新增</el-button>
              <el-button size="small" @click="openPanel('category', 'edit')">编辑</el-button>
            </template>
          </div>
          <div v-if="activePanel === 'category'" class="quick-panel">
            <el-input v-model="panelInput" :placeholder="panelMode === 'edit' ? '请输入新的内容' : '请输入新的类别'" size="small" />
            <el-button size="small" type="primary" @click="savePanel('category')">保存</el-button>
            <el-button size="small" @click="activePanel = ''">取消</el-button>
          </div>
        </el-form-item>

        <!-- Channel 名称 -->
        <el-form-item label="Channel 名称" required>
          <div class="inline-field">
            <el-select v-model="form.name" placeholder="请先选择类别" :disabled="isViewMode || !form.category" style="flex:1">
              <el-option v-for="n in nameOptions" :key="n" :label="n" :value="n" />
            </el-select>
            <template v-if="!isViewMode">
              <el-button size="small" @click="openPanel('name', 'add')">新增</el-button>
              <el-button size="small" @click="openPanel('name', 'edit')">编辑</el-button>
            </template>
          </div>
          <div v-if="activePanel === 'name'" class="quick-panel">
            <el-input v-model="panelInput" :placeholder="panelMode === 'edit' ? '请输入新的内容' : '请输入新的名称'" size="small" />
            <el-button size="small" type="primary" @click="savePanel('name')">保存</el-button>
            <el-button size="small" @click="activePanel = ''">取消</el-button>
          </div>
        </el-form-item>

        <el-form-item label="Channel 子名称">
          <el-input v-model="form.subName" placeholder="请输入Channel 子名称" :disabled="isViewMode" />
        </el-form-item>
        <el-form-item label="跟进员工">
          <el-input v-model="form.owner" placeholder="请输入跟进员工姓名" :disabled="isViewMode" />
        </el-form-item>
      </el-form>
      <template v-if="!isViewMode" #footer>
        <span>
          <el-button @click="modalVisible = false">取消</el-button>
          <el-button type="primary" @click="submitModal">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

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

export default {
  name: 'ChannelManagement',
  data() {
    return {
      searchForm: { id: '', type: '', category: '', name: '', subName: '', owner: '' },
      tableData: [],
      channelDict: {},
      modalVisible: false,
      modalMode: 'create',
      form: { id: '', type: '', category: '', name: '', subName: '', owner: '' },
      activePanel: '',
      panelMode: 'add',
      panelInput: ''
    }
  },
  computed: {
    modalTitle() {
      return this.modalMode === 'create' ? '新建 Channel' : this.modalMode === 'edit' ? '编辑 Channel' : '查看 Channel'
    },
    isViewMode() {
      return this.modalMode === 'view'
    },
    typeOptions() {
      return Object.keys(this.channelDict)
    },
    categoryOptions() {
      if (!this.form.type || !this.channelDict[this.form.type]) return []
      return Object.keys(this.channelDict[this.form.type])
    },
    nameOptions() {
      if (!this.form.type || !this.form.category) return []
      return (this.channelDict[this.form.type] || {})[this.form.category] || []
    }
  },
  created() {
    this.fetchDict()
    this.fetchList()
  },
  methods: {
    async fetchDict() {
      const res = await request.get('/api/channel/dict')
      this.channelDict = res.data
    },
    async fetchList() {
      const res = await request.get('/api/channel/list', { params: this.searchForm })
      this.tableData = res.data
    },
    handleSearch() { this.fetchList() },
    handleReset() {
      this.searchForm = { id: '', type: '', category: '', name: '', subName: '', owner: '' }
      this.fetchList()
    },
    async handleDelete(row) {
      await ElMessageBox.confirm('您确定要删除此条数据吗？删除后将无法恢复。', '确认删除', { type: 'warning', confirmButtonText: '确认删除', cancelButtonText: '取消' })
      await request.post('/api/channel/delete', { id: row.id })
      ElMessage.success('删除成功')
      this.fetchList()
    },
    openModal(mode, row) {
      this.modalMode = mode
      this.activePanel = ''
      this.panelInput = ''
      if (mode === 'create') {
        this.form = { id: '', type: '', category: '', name: '', subName: '', owner: '' }
      } else {
        this.form = { ...row }
      }
      this.modalVisible = true
    },
    onTypeChange() {
      this.form.category = ''
      this.form.name = ''
    },
    onCategoryChange() {
      this.form.name = ''
    },
    openPanel(target, mode) {
      if (target === 'category' && !this.form.type) {
        ElMessage.warning('请先选择 Channel 类型')
        return
      }
      if (target === 'name' && (!this.form.type || !this.form.category)) {
        ElMessage.warning('请先选择 Channel 类型和类别')
        return
      }
      if (mode === 'edit') {
        if (target === 'type' && !this.form.type) { ElMessage.warning('请先选择要编辑的类型'); return }
        if (target === 'category' && !this.form.category) { ElMessage.warning('请先选择要编辑的类别'); return }
        if (target === 'name' && !this.form.name) { ElMessage.warning('请先选择要编辑的名称'); return }
      }
      this.activePanel = target
      this.panelMode = mode
      this.panelInput = mode === 'edit'
        ? (target === 'type' ? this.form.type : target === 'category' ? this.form.category : this.form.name)
        : ''
    },
    async savePanel(target) {
      const value = this.panelInput.trim()
      if (!value) { ElMessage.warning('请输入内容'); return }
      const oldValue = target === 'type' ? this.form.type : target === 'category' ? this.form.category : this.form.name
      const existingValues = this.getPanelExistingValues(target)
      const exists = existingValues.some(item => item === value)
      if (this.panelMode === 'add' && exists) {
        ElMessage.warning(`${this.getPanelTargetName(target)}已存在，不能重复新增`)
        return
      }
      if (this.panelMode === 'edit' && value !== oldValue && exists) {
        ElMessage.warning(`${this.getPanelTargetName(target)}已存在，不能修改为重复值`)
        return
      }
      const res = await request.post('/api/channel/dict/save', {
        target,
        type: this.form.type,
        category: this.form.category,
        oldValue,
        newValue: value,
        mode: this.panelMode
      })
      this.channelDict = res.data
      if (this.panelMode === 'add') {
        if (target === 'type') this.form.type = value
        else if (target === 'category') this.form.category = value
        else this.form.name = value
      } else {
        if (target === 'type') this.form.type = value
        else if (target === 'category') this.form.category = value
        else this.form.name = value
      }
      this.activePanel = ''
      ElMessage.success(this.panelMode === 'add' ? '新增成功' : '编辑成功')
      this.fetchList()
    },
    getPanelExistingValues(target) {
      if (target === 'type') return Object.keys(this.channelDict)
      if (target === 'category') return Object.keys(this.channelDict[this.form.type] || {})
      return ((this.channelDict[this.form.type] || {})[this.form.category] || [])
    },
    getPanelTargetName(target) {
      if (target === 'type') return 'Channel 类型'
      if (target === 'category') return 'Channel 类别'
      return 'Channel 名称'
    },
    async submitModal() {
      if (!this.form.type || !this.form.category || !this.form.name) {
        ElMessage.warning('请完整选择类型、类别和名称')
        return
      }
      await request.post('/api/channel/save', this.form)
      ElMessage.success(this.modalMode === 'create' ? '新建成功' : '保存成功')
      this.modalVisible = false
      this.fetchList()
    }
  }
}
</script>

<style scoped>
.search-form .search-row { display: flex; flex-wrap: wrap; margin-bottom: 0; }
.search-section .action-row { margin-top: 15px; }
.empty-text { color: #c0c4cc; }

.inline-field { display: flex; gap: 8px; align-items: center; width: 100%; }
.inline-field :deep(.el-select) { flex: 1; min-width: 0; }
.quick-panel {
  display: flex; gap: 8px; align-items: center;
  margin-top: 8px; padding: 10px;
  background: #f0f7ff; border: 1px solid #d9ecff; border-radius: 4px;
}
</style>
