<template>
  <div class="activity-mutex-group">
    <el-card>
      <template #header>
        <div class="search-section">
          <div class="search-row">
            <el-form :model="searchForm" inline label-width="90px">
              <el-form-item label="互斥组名称">
                <el-input v-model="searchForm.name" clearable placeholder="请输入" class="search-field" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="searchForm.status" clearable placeholder="全部" class="status-field">
                  <el-option label="启用" value="启用" />
                  <el-option label="停用" value="停用" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="operation-row">
            <el-button type="primary" @click="openDialog()">
              <el-icon><Plus /></el-icon>新增互斥组
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="pagedRows" stripe style="width:100%">
        <el-table-column label="操作" width="150" fixed="left">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="openDialog(row)">编辑</el-button>
            <el-button type="text" size="small" @click="toggleStatus(row)">{{ row.status === '启用' ? '停用' : '启用' }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="互斥组编号" width="120" />
        <el-table-column prop="name" label="互斥组名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="mutexType" label="互斥类型" width="120" />
        <el-table-column prop="businessType" label="业务类型" width="120" />
        <el-table-column prop="scopeType" label="互斥活动范围" width="130" />
        <el-table-column prop="activities" label="互斥活动" min-width="220" show-overflow-tooltip />
        <el-table-column label="判断依据" min-width="190">
          <template #default="{ row }">{{ basisText(row.judgeBasis) }}</template>
        </el-table-column>
        <el-table-column label="实时拦截" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.realtimeBlock ? 'success' : 'info'">{{ row.realtimeBlock ? '开启' : '关闭' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="T+1修正" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.tPlusOneFix ? 'warning' : 'info'">{{ row.tPlusOneFix ? '开启' : '关闭' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="releaseRule" label="释放规则" min-width="170" show-overflow-tooltip />
        <el-table-column prop="listStatusText" label="列表状态文案" min-width="140" show-overflow-tooltip />
        <el-table-column label="状态" width="90" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'info'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="updatedAt" label="更新时间" width="170" />
      </el-table>
      <div class="pagination-section">
        <span>Total {{ filteredRows.length }}</span>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :page-sizes="[10, 20, 50]"
          :total="filteredRows.length"
        />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="editing.id ? '编辑互斥组' : '新增互斥组'" width="860px" :close-on-click-modal="false">
      <el-form :model="editing" label-width="130px">
        <el-divider content-position="left">基础规则</el-divider>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="互斥组名称" required>
              <el-input v-model="editing.name" placeholder="如：NTB新客互斥组" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="互斥类型" required>
              <el-select v-model="editing.mutexType" style="width: 100%">
                <el-option label="互斥报名" value="互斥报名" />
                <el-option label="互斥继续参与" value="互斥继续参与" />
                <el-option label="互斥展示" value="互斥展示" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务类型" required>
              <el-select v-model="editing.businessType" style="width: 100%">
                <el-option label="NTB/MGM" value="NTB/MGM" />
                <el-option label="NTB" value="NTB" />
                <el-option label="MGM" value="MGM" />
                <el-option label="普通活动" value="普通活动" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="互斥活动范围" required>
              <el-select v-model="editing.scopeType" style="width: 100%">
                <el-option label="指定活动" value="指定活动" />
                <el-option label="指定活动类型" value="指定活动类型" />
                <el-option label="同业务类型全部活动" value="同业务类型全部活动" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="互斥活动" required>
              <el-input v-model="editing.activities" placeholder="填写活动名称，多个用顿号或逗号分隔" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">判断与拦截</el-divider>
        <el-form-item label="判断依据" required>
          <el-checkbox-group v-model="editing.judgeBasis">
            <el-checkbox label="报名记录">报名记录</el-checkbox>
            <el-checkbox label="MGM标签">MGM标签</el-checkbox>
            <el-checkbox label="开户时间">开户时间</el-checkbox>
            <el-checkbox label="达标状态">达标状态</el-checkbox>
            <el-checkbox label="活动状态">活动状态</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="报名实时拦截" required>
              <el-switch v-model="editing.realtimeBlock" active-text="开启" inactive-text="关闭" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="T+1标签修正">
              <el-switch v-model="editing.tPlusOneFix" active-text="开启" inactive-text="关闭" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="拦截文案" required>
          <el-input v-model="editing.blockText" type="textarea" :rows="3" placeholder="点击报名时弹出的拦截提示" />
        </el-form-item>
        <el-form-item label="T+1修正文案">
          <el-input v-model="editing.correctionText" type="textarea" :rows="3" placeholder="次日标签更新后活动状态修正说明" />
        </el-form-item>

        <el-divider content-position="left">释放与展示</el-divider>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="释放规则" required>
              <el-select v-model="editing.releaseRule" style="width: 100%">
                <el-option label="活动结束且未达标释放" value="活动结束且未达标释放" />
                <el-option label="活动结束后释放" value="活动结束后释放" />
                <el-option label="报名失败立即释放" value="报名失败立即释放" />
                <el-option label="不自动释放" value="不自动释放" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="列表状态文案">
              <el-input v-model="editing.listStatusText" placeholder="如：不符合参与条件" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详情状态文案">
              <el-input v-model="editing.detailStatusText" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="命中后展示规则">
              <el-input v-model="editing.conflictDisplayRule" placeholder="如：命中后其他活动展示不符合条件" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" required>
              <el-select v-model="editing.status" style="width: 100%">
                <el-option label="启用" value="启用" />
                <el-option label="停用" value="停用" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="editing.remark" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

function emptyMutex() {
  return {
    name: '',
    mutexType: '互斥报名',
    businessType: 'NTB/MGM',
    scopeType: '指定活动',
    activities: '',
    judgeBasis: ['报名记录'],
    realtimeBlock: true,
    tPlusOneFix: false,
    releaseRule: '活动结束且未达标释放',
    listStatusText: '不符合参与条件',
    detailStatusText: '',
    blockText: '',
    conflictDisplayRule: '命中后其他活动展示不符合条件',
    correctionText: '',
    remark: '',
    status: '启用'
  }
}

export default {
  name: 'ActivityMutexGroup',
  data() {
    return {
      dialogVisible: false,
      editing: emptyMutex(),
      searchForm: { name: '', status: '' },
      appliedSearch: { name: '', status: '' },
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    rows() {
      return activityStore.mutexGroups
    },
    filteredRows() {
      return this.rows.filter((row) => {
        if (this.appliedSearch.name && !String(row.name || '').includes(this.appliedSearch.name)) return false
        if (this.appliedSearch.status && row.status !== this.appliedSearch.status) return false
        return true
      })
    },
    pagedRows() {
      const start = (this.currentPage - 1) * this.pageSize
      return this.filteredRows.slice(start, start + this.pageSize)
    }
  },
  methods: {
    handleSearch() {
      this.appliedSearch = { ...this.searchForm }
      this.currentPage = 1
    },
    handleReset() {
      this.searchForm = { name: '', status: '' }
      this.handleSearch()
    },
    basisText(value) {
      return Array.isArray(value) ? value.join('、') : value || '-'
    },
    openDialog(row) {
      this.editing = row ? { ...emptyMutex(), ...JSON.parse(JSON.stringify(row)) } : emptyMutex()
      if (!Array.isArray(this.editing.judgeBasis)) this.editing.judgeBasis = []
      this.dialogVisible = true
    },
    save() {
      if (!this.editing.name) return ElMessage.warning('互斥组名称必填')
      if (!this.editing.activities) return ElMessage.warning('互斥活动必填')
      if (!this.editing.judgeBasis.length) return ElMessage.warning('判断依据至少选择一项')
      if (this.editing.realtimeBlock && !this.editing.blockText) return ElMessage.warning('开启报名实时拦截时，拦截文案必填')
      activityStore.saveSimple('mutexGroups', this.editing)
      ElMessage.success('保存成功')
      this.dialogVisible = false
    },
    async toggleStatus(row) {
      const action = row.status === '启用' ? '停用' : '启用'
      await ElMessageBox.confirm(`确定${action}互斥组「${row.name}」吗？`, `${action}互斥组`, { type: 'warning' })
      row.status = row.status === '启用' ? '停用' : '启用'
      activityStore.saveSimple('mutexGroups', row)
      ElMessage.success('状态已更新')
    }
  }
}
</script>

<style scoped>
.activity-mutex-group { padding:0; }
.search-section { display:flex; flex-direction:column; }
.search-row { margin-bottom:15px; }
.search-row .el-form { display:flex; flex-wrap:wrap; }
.search-row .el-form-item { margin-right:0; margin-bottom:0; }
.search-field { width:200px; }
.status-field { width:140px; }
.operation-row { display:flex; align-items:center; }
.pagination-section { display:flex; justify-content:flex-end; align-items:center; gap:20px; margin-top:20px; }
.activity-mutex-group :deep(.el-dialog__body) { padding-top:8px; }
.activity-mutex-group :deep(.el-divider__text) { color:#303133; font-size:15px; font-weight:600; }
</style>
