<script setup lang="ts">
import { ref, onMounted, h } from 'vue'
import { useMessage, NDataTable, NButton, NInput, NTag, NSpace, NModal, NForm, NFormItem, NSelect, NIcon } from 'naive-ui'
import { SearchOutline, SaveOutline } from '@vicons/ionicons5'
import { api } from '../../api/client'

interface TenantRole {
  tenant_name: string
  role: string
}

interface User {
  id: string
  email: string
  display_name: string
  is_active: boolean
  platform_role?: string
  admin_note?: string
  customer_name?: string
  created_at?: string
  last_login_at?: string
  tenant_count?: number
  tenants?: TenantRole[]
  [key: string]: unknown
}

const users = ref<User[]>([])
const total = ref(0)
const loading = ref(true)
const searchQ = ref('')
const showModal = ref(false)
const showModalMax = ref(false)
const editing = ref<User | null>(null)
const saving = ref(false)
const message = useMessage()

// Maximized note viewer
const showNoteMax = ref(false)
const noteToView = ref('')
const noteTitle = ref('')

onMounted(loadData)
async function loadData() {
  loading.value = true
  try { const { data } = await api.get('/admin/users', { params: { q: searchQ.value, page_size:50 } }); users.value = data.items; total.value = data.total }
  catch (e) { message.error('加载用户列表失败：' + ((e as any)?.response?.data?.detail || '请重试')) }
  finally { loading.value = false }
}
async function editUser(row: User) { editing.value = {...row}; showModal.value = true }
async function saveUser() {
  if (!editing.value) return
  saving.value = true
  try { await api.put(`/admin/users/${editing.value.id}`, { is_active: editing.value.is_active, admin_note: editing.value.admin_note || null, customer_name: editing.value.customer_name || null }); showModal.value = false; loadData() }
  catch (e) { message.error('保存失败：' + ((e as any)?.response?.data?.detail || '请重试')) }
  finally { saving.value = false }
}
function openMaxNote(note: string, title: string) { noteToView.value = note; noteTitle.value = title; showNoteMax.value = true }
const editModalStyle = ref('width:520px')
function toggleModalMax() {
  showModalMax.value = !showModalMax.value
  editModalStyle.value = showModalMax.value ? 'width:90vw;max-width:1200px' : 'width:520px'
}

const cols = [
  { title: '邮箱', key: 'email', width: 280, ellipsis: { tooltip: true } },
  { title: '姓名', key: 'display_name', width: 160, ellipsis: { tooltip: true } },
  { title: '客户名称', key: 'customer_name', width: 200, ellipsis: { tooltip: true }, render: (r: User) => r.customer_name || '—' },
  { title: '所属租户(角色)', key: 'tenants', width: 300, ellipsis: { tooltip: true }, render: (r: User) => {
      const list = r.tenants || []
      return h('div', { style: 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap' },
        list.length ? list.map((t: TenantRole) => `${t.tenant_name}(${t.role})`).join(', ') : '—'
      )
    }
  },
  { title: '状态', key: 'is_active', width: 80, render: (r: User) => h(NTag, { size:'tiny', type: r.is_active?'success':'error' }, r.is_active?'正常':'禁用') },
  { title: '平台角色', key: 'platform_role', width: 120, render: (r: User) => r.platform_role ? h(NTag, { size:'tiny', type:'info' }, r.platform_role) : '—' },
  { title: '注册时间', key: 'created_at', width: 200, render: (r: User) => r.created_at ? r.created_at.slice(0,16).replace('T', ' ') : '—' },
  { title: '最后登录', key: 'last_login_at', width: 200, render: (r: User) => r.last_login_at ? r.last_login_at.slice(0,16).replace('T', ' ') : '—' },
  { title: '备注', key: 'admin_note', width: 200, ellipsis: { tooltip: true }, render: (r: User) => {
      if (!r.admin_note) return '—'
      return h('div', { style:'display:flex;align-items:center;gap:4px' }, [
        h('span', { style:'flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap' }, r.admin_note),
        h(NButton as any, { size:'tiny', quaternary:true, onClick:(e:Event) => { e.stopPropagation(); openMaxNote(r.admin_note!, r.display_name + ' 备注') } }, '🔍'),
      ])
    }
  },
  { title: '操作', key: 'actions', width: 100, render: (r: User) => h(NButton, { size:'tiny', onClick:()=>editUser(r) }, '编辑') },
]
const scrollX = 1840
</script>

<template>
  <div>
    <div style="display:flex;justify-content:space-between;margin-bottom:16px">
      <h2>👤 用户管理 ({{ total }})</h2>
      <NSpace>
        <NInput v-model:value="searchQ" placeholder="搜索邮箱/姓名/客户/备注..." size="small" @keyup.enter="loadData" style="min-width:200px" />
        <NButton size="small" @click="loadData" class="sky-btn"><template #icon><NIcon size="14"><SearchOutline /></NIcon></template>搜索</NButton>
        <NButton size="small" @click="searchQ='';loadData()" class="sky-btn">重置</NButton>
      </NSpace>
    </div>
    <NDataTable :columns="cols" :data="users" :loading="loading" size="small" single-line :paginate="{ pageSize: 20 }" class="tight-rows" :scroll-x="scrollX" />

    <!-- Edit Modal -->
    <NModal v-model:show="showModal" title="编辑用户" v-if="editing" :style="editModalStyle" preset="card" closable>
      <div style="position:absolute;top:16px;right:48px;z-index:10">
        <NButton size="tiny" quaternary @click="toggleModalMax">{{ showModalMax ? '🗗 还原' : '🗖 最大化' }}</NButton>
      </div>
      <NForm label-placement="left" label-width="80" :show-feedback="false" class="tight-form">
        <NFormItem label="邮箱">{{ editing.email }}</NFormItem>
        <NFormItem label="状态"><NSelect :value="editing?.is_active ? 'yes' : 'no'" @update:value="v => { if (editing) editing.is_active = v === 'yes' }" :options="[{label:'正常',value:'yes'},{label:'禁用',value:'no'}]" /></NFormItem>
        <NFormItem label="平台角色"><NTag :type="editing?.platform_role ? 'info' : 'default'" size="small">{{ editing?.platform_role || '无' }}</NTag></NFormItem>
        <NFormItem label="客户名称"><NInput v-model:value="editing.customer_name" placeholder="客户名称（用户不可见）" maxlength="200" show-count /></NFormItem>
        <NFormItem label="备注">
          <div style="width:100%">
            <NInput v-model:value="editing.admin_note" placeholder="平台备注（用户不可见）" type="textarea" :rows="showModalMax ? 8 : 3" maxlength="1000" show-count />
            <NButton v-if="editing.admin_note" size="tiny" quaternary style="margin-top:4px" @click="openMaxNote(editing.admin_note!, editing.display_name + ' 备注')">
              最大化查看
            </NButton>
          </div>
        </NFormItem>
        <NButton type="primary" :loading="saving" @click="saveUser" class="sky-btn" style="margin-top:4px"><template #icon><NIcon size="14"><SaveOutline /></NIcon></template>保存</NButton>
      </NForm>
    </NModal>

    <!-- Maximized Note Viewer -->
    <NModal v-model:show="showNoteMax" :title="noteTitle" preset="card" style="width:800px" closable>
      <div style="white-space:pre-wrap;font-size:14px;line-height:1.7;max-height:70vh;overflow-y:auto;padding:12px;background:var(--bg-hover);border-radius:6px">
        {{ noteToView }}
      </div>
    </NModal>
  </div>
</template>

<style scoped>
.tight-rows :deep(td) { padding-top: 4px !important; padding-bottom: 4px !important; }
.tight-form :deep(.n-form-item) { margin-bottom: 0 !important; padding-bottom: 4px !important; }
</style>
