<template>
  <div class="frame-body adaption-frame-body summary-settings-page">
    <el-card shadow="never">
      <template #header>
        <div class="page-header">
          <div>
            <div class="page-title">简报设置</div>
            <div class="page-subtitle">维护各类简报提醒场景的人员名单，保留旧版页面的核心配置能力。</div>
          </div>
          <el-button :loading="loading" @click="load">刷新</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="rows" border>
        <el-table-column prop="settingType" label="设置属性" min-width="220" />
        <el-table-column label="人员名单" min-width="360">
          <template #default="{ row }">
            <div v-if="normalizeUsers(row).length" class="user-tags">
              <el-tag v-for="user in normalizeUsers(row)" :key="user.id || user.realName" type="info" effect="plain">
                {{ user.realName || user.name || '-' }}
              </el-tag>
            </div>
            <span v-else class="empty-text">暂无人员</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="remove(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="!rows.length && !loading" description="暂无设置" />
    </el-card>

    <el-dialog v-model="dialogVisible" :title="`选择${currentSettingLabel}人员`" width="720px">
      <el-form label-width="90px">
        <el-form-item label="选择人员">
          <SelectUser v-model="selectedUserIds" multiple placeholder="请选择人员" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="submit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'
import SelectUser from '@/components/SelectUser/SelectUser.vue'
import { summarySettingDelete, summarySettingEdit, summarySettingList } from '@/api/otr/summary/core'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const rows = ref<any[]>([])
const currentSetting = ref<any>(null)
const selectedUserIds = ref<Array<string | number>>([])

const currentSettingLabel = computed(() => currentSetting.value?.settingType || '设置')

function normalizeUsers(row: any) {
  const users = row?.summarySettingVoList || row?.userList || row?.users || []
  return Array.isArray(users) ? users : []
}

function extractIds(row: any) {
  if (Array.isArray(row?.summarySettingIds)) return row.summarySettingIds
  const users = normalizeUsers(row)
  return users.map((item: any) => item.id).filter(Boolean)
}

async function load() {
  loading.value = true
  try {
    const res: any = await summarySettingList()
    const result = res?.result
    rows.value = Array.isArray(result) ? result : result?.records || result?.list || []
  } finally {
    loading.value = false
  }
}

function openEdit(row: any) {
  currentSetting.value = row
  selectedUserIds.value = extractIds(row)
  dialogVisible.value = true
}

async function submit() {
  if (!currentSetting.value?.settingType) return
  submitting.value = true
  try {
    await summarySettingEdit({
      settingType: currentSetting.value.settingType,
      summarySettingIds: selectedUserIds.value,
    })
    ElMessage.success('设置成功')
    dialogVisible.value = false
    load()
  } finally {
    submitting.value = false
  }
}

function remove(row: any) {
  ElMessageBox.confirm(`确定删除${row.settingType}人员吗？`, '系统提示', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      await summarySettingDelete({ settingType: row.settingType })
      ElMessage.success('删除成功')
      load()
    })
    .catch(() => undefined)
}

load()
</script>

<style scoped lang="scss">
.summary-settings-page {
  .page-header {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 16px;
  }

  .page-title {
    font-size: 18px;
    font-weight: 600;
    color: #111827;
  }

  .page-subtitle {
    margin-top: 4px;
    font-size: 13px;
    color: #6b7280;
  }

  .user-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .empty-text {
    color: #9ca3af;
  }
}
</style>

