<template>
  <div class="menu-manage">
    <div class="header">
      <h2>菜单管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增菜单
      </el-button>
    </div>

    <el-table 
      :data="menuList" 
      style="width: 100%" 
      v-loading="loading"
      border
      stripe
      row-key="menuID"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="菜单名称" min-width="200" />
      <el-table-column prop="menuID" label="菜单ID" min-width="150" />
      <el-table-column prop="url" label="菜单路径" min-width="200" show-overflow-tooltip />
      <el-table-column prop="component" label="菜单组件" min-width="200" show-overflow-tooltip />
      <el-table-column prop="icon" label="菜单图标" width="100">
        <template #default="{ row }">
          <el-icon v-if="row.icon">
            <component :is="row.icon" />
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="排序" width="80" />
      <el-table-column prop="type" label="菜单类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getMenuTypeTagType(row.type)" size="small">
            {{ getMenuTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="creatorName" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleAddChild(row)"
            link
          >
            新增子菜单
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleEdit(row)"
            link
          >
            编辑
          </el-button>
          <el-button 
            type="primary" 
            size="small" 
            @click="handleBindPermission(row)"
            link
          >
            绑定权限
          </el-button>
          <el-button 
            type="danger" 
            size="small" 
            @click="handleDelete(row)"
            link
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑菜单' : '新增菜单'"
      width="600px"
      @close="resetForm"
    >
      <el-form 
        ref="formRef"
        :model="formData" 
        :rules="formRules" 
        label-width="100px"
      >
        <el-form-item label="父菜单" prop="parentID">
          <el-cascader
            v-model="formData.parentID"
            :options="parentMenuOptions"
            :props="cascaderProps"
            placeholder="请选择父菜单"
            clearable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input 
            v-model="formData.name" 
            placeholder="请输入菜单名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单描述" prop="description">
          <el-input 
            v-model="formData.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入菜单描述"
          />
        </el-form-item>
        <el-form-item label="菜单路径" prop="url">
          <el-input 
            v-model="formData.url" 
            placeholder="请输入菜单路径"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单组件" prop="component">
          <el-input 
            v-model="formData.component" 
            placeholder="请输入菜单组件"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input 
            v-model="formData.icon" 
            placeholder="请输入菜单图标"
            clearable
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择菜单类型" style="width: 100%">
            <el-option label="侧边栏" :value="0" />
            <el-option label="导航栏" :value="1" />
            <el-option label="按钮" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number 
            v-model="formData.orderNum" 
            :min="0"
            :max="999"
            placeholder="请输入排序"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit"
          :loading="submitting"
        >
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 绑定权限对话框 -->
    <el-dialog v-model="bindPermissionDialogVisible" title="绑定权限" width="800px" @close="resetBindList">
      <div class="permission-binding-container">
        <!-- 菜单信息显示 -->
        <div class="menu-info" v-if="currentMenu">
          <h4>菜单信息：{{ currentMenu.name }}</h4>
          <p>菜单ID：{{ currentMenu.menuID }}</p>
        </div>
        
        <!-- 权限绑定状态表格 -->
        <el-table :data="permissionList" style="width: 100%" border stripe>
          <el-table-column width="80" label="绑定状态">
            <template #default="{ row }">
              <el-tag 
                :type="isPermissionSelected(row.permissionID) ? 'success' : 'info'"
                size="small"
              >
                {{ isPermissionSelected(row.permissionID) ? '已绑定' : '未绑定' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="权限名称" min-width="150" />
          <el-table-column prop="permissionID" label="权限ID" min-width="120" />
          <el-table-column prop="code" label="权限编码" min-width="150" />
          <el-table-column prop="description" label="权限描述" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button 
                :type="isPermissionSelected(row.permissionID) ? 'danger' : 'primary'"
                size="small"
                @click="togglePermissionSelection(row)"
              >
                {{ isPermissionSelected(row.permissionID) ? '解绑' : '绑定' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 统计信息 -->
        <div class="binding-stats">
          <el-alert 
            :title="`已绑定 ${selectedPermissions.length} 个权限，未绑定 ${permissionList.length - selectedPermissions.length} 个权限`"
            type="info"
            :closable="false"
            show-icon
          />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="bindPermissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissionBinding" :loading="submitting">
          保存
        </el-button>
      </template>
    </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { menuApi } from '@/apis/system/menu';
import { permissionApi } from '@/apis/system/permission';
import { SysMenu, SysPermission } from '@/types';
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

// 数据状态
const menuList = ref<SysMenu[]>([]);
const loading = ref(false);
const submitting = ref(false);

// 权限绑定相关数据
const permissionList = ref<SysPermission[]>([]);
const selectedPermissions = ref<string[]>([]);
const currentMenu = ref<SysMenu | null>(null);
const bindList = ref<{ permissions: SysPermission[] }>({
  permissions: []
});

// 对话框状态
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref<FormInstance>();
const bindPermissionDialogVisible = ref(false);

// 表单数据
const formData = reactive<SysMenu>({
  name: '',
  description: '',
  url: '',
  component: '',
  icon: '',
  type: 0,
  orderNum: 0,
  parentID: undefined
});

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  url: [
    { max: 200, message: '菜单路径不能超过 200 个字符', trigger: 'blur' }
  ],
  component: [
    { max: 200, message: '菜单组件不能超过 200 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ]
};

// 级联选择器配置
const cascaderProps = {
  value: 'menuID',
  label: 'name',
  children: 'children',
  checkStrictly: true
};

// 父菜单选项
const parentMenuOptions = computed(() => {
  return buildParentMenuOptions(menuList.value);
});

// 构建父菜单选项
function buildParentMenuOptions(menus: SysMenu[]): any[] {
  return menus.map(menu => ({
    menuID: menu.menuID,
    name: menu.name,
    children: menu.children ? buildParentMenuOptions(menu.children) : undefined
  }));
}

// 获取菜单类型标签类型
function getMenuTypeTagType(type: number | undefined): string {
  switch (type) {
    case 0: return 'primary';
    case 1: return 'success';
    case 2: return 'warning';
    default: return 'info';
  }
}

// 获取菜单类型文本
function getMenuTypeText(type: number | undefined): string {
  switch (type) {
    case 0: return '侧边栏';
    case 1: return '导航栏';
    case 2: return '按钮';
    default: return '未知';
  }
}

// 加载菜单列表
async function loadMenuList() {
  try {
    loading.value = true;
    menuList.value = await menuApi.getAllMenuList();
  } catch (error) {
    console.error('加载菜单列表失败:', error);
    ElMessage.error('加载菜单列表失败');
  } finally {
    loading.value = false;
  }
}

// 新增菜单
function handleAdd() {
  isEdit.value = false;
  formData.parentID = undefined;
  dialogVisible.value = true;
}

// 新增子菜单
function handleAddChild(row: SysMenu) {
  isEdit.value = false;
  formData.parentID = row.menuID;
  dialogVisible.value = true;
}

// 编辑菜单
function handleEdit(row: SysMenu) {
  isEdit.value = true;
  Object.assign(formData, row);
  dialogVisible.value = true;
}

// 删除菜单
async function handleDelete(row: SysMenu) {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    await menuApi.deleteMenu(row.menuID!);
    ElMessage.success('删除成功');
    await loadMenuList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error);
      ElMessage.error('删除菜单失败');
    }
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitting.value = true;
    
    if (isEdit.value) {
      await menuApi.updateMenu(formData);
      ElMessage.success('更新成功');
    } else {
      await menuApi.createMenu(formData);
      ElMessage.success('新增成功');
    }
    
    dialogVisible.value = false;
    await loadMenuList();
  } catch (error) {
    if (error !== false) { // 表单验证失败时error为false
      console.error('提交失败:', error);
      ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
    }
  } finally {
    submitting.value = false;
  }
}

// 重置表单
function resetForm() {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    name: '',
    description: '',
    url: '',
    component: '',
    icon: '',
    type: 0,
    orderNum: 0,
    parentID: undefined
  });
}

// 查看绑定权限
async function handleBindPermission(row: SysMenu) {
  currentMenu.value = row;
  
  try {
    // 获取所有权限
    let permission:SysPermission = {
        permissionID: undefined,
        name: undefined,
        code: undefined,
        description: undefined,
    };
    permissionList.value = await permissionApi.getPermissionList(permission);
    
    // 获取已绑定的权限
    const bindingResult = await menuApi.getMenuPermission(row.menuID!);
    bindList.value.permissions = bindingResult || [];
    
    // 设置已选中的权限
    selectedPermissions.value = bindList.value.permissions.map(permission => permission.permissionID).filter((id): id is string => !!id);
    
    console.log('已绑定的权限:', bindList.value.permissions);
    console.log('所有权限:', permissionList.value);
    bindPermissionDialogVisible.value = true;
  } catch (error) {
    console.error('获取权限绑定信息失败:', error);
    ElMessage.error('获取权限绑定信息失败');
  }
}

// 重置绑定列表
function resetBindList() {
  bindList.value = {
    permissions: []
  };
  selectedPermissions.value = [];
  currentMenu.value = null;
}

// 检查权限是否已选中
function isPermissionSelected(permissionID: string | undefined): boolean {
  return permissionID ? selectedPermissions.value.includes(permissionID) : false;
}

// 切换权限选择状态
function togglePermissionSelection(permission: SysPermission) {
  if (!permission.permissionID) return;
  
  const index = selectedPermissions.value.indexOf(permission.permissionID);
  if (index > -1) {
    selectedPermissions.value.splice(index, 1);
  } else {
    selectedPermissions.value.push(permission.permissionID);
  }
}

// 保存权限绑定
async function savePermissionBinding() {
  if (!currentMenu.value || !currentMenu.value.menuID) {
    ElMessage.error('菜单信息不完整');
    return;
  }
  
  try {
    submitting.value = true;
    
    // 获取当前已绑定的权限ID
    const currentBoundPermissions = (bindList.value.permissions || []).map(permission => permission.permissionID).filter((id): id is string => !!id);
    
    // 找出需要绑定的权限（新增的）
    const permissionsToBind = selectedPermissions.value.filter(permissionID => !currentBoundPermissions.includes(permissionID));
    
    // 找出需要解绑的权限（移除的）
    const permissionsToUnbind = currentBoundPermissions.filter(permissionID => !selectedPermissions.value.includes(permissionID));
    
    // 构建需要绑定的权限对象数组
    if (permissionsToBind.length > 0) {
      const permissionsToBindObjects = permissionsToBind.map(permissionID => {
        const permission = permissionList.value.find(p => p.permissionID === permissionID);
        return permission || { permissionID: permissionID };
      });
      
      const bindMenu = {
        ...currentMenu.value,
        permissions: permissionsToBindObjects,
        menus: [{menuID: currentMenu.value.menuID}]
      };
      await permissionApi.bindMenu(bindMenu);
    }
    
    // 构建需要解绑的权限对象数组
    if (permissionsToUnbind.length > 0) {
      const permissionsToUnbindObjects = permissionsToUnbind.map(permissionID => {
        const permission = permissionList.value.find(p => p.permissionID === permissionID);
        return permission || { permissionID: permissionID };
      });
      
      const unbindMenu = {
        ...currentMenu.value,
        permissions: permissionsToUnbindObjects,
        menus: [{menuID: currentMenu.value.menuID}]
      };
      await permissionApi.unbindMenu(unbindMenu);
    }
    
    ElMessage.success('权限绑定保存成功');
    bindPermissionDialogVisible.value = false;
    
    // 刷新菜单列表
    await loadMenuList();
  } catch (error) {
    console.error('保存权限绑定失败:', error);
    ElMessage.error('保存权限绑定失败');
  } finally {
    submitting.value = false;
  }
}

// 页面加载时获取菜单列表
onMounted(() => {
  loadMenuList();
});
</script>

<style scoped lang="scss">
.menu-manage {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }
  }
  
  .el-table {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  .el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #ebeef5;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-dialog__body {
    padding: 20px;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px;
    border-top: 1px solid #ebeef5;
  }
}

// 表单样式优化
:deep(.el-form) {
  .el-form-item__label {
    font-weight: 500;
    color: #606266;
  }
  
  .el-input__wrapper {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &.is-focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
  
  .el-textarea__inner {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    
    &:hover {
      box-shadow: 0 0 0 1px #c0c4cc inset;
    }
    
    &:focus {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
}

// 按钮样式优化
:deep(.el-button) {
  &.is-link {
    padding: 0;
    margin-right: 12px;
    
    &:last-child {
      margin-right: 0;
    }
  }
}

// 权限绑定容器样式
.permission-binding-container {
  .menu-info {
    background: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    
    h4 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 16px;
    }
    
    p {
      margin: 0;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .binding-stats {
    margin-top: 20px;
  }
}
</style>