<script setup lang="ts">
import { api } from '@/utils/request'
import { useUserManageStore, type UserRecord } from '@/stores/user-manage'
import { useUserStore } from '@/stores/user'
import UserFormModal from '@/components/UserFormModal.vue'
import DataScopeModal from '@/components/DataScopeModal.vue'
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
} from '@ant-design/icons-vue'

const store = useUserManageStore()
const userStore = useUserStore()

// Detail drawer
const drawerVisible = ref(false)
const drawerLoading = ref(false)
const currentUser = ref<UserRecord | null>(null)

// Form modal
const modalOpen = ref(false)
const modalMode = ref<'create' | 'edit'>('create')
const editingUser = ref<UserRecord | null>(null)

// Role assign modal
const roleModalOpen = ref(false)
const roleAssigning = ref(false)
const assigningUser = ref<UserRecord | null>(null)
const selectedRoleId = ref<number | undefined>(undefined)
const roleOptions = ref<{ value: number; label: string }[]>([])

// Role filter options
const roleFilterOptions = ref<{ value: number; label: string }[]>([])

// Data scope modal
const scopeModalOpen = ref(false)
const scopeUserId = ref<number | null>(null)
const scopeUsername = ref('')

const columns = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username' },
  { title: '邮箱', dataIndex: 'email' },
  { title: '角色', key: 'role', width: 120 },
  { title: '状态', dataIndex: 'status', width: 100 },
  { title: 'API Key', key: 'api_key_enabled', width: 100 },
  { title: '创建时间', dataIndex: 'created_at', width: 180 },
  { title: '数据范围', key: 'data_scope', width: 120 },
  { title: '操作', key: 'action', width: 320 },
]

onMounted(() => {
  store.fetchUsers()
  api.get<{ id: number; name: string; description: string }[]>('/api/v1/roles')
    .then((roles) => {
      roleFilterOptions.value = roles.map((r) => ({ value: r.id, label: r.description || r.name }))
    })
    .catch(() => { /* 角色列表加载失败不影响页面 */ })
})

function handleSearch() {
  store.pagination.page = 1
  store.fetchUsers()
}

function handleReset() {
  store.resetFilters()
  store.fetchUsers()
}

function handlePageChange(page: number, pageSize: number) {
  store.pagination.page = page
  store.pagination.per_page = pageSize
  store.fetchUsers()
}

async function handleViewDetail(record: UserRecord) {
  drawerVisible.value = true
  drawerLoading.value = true
  try {
    currentUser.value = await api.get<UserRecord>(`/api/v1/users/${record.id}`)
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '获取详情失败'
    message.error(msg)
  } finally {
    drawerLoading.value = false
  }
}

function handleCreate() {
  modalMode.value = 'create'
  editingUser.value = null
  modalOpen.value = true
}

function handleEdit(record: UserRecord) {
  modalMode.value = 'edit'
  editingUser.value = record
  modalOpen.value = true
}

async function handleToggleStatus(record: UserRecord) {
  const newStatus = record.status === 1 ? 0 : 1
  try {
    await api.patch(`/api/v1/users/${record.id}/status`, { status: newStatus })
    message.success('操作成功')
    store.fetchUsers()
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '操作失败'
    message.error(msg)
  }
}

function handleModalSuccess() {
  store.fetchUsers()
}

async function handleAssignRole(record: UserRecord) {
  assigningUser.value = record
  selectedRoleId.value = record.role_id || undefined
  roleModalOpen.value = true
  try {
    const roles = await api.get<{ id: number; name: string; description: string }[]>('/api/v1/roles')
    roleOptions.value = roles.map((r) => ({ value: r.id, label: r.description || r.name }))
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '获取角色列表失败'
    message.error(msg)
  }
}

async function submitRoleAssign() {
  if (!assigningUser.value || !selectedRoleId.value) return
  roleAssigning.value = true
  try {
    await api.put(`/api/v1/users/${assigningUser.value.id}/role`, { role_id: selectedRoleId.value })
    message.success('角色分配成功')
    roleModalOpen.value = false
    store.fetchUsers()
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '分配失败'
    message.error(msg)
  } finally {
    roleAssigning.value = false
  }
}

function handleDataScope(record: UserRecord) {
  scopeUserId.value = record.id
  scopeUsername.value = record.username
  scopeModalOpen.value = true
}

const togglingApiKeyId = ref<number | null>(null)

async function handleToggleApiKeyEnabled(record: UserRecord, enabled: boolean) {
  togglingApiKeyId.value = record.id
  const original = record.api_key_enabled
  record.api_key_enabled = enabled
  try {
    await store.toggleApiKeyEnabled(record.id, enabled)
    message.success('操作成功')
  } catch (err: unknown) {
    record.api_key_enabled = original
    const msg = err instanceof Error ? err.message : '操作失败'
    message.error(msg)
  } finally {
    togglingApiKeyId.value = null
  }
}

function handleScopeSuccess() {
  store.fetchUsers()
}

function formatTime(time: string) {
  return time ? time.replace('T', ' ').substring(0, 19) : '-'
}
</script>

<template>
  <div>
    <h2 class="text-xl font-semibold mb-4">用户管理</h2>

    <!-- Filter area -->
    <a-card class="mb-4">
      <a-form layout="inline" @submit.prevent="handleSearch">
        <a-form-item label="用户名">
          <a-input
            v-model:value="store.filters.username"
            placeholder="请输入用户名"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="邮箱">
          <a-input
            v-model:value="store.filters.email"
            placeholder="请输入邮箱"
            allow-clear
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="store.filters.status"
            placeholder="全部"
            allow-clear
            style="width: 120px"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色">
          <a-select
            v-model:value="store.filters.role_id"
            placeholder="全部"
            allow-clear
            style="width: 140px"
            :options="roleFilterOptions"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><SearchOutlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><ReloadOutlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- Table -->
    <a-card>
      <div v-if="userStore.isAdmin" class="mb-4">
        <a-button type="primary" @click="handleCreate">
          <template #icon><PlusOutlined /></template>
          新建用户
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="store.users"
        :loading="store.loading"
        :pagination="false"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'role'">
            <a-tag v-if="record.role" color="blue">{{ record.role.name }}</a-tag>
            <span v-else>-</span>
          </template>
          <template v-else-if="column.key === 'api_key_enabled'">
            <a-popconfirm
              title="确定关闭该用户的 API Key 功能？"
              description="关闭后，该用户的所有 API Key 将立即无法用于认证。已有 Key 不会被删除，重新开启后自动恢复。"
              :disabled="!(record as UserRecord).api_key_enabled"
              @confirm="handleToggleApiKeyEnabled(record as UserRecord, false)"
            >
              <a-switch
                :checked="(record as UserRecord).api_key_enabled"
                :loading="togglingApiKeyId === (record as UserRecord).id"
                @change="(checked) => {
                  if (checked === true) handleToggleApiKeyEnabled(record as UserRecord, true)
                }"
              />
            </a-popconfirm>
          </template>
          <template v-else-if="column.key === 'data_scope'">
            <a-tag v-if="record.role?.name === 'administrator'" color="green">全部权限</a-tag>
            <a-tag v-else-if="record.role?.name === 'developer'" color="blue">平台级</a-tag>
            <a-tag v-else color="orange">自定义</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'status'">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'created_at'">
            {{ formatTime(record.created_at) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleViewDetail(record as UserRecord)">
                查看
              </a-button>
              <a-button v-if="userStore.isAdmin" type="link" size="small" @click="handleEdit(record as UserRecord)">
                编辑
              </a-button>
              <a-button
                v-if="userStore.isAdmin && record.id !== userStore.user?.id"
                type="link"
                size="small"
                @click="handleAssignRole(record as UserRecord)"
              >
                分配角色
              </a-button>
              <a-button
                v-if="userStore.isAdmin && record.role?.name !== 'administrator'"
                type="link"
                size="small"
                @click="handleDataScope(record as UserRecord)"
              >
                数据范围
              </a-button>
              <a-popconfirm
                v-if="userStore.isAdmin"
                :title="`确定要${record.status === 1 ? '禁用' : '启用'}该用户吗？`"
                @confirm="handleToggleStatus(record as UserRecord)"
              >
                <a-button type="link" size="small" :danger="record.status === 1">
                  {{ record.status === 1 ? '禁用' : '启用' }}
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>

      <div class="mt-4 flex justify-end">
        <a-pagination
          :current="store.pagination.page"
          :page-size="store.pagination.per_page"
          :total="store.pagination.total"
          show-size-changer
          show-quick-jumper
          :show-total="(total: number) => `共 ${total} 条`"
          @change="handlePageChange"
        />
      </div>
    </a-card>

    <!-- Detail drawer -->
    <a-drawer
      title="用户详情"
      :open="drawerVisible"
      :width="480"
      @close="drawerVisible = false"
    >
      <a-spin :spinning="drawerLoading">
        <a-descriptions v-if="currentUser" :column="1" bordered>
          <a-descriptions-item label="ID">{{ currentUser.id }}</a-descriptions-item>
          <a-descriptions-item label="用户名">{{ currentUser.username }}</a-descriptions-item>
          <a-descriptions-item label="邮箱">{{ currentUser.email }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="currentUser.status === 1 ? 'green' : 'red'">
              {{ currentUser.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="角色">{{ currentUser.role?.name || '-' }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatTime(currentUser.created_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatTime(currentUser.updated_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="扩展信息">
            <pre class="m-0 text-xs">{{
              currentUser.ext ? JSON.stringify(currentUser.ext, null, 2) : '-'
            }}</pre>
          </a-descriptions-item>
        </a-descriptions>
      </a-spin>
    </a-drawer>

    <!-- Role assign modal -->
    <a-modal
      v-model:open="roleModalOpen"
      title="分配角色"
      :confirm-loading="roleAssigning"
      @ok="submitRoleAssign"
    >
      <div class="py-2">
        <p class="mb-3">
          用户：<strong>{{ assigningUser?.username }}</strong>
        </p>
        <a-form-item label="选择角色">
          <a-select
            v-model:value="selectedRoleId"
            :options="roleOptions"
            placeholder="请选择角色"
            style="width: 100%"
          />
        </a-form-item>
      </div>
    </a-modal>

    <!-- Create/Edit modal -->
    <UserFormModal
      v-model:open="modalOpen"
      :mode="modalMode"
      :user-data="editingUser"
      @success="handleModalSuccess"
    />

    <!-- Data scope modal -->
    <DataScopeModal
      v-model:open="scopeModalOpen"
      :user-id="scopeUserId"
      :username="scopeUsername"
      @saved="handleScopeSuccess"
    />
  </div>
</template>
