<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['score:pushConfig:add']">新增配置</el-button>
      </el-col>
    </el-row>

    <!-- 按维度分组展示推送配置 -->
    <div v-loading="loading">
      <el-card v-for="dim in dimensionOptions" :key="dim.id" class="dim-group-card" shadow="never">
        <template #header>
          <div class="group-header">
            <span class="dim-title">{{ dim.name }}</span>
            <span class="dim-weight">权重 {{ dim.weight }}% | 基础分 {{ dim.baseScore }}</span>
            <el-button size="small" type="primary" plain icon="Plus"
                       @click="handleAddForDim(dim)" v-hasPermi="['score:pushConfig:add']">添加推送规则</el-button>
          </div>
        </template>
        <el-table :data="getConfigsByDim(dim.id)" border>
          <el-table-column label="适用部门" align="center" prop="deptName">
            <template #default="{ row }">{{ row.deptName || '全局（所有部门）' }}</template>
          </el-table-column>
          <el-table-column label="预警阈值" align="center" width="120">
            <template #default="{ row }">
              <span style="color:#f56c6c;font-weight:bold">低于 {{ row.warnThreshold }} 分</span>
            </template>
          </el-table-column>
          <el-table-column label="推送人员" align="center" prop="pushUserNames" show-overflow-tooltip />
          <el-table-column label="状态" align="center" width="90">
            <template #default="{ row }">
              <el-switch v-model="row.status" active-value="0" inactive-value="1"
                         @change="handleStatusChange(row)" v-hasPermi="['score:pushConfig:edit']" />
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="120">
            <template #default="{ row }">
              <el-button link type="primary" icon="Edit" @click="handleEdit(row)" v-hasPermi="['score:pushConfig:edit']">修改</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPermi="['score:pushConfig:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!getConfigsByDim(dim.id).length" class="no-config">
          暂无推送规则，点击「添加推送规则」进行配置
        </div>
      </el-card>
    </div>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="520px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="维度" prop="dimensionId">
          <el-select v-model="form.dimensionId" placeholder="请选择维度" style="width:100%" @change="onDimChange">
            <el-option v-for="d in dimensionOptions" :key="d.id" :label="d.name" :value="d.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="适用部门">
          <el-input v-model="form.deptName" placeholder="留空=全局，填写部门名称=仅该部门" />
        </el-form-item>
        <el-form-item label="预警阈值" prop="warnThreshold">
          <el-input-number v-model="form.warnThreshold" :precision="2" :min="0" :max="200" style="width:100%" />
          <div style="color:#909399;font-size:12px;margin-top:4px">低于此分值时触发推送（默认 75 分）</div>
        </el-form-item>
        <el-form-item label="推送人员">
          <el-input v-model="form.pushUserNames" placeholder="请输入推送人员姓名，多人用逗号分隔" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="0">启用</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" 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 { listPushConfig, addPushConfig, updatePushConfig, delPushConfig } from '@/api/score/index'
import { allDimension } from '@/api/score/index'

defineOptions({ name: 'ScorePushConfig' })

const loading = ref(false)
const configList = ref([])
const dimensionOptions = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const form = reactive({ id: null, dimensionId: null, dimensionName: '', deptId: null, deptName: '', warnThreshold: 75, pushUserIds: '', pushUserNames: '', status: '0', remark: '' })
const rules = {
  dimensionId: [{ required: true, message: '请选择维度', trigger: 'change' }],
  warnThreshold: [{ required: true, message: '请输入预警阈值', trigger: 'blur' }]
}

async function loadDimensions() {
  const r = await allDimension()
  dimensionOptions.value = r.data || []
}

async function getList() {
  loading.value = true
  const r = await listPushConfig({ pageNum: 1, pageSize: 200 }).finally(() => loading.value = false)
  configList.value = r.rows || []
}

function getConfigsByDim(dimId) {
  return configList.value.filter(c => c.dimensionId === dimId)
}

function resetForm() {
  Object.assign(form, { id: null, dimensionId: null, dimensionName: '', deptId: null, deptName: '', warnThreshold: 75, pushUserIds: '', pushUserNames: '', status: '0', remark: '' })
}

function handleAdd() { resetForm(); dialogTitle.value = '新增推送配置'; dialogVisible.value = true }

function handleAddForDim(dim) {
  resetForm()
  form.dimensionId = dim.id
  form.dimensionName = dim.name
  dialogTitle.value = '新增推送配置 — ' + dim.name
  dialogVisible.value = true
}

function handleEdit(row) {
  Object.assign(form, row)
  dialogTitle.value = '修改推送配置'
  dialogVisible.value = true
}

function onDimChange(dimId) {
  const dim = dimensionOptions.value.find(d => d.id === dimId)
  if (dim) form.dimensionName = dim.name
}

async function submitForm() {
  await formRef.value.validate()
  if (form.id) { await updatePushConfig(form); ElMessage.success('修改成功') }
  else { await addPushConfig(form); ElMessage.success('新增成功') }
  dialogVisible.value = false
  getList()
}

async function handleStatusChange(row) {
  await updatePushConfig({ id: row.id, status: row.status })
  ElMessage.success(row.status === '0' ? '已启用' : '已停用')
}

function handleDelete(row) {
  ElMessageBox.confirm('确认删除此推送配置？', '提示', { type: 'warning' }).then(() => {
    delPushConfig(row.id).then(() => { ElMessage.success('删除成功'); getList() })
  })
}

onMounted(() => { loadDimensions(); getList() })
</script>

<style scoped>
.dim-group-card { margin-bottom: 16px; }
.group-header { display: flex; align-items: center; gap: 12px; }
.dim-title { font-size: 15px; font-weight: bold; color: #303133; }
.dim-weight { font-size: 13px; color: #909399; flex: 1; }
.no-config { text-align: center; color: #c0c4cc; padding: 20px 0; font-size: 13px; }
</style>
