<template>
  <a-modal v-model:visible="visible" title="设置权限" :mask-closable="false" :width="600" @cancel="handleClose">
    <a-spin :loading="loading" style="width: 100%">
      <div class="permission-header">
        <span>用户账号: {{ user?.account }}</span>
      </div>
      <div class="permission-content">
        <PermissionTreeItem
          v-if="permissionTree.length > 0"
          :items="permissionTree"
          :selected-permissions="selectedPermissions"
          :expanded-keys="expandedKeys"
          @change="handlePermissionChange"
        />
        <a-empty v-else description="暂无权限数据" />
      </div>
    </a-spin>

    <template #footer>
      <a-space>
        <a-button @click="handleClose">取消</a-button>
        <a-button type="primary" :loading="submitting" @click="handleSubmit">确定</a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import PermissionTreeItem from './PermissionTree.vue'
import { userPmn, userModifyPmn } from '@/api/module/user'
import { fetchMenu } from '@/api/module/pmn'
import type { UserItem } from '@/api/types'
import { useAppStore } from '@/store'
import { buildTree } from '@/utils/tree'

const props = defineProps<{
  user: UserItem | null
}>()

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'success'): void
}>()

const appStore = useAppStore()

const visible = computed({
  get: () => !!props.user,
  set: (val) => emit('update:visible', val),
})

const loading = ref(false)
const submitting = ref(false)
const permissionTree = ref<any[]>([])
const selectedPermissions = ref<number[]>([])
const originalPermissions = ref<number[]>([])
const expandedKeys = ref<Set<number>>(new Set())

// 获取权限数据
const fetchPermissions = async () => {
  if (!props.user?.id) return

  loading.value = true
  try {
    // 并行获取完整权限树和用户当前权限
    const [menuRes, pmnRes] = await Promise.all([
      fetchMenu({ page: 1, size: 999 }), // 获取系统所有菜单
      userPmn({
        id: props.user.id,
        workspace: import.meta.env.VITE_APP_WORKSPACE || '',
      }),
    ])

    // 构建完整的权限树结构
    if (menuRes?.code === 0 && menuRes.details?.data) {
      const { rootItems } = buildTree(menuRes.details.data, {
        idKey: 'id',
        parentKey: 'parent_id',
        childrenKey: 'children',
        orderKey: 'sort_key',
      })
      permissionTree.value = rootItems

      // 默认展开第一层
      rootItems.forEach((item: any) => {
        expandedKeys.value.add(item.id)
      })
    }

    // 设置用户当前拥有的权限为选中状态
    if (pmnRes.details) {
      console.log('pmnRes.details', pmnRes.details)
      // 处理不同的数据格式：对象数组或ID数组
      selectedPermissions.value = pmnRes.details[0]?.permissions
        .map((item: any) => {
          if (typeof item === 'object' && item !== null) {
            // 如果是对象，优先使用 id 字段，其次 pmn_id 字段
            return item.id || item.pmn_id
          }
          // 如果是数字，直接返回
          return item
        })
        .filter((id: any) => id !== undefined && id !== null)
      originalPermissions.value = [...selectedPermissions.value]
    }
  } catch (error) {
    console.error('获取权限数据失败', error)
  } finally {
    loading.value = false
  }
}

// 监听 user 变化
watch(
  () => props.user,
  (val) => {
    if (val?.id) {
      fetchPermissions()
    } else {
      permissionTree.value = []
      selectedPermissions.value = []
    }
  }
)

// 处理权限变化
const handlePermissionChange = (permissions: number[]) => {
  selectedPermissions.value = permissions
}

const handleClose = () => {
  emit('update:visible', false)
}

const handleSubmit = async () => {
  if (!props.user?.id) return

  submitting.value = true
  try {
    const res = await userModifyPmn({
      id: props.user.id,
      list: selectedPermissions.value,
    })

    if (res.code === 0) {
      Message.success('权限设置成功')
      handleClose()
      emit('success')
    }
  } catch (error) {
    console.error('设置权限失败', error)
  } finally {
    submitting.value = false
  }
}
</script>

<script lang="ts">
export default {
  name: 'PermissionSettingDialog',
}
</script>

<style scoped lang="less">
.permission-header {
  margin-bottom: 16px;
  padding: 12px;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}

.permission-content {
  max-height: 400px;
  overflow-y: auto;
  padding: 8px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
}
</style>
