<template>
  <div class="menu-permission-container">
    <el-card class="main-container" shadow="never">
      <div class="filter-section">
        <div class="filter-content">
          <el-form :inline="true" :model="queryParams" class="filter-form">
            <el-form-item label="类型">
              <el-select v-model="queryParams.owner_type" placeholder="请选择类型" clearable style="width: 130px" @change="handleOwnerTypeChange">
                <el-option label="用户" value="user" />
                <el-option label="管理员组" value="group" />
              </el-select>
            </el-form-item>
            <el-form-item label="用户" v-if="queryParams.owner_type === 'user'">
              <div class="selector-inline">
                <el-tag v-if="queryParams.user_id" type="primary" closable @close="clearQueryUser" style="margin-right: 8px;">
                  {{ queryUserName || `用户 #${queryParams.user_id}` }}
                </el-tag>
                <el-button type="primary" plain @click="openUserSelector('query')" size="default">
                  <el-icon><User /></el-icon>
                  {{ queryParams.user_id ? '重新选择' : '选择用户' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item label="管理员组" v-if="queryParams.owner_type === 'group'">
              <div class="selector-inline">
                <el-tag v-if="queryParams.admin_group_id" type="success" closable @close="clearQueryGroup" style="margin-right: 8px;">
                  {{ queryGroupName || `组 #${queryParams.admin_group_id}` }}
                </el-tag>
                <el-button type="success" plain @click="openGroupSelector('query')" size="default">
                  <el-icon><User /></el-icon>
                  {{ queryParams.admin_group_id ? '重新选择' : '选择管理员组' }}
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon><Search /></el-icon>查询
              </el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <div class="action-bar">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>分配权限
            </el-button>
            <el-button type="success" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>刷新
            </el-button>
          </div>
        </div>
      </div>

      <div class="table-section">
        <el-table
          v-loading="loading"
          :data="permissionList"
          style="width: 100%"
          :header-cell-style="{ background: '#fafafa', color: '#333', fontWeight: 600 }"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="所属类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getOwnerType(row) === 'user' ? 'primary' : 'success'" size="small">
                {{ getOwnerType(row) === 'user' ? '用户' : '管理员组' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所属对象" width="150">
            <template #default="{ row }">
              <span v-if="row.userId">用户 #{{ row.userId }}</span>
              <span v-else-if="row.adminGroupId">管理员组 #{{ row.adminGroupId }}</span>
              <span v-else class="text-muted">-</span>
            </template>
          </el-table-column>
          <el-table-column label="菜单" min-width="200">
            <template #default="{ row }">
              <div v-if="row.webRouts">
                <span style="font-weight: 500;">{{ row.webRouts.title }}</span>
                <el-tag size="small" type="info" style="margin-left: 8px;">{{ row.webRouts.path }}</el-tag>
              </div>
              <span v-else class="text-muted">菜单ID: {{ row.webRoutsId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.enable ? 'success' : 'danger'" size="small">
                {{ row.enable ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" width="170">
            <template #default="{ row }">
              {{ formatDate(row.CreatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" link @click="handleToggleEnable(row)">
                  {{ row.enable ? '禁用' : '启用' }}
                </el-button>
                <el-button type="warning" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无权限数据" :image-size="80" />
          </template>
        </el-table>
      </div>
    </el-card>

    <!-- 用户选择弹窗 -->
    <UserListSelector
      v-model="userSelectorVisible"
      :current-user-id="selectorTarget === 'query' ? queryParams.user_id : permForm.user_id"
      @confirm="handleUserConfirm"
    />

    <!-- 管理员组选择弹窗 -->
    <UserGroupSelector
      v-model="groupSelectorVisible"
      :current-group-id="selectorTarget === 'query' ? queryParams.admin_group_id : permForm.admin_group_id"
      admin-group
      @confirm="handleGroupConfirm"
    />

    <!-- 菜单选择弹窗 -->
    <el-dialog v-model="menuSelectorVisible" title="选择菜单" width="700px" append-to-body @open="openMenuSelector">
      <div style="display: flex; gap: 8px; margin-bottom: 12px;">
        <el-input v-model="menuSearchKey" placeholder="搜索菜单名称或路径" clearable style="flex: 1;" @keyup.enter="fetchMenuSelectorList">
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="fetchMenuSelectorList">搜索</el-button>
        <el-button type="success" @click="fetchMenuSelectorList">
          <el-icon><Refresh /></el-icon>刷新
        </el-button>
      </div>
      <el-table
        v-loading="menuSelectorLoading"
        :data="menuSelectorFlatList"
        highlight-current-row
        @current-change="handleMenuCurrentChange"
        :height="400"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="70" />
        <el-table-column prop="title" label="菜单名称" min-width="160">
          <template #default="{ row }">
            <span :style="{ paddingLeft: (row._level || 0) * 20 + 'px' }">
              <span v-if="row._level" style="color: #c0c4cc; margin-right: 4px;">└</span>
              {{ row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" min-width="180">
          <template #default="{ row }">
            <el-tag size="small" type="info">{{ row.path || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="80">
          <template #default="{ row }">
            <el-icon v-if="row.icon"><component :is="row.icon" /></el-icon>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="menuSelectorVisible = false">取消</el-button>
        <el-button type="primary" :disabled="!menuSelectorTemp" @click="confirmMenuSelect">确定选择</el-button>
      </template>
    </el-dialog>

    <!-- 分配/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '分配菜单权限' : '编辑菜单权限'"
      width="600px"
      append-to-body
    >
      <el-form ref="formRef" :model="permForm" :rules="formRules" label-width="120px">
        <el-form-item label="所属类型" prop="owner_type">
          <el-select v-model="permForm.owner_type" placeholder="请选择" style="width: 100%" :disabled="dialogType === 'edit'" @change="handleFormOwnerTypeChange">
            <el-option label="用户" value="user" />
            <el-option label="管理员组" value="group" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="user_id" v-if="permForm.owner_type === 'user'">
          <div class="selector-inline" style="width: 100%;">
            <el-tag v-if="permForm.user_id" type="primary" closable @close="permForm.user_id = null" style="margin-right: 8px;">
              {{ formUserName || `用户 #${permForm.user_id}` }}
            </el-tag>
            <el-button type="primary" plain @click="openUserSelector('form')">
              <el-icon><User /></el-icon>
              {{ permForm.user_id ? '重新选择' : '选择用户' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="管理员组" prop="admin_group_id" v-if="permForm.owner_type === 'group'">
          <div class="selector-inline" style="width: 100%;">
            <el-tag v-if="permForm.admin_group_id" type="success" closable @close="permForm.admin_group_id = null" style="margin-right: 8px;">
              {{ formGroupName || `组 #${permForm.admin_group_id}` }}
            </el-tag>
            <el-button type="success" plain @click="openGroupSelector('form')">
              <el-icon><User /></el-icon>
              {{ permForm.admin_group_id ? '重新选择' : '选择管理员组' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="菜单" prop="web_routs_id">
          <div class="selector-inline" style="width: 100%;">
            <el-tag v-if="permForm.web_routs_id" closable @close="clearFormMenu" style="margin-right: 8px;">
              {{ formMenuName || `菜单 #${permForm.web_routs_id}` }}
            </el-tag>
            <el-button plain @click="menuSelectorVisible = true">
              <el-icon><Menu /></el-icon>
              {{ permForm.web_routs_id ? '重新选择' : '选择菜单' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="permForm.enable" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh, User, Menu } from '@element-plus/icons-vue'
import UserListSelector from '@/components/admin/UserListSelector.vue'
import UserGroupSelector from '@/components/admin/UserGroupSelector.vue'
import {
  getWebRoutsList,
  getWebRoutsPermissionList,
  addWebRoutsPermission,
  updateWebRoutsPermission,
  deleteWebRoutsPermission
} from '@/api/admin/webRouts'
import { formatDate as formatDateTool } from '@/utils/tool'

const loading = ref(false)
const permissionList = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const userSelectorVisible = ref(false)
const groupSelectorVisible = ref(false)
const menuSelectorVisible = ref(false)
const menuSelectorLoading = ref(false)
const menuSelectorTemp = ref(null)
const menuSearchKey = ref('')
const selectorTarget = ref('query')

const queryUserName = ref('')
const queryGroupName = ref('')
const formUserName = ref('')
const formGroupName = ref('')
const formMenuName = ref('')

const queryParams = reactive({
  owner_type: 'group',
  user_id: null,
  admin_group_id: null
})

const permForm = reactive({
  id: undefined,
  web_routs_id: null,
  enable: true,
  owner_type: 'group',
  admin_group_id: null,
  user_id: null
})

const formRules = {
  owner_type: [{ required: true, message: '请选择所属类型', trigger: 'change' }],
  web_routs_id: [{ required: true, message: '请选择菜单', trigger: 'change' }],
  user_id: [{ required: true, message: '请选择用户', trigger: 'change' }],
  admin_group_id: [{ required: true, message: '请选择管理员组', trigger: 'change' }]
}

const formatDate = (dateStr) => formatDateTool(dateStr)

const getOwnerType = (row) => {
  if (row.userId) return 'user'
  if (row.adminGroupId) return 'group'
  return 'unknown'
}

const fetchPermissionList = async () => {
  loading.value = true
  try {
    const params = {}
    if (queryParams.owner_type) params.owner_type = queryParams.owner_type
    if (queryParams.owner_type === 'user' && queryParams.user_id) params.user_id = queryParams.user_id
    if (queryParams.owner_type === 'group' && queryParams.admin_group_id) params.admin_group_id = queryParams.admin_group_id
    const res = await getWebRoutsPermissionList(params)
    if (res.data.code === 200) {
      permissionList.value = res.data.data || []
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

const flattenMenuTree = (list, level = 0) => {
  const result = []
  for (const item of list) {
    result.push({ ...item, _level: level, children: undefined })
    if (item.children?.length) {
      result.push(...flattenMenuTree(item.children, level + 1))
    }
  }
  return result
}

const menuSelectorFlatList = ref([])

const openMenuSelector = () => {
  menuSelectorTemp.value = null
  menuSearchKey.value = ''
  fetchMenuSelectorList()
}

const fetchMenuSelectorList = async () => {
  menuSelectorLoading.value = true
  try {
    const params = { page: 1, count: 10 }
    if (menuSearchKey.value) params.key = menuSearchKey.value
    const res = await getWebRoutsList(params)
    if (res.data.code === 200) {
      const treeList = res.data.data?.list || []
      menuSelectorFlatList.value = flattenMenuTree(treeList)
    }
  } catch (error) {
    console.error('获取菜单列表失败:', error)
  } finally {
    menuSelectorLoading.value = false
  }
}

const handleMenuCurrentChange = (row) => {
  menuSelectorTemp.value = row
}

const confirmMenuSelect = () => {
  if (!menuSelectorTemp.value) return
  permForm.web_routs_id = menuSelectorTemp.value.id
  formMenuName.value = `${menuSelectorTemp.value.title} (${menuSelectorTemp.value.path})`
  menuSelectorVisible.value = false
  menuSelectorTemp.value = null
  menuSearchKey.value = ''
}

const clearFormMenu = () => {
  permForm.web_routs_id = null
  formMenuName.value = ''
}

const handleOwnerTypeChange = () => {
  queryParams.user_id = null
  queryParams.admin_group_id = null
  queryUserName.value = ''
  queryGroupName.value = ''
}

const handleFormOwnerTypeChange = () => {
  permForm.user_id = null
  permForm.admin_group_id = null
  formUserName.value = ''
  formGroupName.value = ''
}

const canQuery = () => {
  if (queryParams.owner_type === 'user' && !queryParams.user_id) {
    ElMessage.warning('请先选择用户')
    return false
  }
  if (queryParams.owner_type === 'group' && !queryParams.admin_group_id) {
    ElMessage.warning('请先选择管理员组')
    return false
  }
  if (!queryParams.owner_type) {
    ElMessage.warning('请先选择类型')
    return false
  }
  return true
}

const handleQuery = () => {
  if (!canQuery()) return
  fetchPermissionList()
}

const handleRefresh = () => {
  if (!canQuery()) return
  fetchPermissionList()
}

const resetQuery = () => {
  queryParams.owner_type = 'group'
  queryParams.user_id = null
  queryParams.admin_group_id = null
  queryUserName.value = ''
  queryGroupName.value = ''
  permissionList.value = []
}

const clearQueryUser = () => {
  queryParams.user_id = null
  queryUserName.value = ''
}

const clearQueryGroup = () => {
  queryParams.admin_group_id = null
  queryGroupName.value = ''
}

const openUserSelector = (target) => {
  selectorTarget.value = target
  userSelectorVisible.value = true
}

const openGroupSelector = (target) => {
  selectorTarget.value = target
  groupSelectorVisible.value = true
}

const handleUserConfirm = (user) => {
  const id = user.user_id || user.UserId || user.userId
  const name = user.user_name || user.UserName || user.userName || `用户 #${id}`
  if (selectorTarget.value === 'query') {
    queryParams.user_id = id
    queryUserName.value = name
  } else {
    permForm.user_id = id
    formUserName.value = name
  }
}

const handleGroupConfirm = (group) => {
  const name = group.name || group.groupName || `组 #${group.id}`
  const id = group.id
  if (selectorTarget.value === 'query') {
    queryParams.admin_group_id = id
    queryGroupName.value = name
  } else {
    permForm.admin_group_id = id
    formGroupName.value = name
  }
}

const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.assign(permForm, {
    id: undefined,
    web_routs_id: null,
    enable: true,
    owner_type: 'group',
    admin_group_id: null,
    user_id: null
  })
  formUserName.value = ''
  formGroupName.value = ''
  formMenuName.value = ''
  formRef.value?.resetFields()
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  const ownerType = row.userId ? 'user' : 'group'
  Object.assign(permForm, {
    id: row.id,
    web_routs_id: row.webRoutsId,
    enable: row.enable,
    owner_type: ownerType,
    admin_group_id: row.adminGroupId || null,
    user_id: row.userId || null
  })
  formUserName.value = row.userId ? `用户 #${row.userId}` : ''
  formGroupName.value = row.adminGroupId ? `组 #${row.adminGroupId}` : ''
  if (row.webRouts) {
    formMenuName.value = `${row.webRouts.title} (${row.webRouts.path})`
  } else {
    formMenuName.value = row.webRoutsId ? `菜单 #${row.webRoutsId}` : ''
  }
}

const handleToggleEnable = async (row) => {
  const newEnable = !row.enable
  const action = newEnable ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm(`确认${action}该菜单权限吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await updateWebRoutsPermission({
      id: row.id,
      enable: newEnable
    })
    if (res.data.code === 200) {
      ElMessage.success(`${action}成功`)
      fetchPermissionList()
    } else {
      ElMessage.error(res.data.message || `${action}失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.response?.data?.message || `${action}失败`)
    }
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该菜单权限吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteWebRoutsPermission({ id: row.id })
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        fetchPermissionList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '删除失败')
    }
  }).catch(() => {})
}

const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      const submitData = {
        web_routs_id: permForm.web_routs_id,
        enable: permForm.enable,
        owner_type: permForm.owner_type
      }
      if (permForm.owner_type === 'user') {
        submitData.user_id = permForm.user_id
      } else {
        submitData.admin_group_id = permForm.admin_group_id
      }

      let res
      if (dialogType.value === 'add') {
        res = await addWebRoutsPermission(submitData)
      } else {
        submitData.id = permForm.id
        res = await updateWebRoutsPermission(submitData)
      }

      if (res.data.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '分配成功' : '修改成功')
        dialogVisible.value = false
        fetchPermissionList()
      } else {
        ElMessage.error(res.data.message || '操作失败')
      }
    } catch (error) {
      ElMessage.error(error.response?.data?.message || '操作失败')
    }
  })
}

</script>

<style scoped>
.menu-permission-container { padding: 0; }
.main-container { border: 1px solid #e1e8ed; background: #ffffff; }
.filter-section { padding: 0; border-bottom: 1px solid #e1e8ed; background: #fafbfc; }
.filter-content { display: flex; justify-content: space-between; align-items: flex-start; padding: 16px 20px; gap: 20px; flex-wrap: wrap; }
.filter-form { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.filter-form :deep(.el-form-item) { margin-bottom: 0; margin-right: 8px; }
.filter-form :deep(.el-form-item__label) { font-size: 13px; }
.action-bar { display: flex; gap: 12px; flex-shrink: 0; }
.selector-inline { display: flex; align-items: center; }
.table-section { padding: 0; }
.action-buttons { display: flex; gap: 8px; align-items: center; }
.text-muted { color: #c0c4cc; }
.dialog-footer { display: flex; justify-content: flex-end; gap: 12px; }
:deep(.el-card__body) { padding: 0; }
:deep(.el-table th) { background: #f8f9fa !important; border-bottom: 2px solid #e1e8ed; color: #2c3e50; font-weight: 600; font-size: 13px; }
:deep(.el-table td) { border-bottom: 1px solid #f0f2f5; color: #34495e; }
:deep(.el-table tr:hover > td) { background-color: #f8f9fa !important; }
</style>
