<template>
  <div class="p-2">
    <el-row :gutter="20">
      <!-- 菜单树 -->
      <el-col :lg="4" :xs="24">
        <el-card shadow="hover" class="menu-tree-card">
          <!-- 菜单树头部 -->
          <template #header>
            <div class="menu-tree-header">
              <span class="menu-tree-title">功能菜单</span>
              <div class="menu-tree-actions"></div>
            </div>
          </template>

          <!-- 搜索框 -->
          <div class="menu-search-box">
            <el-input v-model="menuName" placeholder="搜索菜单..." prefix-icon="Search" clearable size="small" @clear="handleSearchClear" />
          </div>

          <!-- 菜单树容器 -->
          <div class="menu-tree-container">
            <el-scrollbar height="100%">
              <el-tree
                ref="menuTreeRef"
                class="menu-tree"
                node-key="menuId"
                :data="menuOptions"
                :props="{ label: 'menuName', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                :default-expanded-keys="defaultExpandedKeys"
                highlight-current
                accordion
                @node-click="handleNodeClick"
                @node-expand="handleNodeExpand"
                @node-collapse="handleNodeCollapse"
              >
                <template #default="{ node, data }">
                  <div class="menu-tree-node">
                    <el-icon class="menu-node-icon">
                      <component :is="getMenuIcon(data)" />
                    </el-icon>
                    <span class="menu-node-label" :title="node.label">
                      {{ node.label }}
                    </span>
                    <el-badge v-if="data.videoCount > 0" :value="data.videoCount" :max="99" class="menu-badge" type="primary" />
                  </div>
                </template>
              </el-tree>

              <!-- 空状态 -->
              <el-empty v-if="filteredMenuCount === 0 && menuName" description="未找到匹配的菜单" :image-size="60" />
            </el-scrollbar>
          </div>

          <!-- 菜单统计信息 -->
          <div class="menu-tree-footer">
            <el-text size="small" type="info">
              共 {{ totalMenuCount }} 个菜单
              <span v-if="menuName">，筛选出 {{ filteredMenuCount }} 个</span>
            </el-text>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :lg="20" :xs="24">
        <!-- 搜索区域 -->
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="渠道" prop="branchType">
                  <i-select v-model="queryParams.branchType" dict-type="branchtype"></i-select>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>

        <!-- 视频列表 -->
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd">视频上传</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" v-hasPermi="['video:userVideoPlay:query']" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" v-hasPermi="['video:userVideoPlay:remove']" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
              </el-col>
              <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <!-- 视频列表表格部分的修改 -->
          <el-table v-loading="loading" :data="userVideoList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column v-if="false" label="ID" align="center" prop="id" />

            <!-- 使用新的字段显示渠道名称 -->
            <el-table-column label="渠道" align="center" prop="branchTypeName" width="100" />

            <!-- 使用新的字段显示菜单名称 -->
            <el-table-column label="菜单名称" align="center" prop="menuName" min-width="200" />

            <el-table-column label="时长" align="center" prop="duration" width="80" />
            <el-table-column label="说明" align="center" prop="description" min-width="120" show-overflow-tooltip />

            <el-table-column label="操作" width="150" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="播放" placement="top">
                  <el-button link type="primary" icon="VideoPlay" @click="handleVideoPlay(scope.row)">播放</el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            :total="total"
            @pagination="getList"
          />
        </el-card>

        <!-- 引入视频表单组件 -->
        <video-form v-model:visible="formVisible" :edit-type="editType" :row-data="currentRow" :menu-options="menuOptions" @save="handleSave" />

        <!-- 视频播放对话框 -->
        <el-dialog v-model="dialogVisible" title="视频播放" width="680" append-to-body>
          <video ref="videoRef" :src="videoUrl" width="650" height="380" autoplay controls></video>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Video" lang="ts">
import { listUserVideoInfo, deleteVideoInfo, queryVideoUrl } from '@/api/system/video';
import { listMenu } from '@/api/system/menu';
import { UserVideoPlayQuery, UserVideoPlayVO } from '@/api/system/video/types';
import ISelect from '@/views/modules/common/ISelect.vue';
import VideoForm from './videoForm.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_branch_type, sys_upload_state } = toRefs<any>(proxy?.useDict('sys_branch_type', 'sys_upload_state'));

// 表单控制状态
const formVisible = ref(false);
const editType = ref('');
const currentRow = ref<UserVideoPlayVO | null>(null);

// 视频播放相关
const dialogVisible = ref(false);
const videoUrl = ref('');
const videoRef = ref<HTMLVideoElement>();

// 列表数据
const userVideoList = ref<UserVideoPlayVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

// 菜单树相关状态
const menuName = ref('');
const menuOptions = ref<any[]>([]);
const menuTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const defaultExpandedKeys = ref<number[]>([]);
const expandedKeys = ref<Set<number>>(new Set());
const totalMenuCount = ref(0);
const filteredMenuCount = ref(0);

// 查询参数
const queryParams = reactive<UserVideoPlayQuery>({
  pageNum: 1,
  pageSize: 10,
  branchType: '2',
  menuId: undefined,
  state: undefined,
  belongMenuId: undefined
});

// 菜单图标映射
const menuIconMap = {
  'M': 'Folder', // 目录
  'C': 'Document', // 菜单
  'default': 'Files'
};

/** 获取菜单图标 */
const getMenuIcon = (menuData: any) => {
  return menuIconMap[menuData.menuType] || menuIconMap.default;
};

/** 通过条件过滤节点 */
const filterNode = (value: string, data: any) => {
  if (!value) {
    filteredMenuCount.value = totalMenuCount.value;
    return true;
  }

  const match = data.menuName.toLowerCase().includes(value.toLowerCase());

  // 递归检查子节点是否匹配
  const hasMatchingChild = (node: any): boolean => {
    if (!node.children) return false;
    return node.children.some((child: any) => child.menuName.toLowerCase().includes(value.toLowerCase()) || hasMatchingChild(child));
  };

  return match || hasMatchingChild(data);
};

/** 根据名称筛选菜单树 */
watchEffect(
  () => {
    if (menuTreeRef.value) {
      menuTreeRef.value.filter(menuName.value);

      // 计算筛选后的菜单数量
      if (menuName.value) {
        updateFilteredCount();
      }
    }
  },
  { flush: 'post' }
);

/** 更新筛选后的菜单数量 */
const updateFilteredCount = () => {
  const countFilteredNodes = (nodes: any[]): number => {
    let count = 0;
    nodes.forEach((node) => {
      if (filterNode(menuName.value, node)) {
        count++;
        if (node.children) {
          count += countFilteredNodes(node.children);
        }
      }
    });
    return count;
  };

  const rootMenu = menuOptions.value[0];
  if (rootMenu && rootMenu.children) {
    filteredMenuCount.value = countFilteredNodes(rootMenu.children);
  }
};

/** 计算菜单总数 */
const countTotalMenus = (nodes: any[]): number => {
  let count = 0;
  nodes.forEach((node) => {
    count++;
    if (node.children && node.children.length > 0) {
      count += countTotalMenus(node.children);
    }
  });
  return count;
};

/** 查询菜单下拉树结构 */
const getTreeSelect = async () => {
  const response = await listMenu();

  // 过滤掉按钮类型(F)的菜单项，只保留目录(M)和菜单(C)
  const filteredMenus = response.data.filter((menu) => menu.menuType !== 'F');

  const menu = { menuId: 0, menuName: '功能菜单', children: [] };
  menu.children = proxy?.handleTree(filteredMenus, 'menuId');
  menuOptions.value = [menu];

  // 计算菜单总数
  if (menu.children) {
    totalMenuCount.value = countTotalMenus(menu.children);
    filteredMenuCount.value = totalMenuCount.value;
  }

  // 设置默认展开的节点（只展开第一级）
  setDefaultExpandedKeys();
};

/** 设置默认展开的节点 */
const setDefaultExpandedKeys = () => {
  const keys: number[] = [];
  const rootMenu = menuOptions.value[0];

  if (rootMenu && rootMenu.children) {
    // 只展开根节点和第一级子节点
    keys.push(rootMenu.menuId);
    rootMenu.children.forEach((child: any) => {
      if (child.children && child.children.length > 0) {
        keys.push(child.menuId);
      }
    });
  }

  defaultExpandedKeys.value = keys.slice(0, 5); // 最多展开5个节点
  expandedKeys.value = new Set(defaultExpandedKeys.value);
};

/** 展开所有节点 */
const expandAllNodes = () => {
  const getAllKeys = (nodes: any[]): number[] => {
    let keys: number[] = [];
    nodes.forEach((node) => {
      keys.push(node.menuId);
      if (node.children && node.children.length > 0) {
        keys = keys.concat(getAllKeys(node.children));
      }
    });
    return keys;
  };

  const rootMenu = menuOptions.value[0];
  if (rootMenu && rootMenu.children) {
    const allKeys = getAllKeys([rootMenu]);
    allKeys.forEach((key) => {
      menuTreeRef.value?.setNodeExpanded(key, true);
      expandedKeys.value.add(key);
    });
  }

  proxy?.$modal.msgSuccess('已展开所有菜单');
};

/** 收起所有节点 */
const collapseAllNodes = () => {
  expandedKeys.value.forEach((key) => {
    menuTreeRef.value?.setNodeExpanded(key, false);
  });
  expandedKeys.value.clear();

  // 保持根节点展开
  const rootMenu = menuOptions.value[0];
  if (rootMenu) {
    menuTreeRef.value?.setNodeExpanded(rootMenu.menuId, true);
    expandedKeys.value.add(rootMenu.menuId);
  }

  proxy?.$modal.msgSuccess('已收起所有菜单');
};

/** 节点展开事件 */
const handleNodeExpand = (data: any) => {
  expandedKeys.value.add(data.menuId);
};

/** 节点收起事件 */
const handleNodeCollapse = (data: any) => {
  expandedKeys.value.delete(data.menuId);
};

/** 清空搜索 */
const handleSearchClear = () => {
  filteredMenuCount.value = totalMenuCount.value;
};

/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  // 只有菜单类型(C)才能被选中查询
  if (data.menuType === 'C') {
    queryParams.belongMenuId = data.menuId;
    queryParams.menuId = undefined;
    handleQuery();
  } else if (data.menuType === 'M') {
    // 目录类型，切换展开/收起状态
    const isExpanded = expandedKeys.value.has(data.menuId);
    menuTreeRef.value?.setNodeExpanded(data.menuId, !isExpanded);
  }
};

/** 查询视频列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listUserVideoInfo(queryParams);
    userVideoList.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  if (queryParams.menuId) {
    queryParams.belongMenuId = undefined;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  queryParams.menuId = undefined;
  menuTreeRef.value?.setCurrentKey(undefined);
  queryParams.belongMenuId = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UserVideoPlayVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  currentRow.value = null;
  editType.value = 'add';
  formVisible.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row?: UserVideoPlayVO) => {
  if (row) {
    currentRow.value = row;
  } else {
    const selectedVideo = userVideoList.value.find((item) => item.id === ids.value[0]);
    currentRow.value = selectedVideo || null;
  }
  editType.value = 'edit';
  formVisible.value = true;
};

/** 保存成功后的处理 */
const handleSave = () => {
  getList();
};

/** 播放视频 */
const handleVideoPlay = async (row: UserVideoPlayVO) => {
  try {
    const res = await queryVideoUrl(row);
    videoUrl.value = res.msg;
    dialogVisible.value = true;
  } catch (error) {
    proxy?.$modal.msgError('获取视频地址失败');
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: UserVideoPlayVO) => {
  const videoIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的视频数据？');
  await deleteVideoInfo(videoIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getTreeSelect();
  getList();
});
</script>

<style scoped>
/* 菜单树卡片 */
.menu-tree-card {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.menu-tree-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 菜单树头部 */
.menu-tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.menu-tree-title {
  font-weight: 500;
  color: #303133;
}

.menu-tree-actions {
  display: flex;
  gap: 4px;
}

/* 搜索框 */
.menu-search-box {
  padding: 12px 16px 8px;
  border-bottom: 1px solid #f0f0f0;
}

/* 菜单树容器 */
.menu-tree-container {
  flex: 1;
  overflow: hidden;
  padding: 8px 0;
}

.menu-tree {
  padding: 0 12px;
}

/* 菜单树节点 */
.menu-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  padding-right: 8px;
}

.menu-node-icon {
  margin-right: 6px;
  font-size: 14px;
  color: #606266;
  flex-shrink: 0;
}

.menu-node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-size: 13px;
}

.menu-badge {
  margin-left: 4px;
  flex-shrink: 0;
}

/* 菜单树底部 */
.menu-tree-footer {
  padding: 8px 16px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
  text-align: center;
}

/* 自定义滚动条 */
.menu-tree-container :deep(.el-scrollbar__bar) {
  right: 0;
  border-radius: 4px;
}

.menu-tree-container :deep(.el-scrollbar__thumb) {
  background-color: rgba(144, 147, 153, 0.3);
  border-radius: 4px;
}

.menu-tree-container :deep(.el-scrollbar__thumb:hover) {
  background-color: rgba(144, 147, 153, 0.5);
}

/* 树节点样式优化 */
.menu-tree :deep(.el-tree-node__content) {
  height: 32px;
  border-radius: 4px;
  margin: 1px 0;
  transition: background-color 0.2s;
}

.menu-tree :deep(.el-tree-node__content:hover) {
  background-color: #f5f7fa;
}

.menu-tree :deep(.is-current > .el-tree-node__content) {
  background-color: #ecf5ff;
  color: #409eff;
}

.menu-tree :deep(.el-tree-node__expand-icon) {
  padding: 6px;
  font-size: 12px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .menu-tree-card {
    height: auto;
    max-height: 400px;
  }

  .menu-tree-container {
    max-height: 300px;
  }

  .menu-tree-actions {
    display: none;
  }
}

/* 空状态样式 */
.menu-tree-container :deep(.el-empty) {
  padding: 20px;
}

.menu-tree-container :deep(.el-empty__description) {
  font-size: 12px;
  color: #909399;
}

:deep(.el-tree-select) {
  width: 100%;
}
</style>
