<template>
  <div class="data-select-root">
    <el-dialog
      title="选择数据"
      :visible.sync="dialogVisible"
      width="1200px"
      :close-on-click-modal="false"
      @close="handleClose"
      class="data-select-dialog"
    >
      <div class="data-select-container">
        <!-- 左侧三层样本树 -->
        <div class="sample-tree-panel">
          <h3 class="panel-title">样本数据</h3>
          <!-- 空数据提示 -->
          <div v-if="!sampleTreeData.length" class="tree-empty-tip">暂无样本数据</div>
          <el-tree
            v-else
            ref="sampleTree"
            :data="sampleTreeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-expand-all="true"
            :key="treeKey"
            :check-strictly="false"
            @check-change="handleTreeCheckChange"
          >
            <template slot-scope="{ node }">
              <el-tooltip
                class="tree-tooltip"
                effect="dark"
                :content="node.label"
                placement="right"
                :disabled="getNodeLabelDisabled(node.label)"
              >
                <span :style="{ color: node.disabled ? '#ccc' : 'inherit' }">{{ node.label }}</span>
              </el-tooltip>
            </template>
          </el-tree>
        </div>

        <!-- 右侧图片列表 -->
        <div class="sample-image-panel">
          <div class="select-header">
            <el-checkbox
              v-model="selectAllPage"
              @change="handleSelectAllPage"
              :disabled="isSelectAllDisabled"
            >
              选择本页
            </el-checkbox>
            <span class="select-count">已选中{{ selectedDataCount }}条，共{{ totalCount }}条</span>
          </div>

          <!-- 空图片提示 -->
          <div v-if="!imageList.length && totalCount === 0" class="image-empty-tip">暂无图片数据</div>
          <div v-else class="image-grid">
            <div class="image-item" v-for="item in imageList" :key="item.id">
              <div class="image-wrapper">
                <img :src="item.filePath" alt="样本图片" class="sample-image" />
              </div>
              <div class="image-footer">
                <el-tooltip
                  effect="dark"
                  :content="item.fileName || item.label"
                  placement="top"
                  :disabled="getImageNameDisabled(item)"
                >
                  <span class="image-name">{{ item.fileName || item.label }}</span>
                </el-tooltip>
                <div class="image-actions">
                  <el-checkbox
                    v-model="item.checked"
                    @change="() => handleImageCheck(item)"
                    size="mini"
                    :disabled="getImageCheckboxDisabled(item)"
                  ></el-checkbox>
                  <el-button
                    type="text"
                    icon="el-icon-view"
                    size="mini"
                    @click="openFullScreenImage(item)"
                    class="preview-btn"
                  ></el-button>
                </div>
              </div>
            </div>
          </div>

          <el-pagination
            v-if="totalCount > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            style="margin-top: 20px; text-align: right"
          >
          </el-pagination>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 全屏图片预览弹窗 -->
    <div v-if="fullScreenImageVisible" class="full-screen-image-modal" @click="closeFullScreenImage">
      <div class="full-screen-image-content" @click.stop>
        <el-button
          type="text"
          icon="el-icon-close"
          class="full-screen-close-btn"
          @click="closeFullScreenImage"
        ></el-button>
        <img :src="fullScreenImageUrl" alt="全屏预览图片" class="full-screen-img" />
        <div class="full-screen-img-name">{{ fullScreenImageName }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { getSampleTreeAPI, getSampleImageListAPI } from '@/api/data/sample'
import { getSampleListByVersionIdAPI } from '@/api/data/dataset'

export default {
  name: "DataSelectDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedIds: {
      type: String,
      default: ""
    },
    sampleLibraryIds: {
      type: Array,
      default: () => []
    },
    changeType: { // 变更类型：1-新增 2-减少（仅版本操作时生效）
      type: String,
      default: "1"
    },
    datasetVersionId: { // 数据集版本ID（有值=版本操作，无值=普通新增数据集）
      type: [String, Number],
      default: ""
    }
  },
  data() {
    return {
      dialogVisible: this.visible,
      treeProps: {
        label: "label",
        children: "children",
        disabled: (nodeData) => this.getTreeNodeDisabled(nodeData) // 节点禁用逻辑
      },
      sampleTreeData: [],
      rawTreeData: [],
      imageList: [],
      allImageList: [],
      currentPage: 1,
      pageSize: 10,
      totalCount: 0,
      selectAllPage: false,
      selectedDataCount: 0,
      checkedImageIds: [],
      treeKey: Date.now(),
      queryParams: {
        sampleLibraryIds: "",
        sampleLabel: null
      },
      // 图片ID → 树节点ID的精准映射（仅关联自身三级节点）
      imageToTreeNodeMap: {},
      // 版本初始选中的样本ID（不可修改）
      versionInitialSelectedIds: [],
      // 全屏预览
      fullScreenImageVisible: false,
      fullScreenImageUrl: "",
      fullScreenImageName: ""
    };
  },
  computed: {
    // 判断是否为版本操作（有版本ID=是，无=普通新增）
    isVersionOperation() {
      return !!this.datasetVersionId;
    },
    // 全选按钮是否禁用
    isSelectAllDisabled() {
      if (!this.isVersionOperation) {
        return false;
      }
      return this.changeType === '2';
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal;
        if (newVal) {
          // 确保DOM更新后再初始化数据，避免状态丢失
          this.$nextTick(() => {
            this.initData();
          });
        } else {
          this.resetState();
        }
      },
      immediate: true
    },
    selectedIds: {
      handler(newVal) {
        if (newVal && newVal.trim()) {
          const newCheckedIds = newVal.split(",").map(id => Number(id)).filter(id => !isNaN(id));
          this.checkedImageIds = newCheckedIds;
          // 仅版本操作时存储初始选中ID
          if (this.isVersionOperation) {
            this.versionInitialSelectedIds = [...newCheckedIds];
          }
          // 确保DOM更新后同步状态
          this.$nextTick(() => {
            this.updateSelectedCount();
            this.syncCheckedState();
            this.syncTreeCheckedState(); // 初始同步树节点
          });
        } else {
          this.checkedImageIds = [];
          this.versionInitialSelectedIds = [];
          this.updateSelectedCount();
          this.syncTreeCheckedState(); // 清空树节点选中
        }
      },
      immediate: true
    },
    sampleLibraryIds: {
      handler(newVal) {
        if (this.dialogVisible && newVal && newVal.length > 0) {
          this.queryParams.sampleLibraryIds = newVal.join(",");
          this.treeKey = Date.now();
          // 确保DOM更新后重新初始化
          this.$nextTick(() => {
            this.initData();
          });
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    /** 树节点tooltip禁用判断 */
    getNodeLabelDisabled(label) {
      return label && label.length <= 10;
    },
    /** 图片名tooltip禁用判断 */
    getImageNameDisabled(item) {
      const name = item.fileName || item.label;
      return name && name.length <= 8;
    },
    /** 判断图片复选框是否禁用 */
    getImageCheckboxDisabled(item) {
      // 空值保护
      if (!item || !item.id) return true;

      // 普通新增数据集：不禁用任何复选框
      if (!this.isVersionOperation) {
        return false;
      }

      const itemId = Number(item.id);
      if (this.changeType === '1') {
        // 版本新增：初始已选的不可取消
        return this.versionInitialSelectedIds.includes(itemId);
      } else if (this.changeType === '2') {
        // 版本减少：初始未选的不可勾选
        return !this.versionInitialSelectedIds.includes(itemId);
      }
      return false;
    },
    /** 树节点禁用逻辑（添加空值保护） */
    getTreeNodeDisabled(nodeData) {
      // 空值保护：节点数据不存在时直接返回false
      if (!nodeData) return false;

      // 非版本操作：不禁用
      if (!this.isVersionOperation) {
        return false;
      }

      // 一级/二级节点：版本减少时禁用
      if (nodeData.type === 'library' || nodeData.type === 'label_combined') {
        return this.changeType === '2';
      }

      // 三级图片节点：和右侧图片复选框禁用逻辑一致
      const sampleId = Number(nodeData.sampleId);
      // 空值保护
      if (isNaN(sampleId)) return false;

      if (this.changeType === '1') {
        return this.versionInitialSelectedIds.includes(sampleId);
      } else if (this.changeType === '2') {
        return !this.versionInitialSelectedIds.includes(sampleId);
      }
      return false;
    },
    /** 重置所有状态 */
    resetState() {
      this.currentPage = 1;
      this.pageSize = 10;
      this.selectAllPage = false;
      this.imageList = [];
      this.allImageList = [];
      this.totalCount = 0;
      // 保留checkedImageIds，避免重新打开时丢失
      // this.checkedImageIds = [];
      this.versionInitialSelectedIds = [];
      this.selectedDataCount = 0;
      this.rawTreeData = [];
      this.sampleTreeData = [];
      this.treeKey = Date.now();
      this.queryParams = {
        sampleLibraryIds: "",
        sampleLabel: null
      };
      this.imageToTreeNodeMap = {};
      // 重置全屏预览
      this.fullScreenImageVisible = false;
      this.fullScreenImageUrl = "";
      this.fullScreenImageName = "";
    },

    /** 初始化数据（调整同步顺序，确保状态正确） */
    async initData() {
      if (!this.dialogVisible || !this.sampleLibraryIds.length) return;
      // 仅重置分页和临时状态，保留选中ID
      this.currentPage = 1;
      this.selectAllPage = false;
      this.rawTreeData = [];
      this.sampleTreeData = [];
      this.imageToTreeNodeMap = {};
      this.queryParams.sampleLibraryIds = this.sampleLibraryIds.join(",");

      try {
        // 1. 版本操作时，先获取版本已选样本
        if (this.isVersionOperation) {
          await this.getVersionSampleData();
        }
        // 2. 获取树形数据
        await this.getSampleTreeData();
        this.assembleStrictThreeLevelTree();
        // 3. 加载图片数据
        await this.loadAllImageData();
        // 4. 先构建映射，再同步状态（核心修复）
        this.buildImageToTreeNodeMap();
        // 5. 确保DOM更新后同步状态
        this.$nextTick(() => {
          this.syncCheckedState();
          this.syncTreeCheckedState();
        });
      } catch (error) {
        console.error("加载数据失败：", error);
        this.$message.error("加载数据失败，请稍后重试");
      }
    },

    /** 获取版本已选样本数据 */
    async getVersionSampleData() {
      try {
        const res = await getSampleListByVersionIdAPI({
          datasetVersionId: this.datasetVersionId,
          pageNum: 1,
          pageSize: 9999
        });
        if (res && res.code === 200 && res.rows && res.rows.length) {
          const versionIds = res.rows.map(item => Number(item.sampleId)).filter(id => !isNaN(id));
          this.versionInitialSelectedIds = versionIds;
          // 合并已选中的ID，避免覆盖
          this.checkedImageIds = [...new Set([...this.checkedImageIds, ...versionIds])];
        }
      } catch (error) {
        console.error("获取版本样本数据失败：", error);
      }
    },

    /** 获取后端原始树形数据 */
    async getSampleTreeData() {
      try {
        const res = await getSampleTreeAPI(this.queryParams);
        if (res && res.code === 200 && Array.isArray(res.data)) {
          const uniqueMap = new Map();
          res.data.forEach(item => {
            if (item.id && !uniqueMap.has(item.id)) {
              uniqueMap.set(item.id, item);
            }
          });
          this.rawTreeData = Array.from(uniqueMap.values());
        } else {
          this.rawTreeData = [];
        }
      } catch (error) {
        console.error("获取样本树数据失败：", error);
        this.rawTreeData = [];
        this.$message.error("获取样本分类数据失败");
      }
    },

    /** 组装三层树形结构 */
    assembleStrictThreeLevelTree() {
      if (!this.rawTreeData.length) {
        this.sampleTreeData = [];
        return;
      }

      const libraryNodes = this.rawTreeData.filter(item => item.type === 'library');
      const labelNodes = this.rawTreeData.filter(item => item.type === 'label');
      const sampleNodes = this.rawTreeData.filter(item => item.type === 'image');

      this.sampleTreeData = libraryNodes.map(library => {
        const libraryId = library.libraryId;
        const childLabels = labelNodes.filter(label => label.libraryId === libraryId);

        // 合并标签名
        const labelNames = childLabels.map(item => item.label || item.labelName || '未知标签').filter(Boolean);
        const combinedLabelName = labelNames.length ? labelNames.join('、') : '无标签';

        // 每个样本保留独立的三级节点
        const allSamplesInLibrary = sampleNodes.filter(sample => sample.libraryId === libraryId)
          .map(sample => ({
            id: sample.id, // 样本唯一ID
            label: sample.label || sample.fileName || '未知样本',
            type: 'image',
            libraryId: sample.libraryId,
            sampleId: Number(sample.id.replace('sample_', '')) || sample.id, // 纯数字ID
            filePath: sample.filePath,
            children: []
          }));

        // 合并标签节点（二级）
        const combinedLabelNode = {
          id: `combined_label_${libraryId}`,
          label: combinedLabelName,
          type: 'label_combined',
          libraryId: libraryId,
          children: allSamplesInLibrary
        };

        // 一级样本库节点
        return {
          id: library.id,
          label: library.label || '未知样本库',
          type: 'library',
          libraryId: library.libraryId,
          children: [combinedLabelNode]
        };
      });
    },

    /** 构建精准映射 */
    buildImageToTreeNodeMap() {
      this.imageToTreeNodeMap = {};

      // 递归遍历树节点，仅映射图片ID到自身三级节点ID
      const traverseTree = (nodes) => {
        nodes.forEach(node => {
          // 空值保护
          if (!node) return;

          if (node.type === 'image') {
            // 仅关联图片ID和自身三级节点ID，不关联父节点
            this.imageToTreeNodeMap[node.sampleId] = node.id;
          }
          if (node.children && node.children.length) {
            traverseTree(node.children);
          }
        });
      };

      traverseTree(this.sampleTreeData);
    },

    /** 加载全量图片数据（优化选中状态回填） */
    async loadAllImageData() {
      let allData = [];
      let pageNum = 1;
      const pageSize = 100;
      let hasMore = true;

      try {
        while (hasMore) {
          const params = {
            pageNum,
            pageSize,
            sampleLibraryIds: this.queryParams.sampleLibraryIds
          };
          const res = await getSampleImageListAPI(params);
          if (res && res.code === 200) {
            const tableData = res || {};
            const rows = Array.isArray(tableData.rows) ? tableData.rows : [];

            const handleRows = rows.map(item => {
              const itemId = Number(item.id) || item.id;
              const fileName = item.fileName ? item.fileName.replace(/\.[^/.]+$/, '') : '未知图片';
              // 核心修复：直接从checkedImageIds获取选中状态
              const isChecked = this.checkedImageIds.includes(Number(itemId));

              return {
                ...item,
                id: itemId,
                fileName: fileName,
                libraryId: Number(item.sample_library_id) || 0,
                checked: isChecked // 直接赋值，不再依赖后续同步
              };
            });
            allData = [...allData, ...handleRows];

            hasMore = pageNum * pageSize < (tableData.total || 0);
            pageNum++;
          } else {
            hasMore = false;
          }
        }

        this.allImageList = allData;
        this.totalCount = this.allImageList.length;
        this.updateImageListByPage();
        this.updateSelectAllStatus();
        this.updateSelectedCount();
      } catch (error) {
        console.error("加载全量图片失败：", error);
        this.allImageList = [];
        this.imageList = [];
        this.totalCount = 0;
        this.$message.error("获取样本图片列表失败");
      }
    },

    /** 更新当前页图片列表 */
    updateImageListByPage() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.imageList = JSON.parse(JSON.stringify(this.allImageList.slice(start, end)));
    },

    /** 树节点勾选事件（修复参数错误+空值保护+版本禁用过滤） */
    handleTreeCheckChange(nodeData, checked) {
      // 空值保护：节点数据不存在时直接返回
      if (!nodeData) return;

      // 禁用的节点不处理勾选事件
      if (this.getTreeNodeDisabled(nodeData)) {
        return;
      }

      if (checked) {
        let filterImageIds = [];
        // 一级/二级节点：全选对应范围图片
        if (nodeData.type === 'library') {
          filterImageIds = this.allImageList
            .filter(img => img.libraryId === nodeData.libraryId)
            .map(img => img.id);
        } else if (nodeData.type === 'label_combined') {
          filterImageIds = this.allImageList
            .filter(img => img.libraryId === nodeData.libraryId)
            .map(img => img.id);
        }
        // 三级节点：仅选中当前图片
        else if (nodeData.type === 'image') {
          filterImageIds = [nodeData.sampleId];
        }

        // 合并选中ID（避免重复+版本禁用过滤）
        filterImageIds.forEach(id => {
          const numId = Number(id);
          // 跳过禁用的图片和无效ID
          if (!isNaN(numId) && !this.checkedImageIds.includes(numId) && !this.getImageCheckboxDisabled({ id: numId })) {
            this.checkedImageIds.push(numId);
          }
        });
      } else {
        // 取消勾选逻辑（原始逻辑+版本禁用过滤）
        if (nodeData.type === 'library') {
          this.checkedImageIds = this.checkedImageIds.filter(id => {
            const img = this.allImageList.find(item => item.id === id);
            // 跳过禁用的图片
            if (this.getImageCheckboxDisabled({ id })) return true;
            return !img || img.libraryId !== nodeData.libraryId;
          });
        } else if (nodeData.type === 'label_combined') {
          this.checkedImageIds = this.checkedImageIds.filter(id => {
            const img = this.allImageList.find(item => item.id === id);
            // 跳过禁用的图片
            if (this.getImageCheckboxDisabled({ id })) return true;
            return !img || img.libraryId !== nodeData.libraryId;
          });
        }
        // 三级节点：仅取消当前图片
        else if (nodeData.type === 'image') {
          const sampleId = Number(nodeData.sampleId);
          // 跳过禁用的图片和无效ID
          if (!isNaN(sampleId) && !this.getImageCheckboxDisabled({ id: sampleId })) {
            this.checkedImageIds = this.checkedImageIds.filter(id => id !== sampleId);
          }
        }
      }

      this.syncCheckedState();
      this.updateSelectedCount();
    },

    /** 同步树节点选中状态（优化空值保护） */
    syncTreeCheckedState() {
      if (!this.$refs.sampleTree || !this.imageToTreeNodeMap) return;

      const tree = this.$refs.sampleTree;
      // 仅选中当前勾选图片对应的三级节点
      const checkedNodeIds = this.checkedImageIds
        .map(imgId => this.imageToTreeNodeMap[imgId])
        .filter(id => id); // 过滤无效ID

      // 全量更新树节点选中状态（支持取消）
      tree.setCheckedKeys(checkedNodeIds, false);
    },

    /** 同步图片选中状态（确保全量更新） */
    syncCheckedState() {
      if (!Array.isArray(this.allImageList)) return;

      this.allImageList = this.allImageList.map(img => ({
        ...img,
        checked: this.checkedImageIds.includes(Number(img.id))
      }));

      this.updateImageListByPage();
      this.updateSelectAllStatus();
      this.$forceUpdate();
    },

    /** 更新全选状态 */
    updateSelectAllStatus() {
      this.selectAllPage = this.imageList.length > 0 && this.imageList.every(item => item.checked);
    },

    /** 更新选中数量 */
    updateSelectedCount() {
      this.checkedImageIds = [...new Set(this.checkedImageIds)]
        .filter(id => !isNaN(id) && id > 0);
      this.selectedDataCount = this.checkedImageIds.length;
    },

    /** 本页全选（版本禁用过滤） */
    handleSelectAllPage(checked) {
      if (!Array.isArray(this.imageList) || this.imageList.length === 0) return;

      this.imageList.forEach(item => {
        // 空值保护
        if (!item) return;

        const itemId = Number(item.id);
        // 跳过禁用的项和无效ID
        if (isNaN(itemId) || this.getImageCheckboxDisabled(item)) {
          return;
        }

        item.checked = checked;

        // 更新全量图片状态
        this.allImageList = this.allImageList.map(img => {
          if (img.id === itemId) {
            return { ...img, checked };
          }
          return img;
        });

        // 更新选中ID列表
        const index = this.checkedImageIds.indexOf(itemId);
        if (checked && index === -1) {
          this.checkedImageIds.push(itemId);
        } else if (!checked && index !== -1) {
          this.checkedImageIds.splice(index, 1);
        }
      });

      this.syncTreeCheckedState(); // 同步树节点（支持取消）
      this.updateSelectedCount();
      this.$forceUpdate();
    },

    /** 单个图片勾选（优化空值保护） */
    handleImageCheck(item) {
      // 空值保护
      if (!item || !item.id) return;

      const itemId = Number(item.id);
      // 无效ID保护
      if (isNaN(itemId)) return;

      // 禁用的项不处理
      if (this.getImageCheckboxDisabled(item)) {
        return;
      }

      // 更新全量图片状态
      this.allImageList = this.allImageList.map(img => {
        if (img.id === itemId) {
          return { ...img, checked: item.checked };
        }
        return img;
      });

      // 更新选中ID列表（支持取消）
      const index = this.checkedImageIds.indexOf(itemId);
      if (item.checked && index === -1) {
        this.checkedImageIds.push(itemId);
      } else if (!item.checked && index !== -1) {
        this.checkedImageIds.splice(index, 1);
      }

      // 同步树节点（关键：取消也会同步）
      this.syncTreeCheckedState();
      this.updateSelectAllStatus();
      this.updateSelectedCount();
      this.$forceUpdate();
    },

    /** 打开全屏预览 */
    openFullScreenImage(item) {
      if (!item || !item.filePath) {
        this.$message.warning("图片地址不存在，无法预览");
        return;
      }
      this.fullScreenImageUrl = item.filePath;
      this.fullScreenImageName = item.fileName || item.label || '样本图片';
      this.fullScreenImageVisible = true;
      document.body.style.overflow = 'hidden';
      document.body.style.paddingRight = '17px';
    },

    /** 关闭全屏预览 */
    closeFullScreenImage() {
      this.fullScreenImageVisible = false;
      this.fullScreenImageUrl = "";
      this.fullScreenImageName = "";
      document.body.style.overflow = 'auto';
      document.body.style.paddingRight = '0';
    },

    /** 页码大小变化 */
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.updateImageListByPage();
      this.updateSelectAllStatus();
    },

    /** 页码变化 */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.updateImageListByPage();
      this.updateSelectAllStatus();
    },

    /** 取消 */
    handleCancel() {
      this.dialogVisible = false;
      this.$emit("close");
    },

    /** 确认 */
    handleConfirm() {
      const finalSelectedIds = [...new Set(this.checkedImageIds)]
        .filter(id => !isNaN(id) && id > 0);

      this.$emit("confirm", {
        selectedIds: finalSelectedIds.join(","),
        selectedCount: finalSelectedIds.length,
        selectedList: this.allImageList.filter(item =>
          finalSelectedIds.includes(Number(item.id))
        )
      });
      this.dialogVisible = false;
      this.$emit("close");
    },

    /** 弹窗关闭 */
    handleClose() {
      this.dialogVisible = false;
      this.$emit("close");
    }
  }
};
</script>

<style lang="scss" scoped>
/* 根容器 */
.data-select-root {
  width: 100%;
  height: 100%;
  overflow: hidden; /* 兜底：禁用根容器滚动 */
}

// 关键：穿透控制el-dialog的所有默认滚动，全局唯一不会污染其他dialog
::v-deep .data-select-dialog {
  .el-dialog__body {
    padding: 15px 20px !important; /* 微调内边距，减少高度浪费 */
    height: 700px !important; /* 固定dialog内容区高度，包含标题/内容/按钮 */
    overflow: hidden !important; /* 彻底禁用dialog默认的内容区滚动，核心修复 */
    display: flex;
    flex-direction: column;
  }
}

/* 主容器 - 核心：移除外层滚动，弹性占满dialog内容区 */
.data-select-container {
  display: flex;
  gap: 20px;
  box-sizing: border-box;
  padding-bottom: 0; /* 修复1：删掉主容器底部内边距，避免间距放大双横线 */
  overflow: hidden; /* 禁用自身滚动 */
  flex: 1; /* 弹性占满dialog body的剩余高度，抵消footer和内边距 */
  height: 100%; /* 兜底高度 */
}

// 左侧树面板 - 独立滚动，高度100%
.sample-tree-panel {
  width: 250px;
  border-right: 1px solid #ebeef5;
  padding-right: 10px;
  box-sizing: border-box;
  height: 100%; /* 占满主容器高度 */
  display: flex;
  flex-direction: column; /* 弹性列布局，标题固定+树滚动 */
  overflow: hidden; /* 禁用面板自身滚动 */

  .panel-title {
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin: 0 0 10px 0;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0; /* 标题不收缩，固定高度 */
  }

  .tree-empty-tip {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
    flex: 1; /* 占满剩余高度，居中显示 */
    display: flex;
    align-items: center;
    justify-content: center;
  }

  ::v-deep .el-tree {
    flex: 1; /* 弹性占满剩余高度 */
    height: 100%;
    overflow-y: auto; /* 仅树组件自身滚动，唯一滚动点 */
    overflow-x: hidden; /* 禁用横向滚动 */
    .tree-tooltip {
      display: inline-block;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    // 禁用节点样式
    .el-tree-node.is-disabled {
      color: #ccc !important;
      .el-checkbox {
        pointer-events: none;
        .el-checkbox__inner {
          background-color: #f5f7fa !important;
          border-color: #e4e7ed !important;
          color: #c0c4cc !important;
          cursor: not-allowed !important;
        }
        .el-checkbox__label {
          color: #ccc !important;
          cursor: not-allowed !important;
        }
      }
    }
    .el-tree-node.is-disabled .el-checkbox {
      display: inline-block !important;
      cursor: not-allowed !important;
    }
  }
}

// 右侧图片面板 - 独立滚动，高度100%
.sample-image-panel {
  flex: 1; /* 占满剩余宽度 */
  height: 100%; /* 占满主容器高度 */
  box-sizing: border-box;
  padding-bottom: 0; /* 修复2：删掉面板底部内边距，避免冗余间距 */
  display: flex;
  flex-direction: column; /* 弹性列布局：头部+图片滚动+分页固定 */
  overflow: hidden; /* 禁用面板自身滚动，核心 */

  .select-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 15px;
    padding-bottom: 8px;
    border-bottom: 1px solid #ebeef5;
    flex-shrink: 0; /* 头部固定，不收缩 */
  }

  .select-count {
    font-size: 12px;
    color: #666;
  }

  .image-empty-tip {
    text-align: center;
    padding: 50px;
    color: #999;
    font-size: 14px;
    flex: 1; /* 占满剩余高度，居中 */
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .image-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    min-height: 100px;
    flex: 1; /* 弹性占满头部和分页之间的所有高度 */
    overflow-y: auto; /* 仅图片网格自身滚动，唯一滚动点 */
    overflow-x: hidden; /* 禁用横向滚动 */
    padding-right: 6px; /* 为滚动条预留空间，避免内容遮挡 */
    box-sizing: border-box;
  }

  .image-item {
    width: calc(33.33% - 10px);
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 8px;
    transition: all 0.2s;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    height: 280px;

    &:hover {
      border-color: #1f72ea;
      box-shadow: 0 2px 8px rgba(31, 114, 234, 0.1);
    }

    .image-wrapper {
      flex: 1;
      margin-bottom: 8px;
      overflow: hidden;
      border-radius: 4px;

      .sample-image {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .image-footer {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      color: #666;
      height: 30px;

      .image-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 60%;
      }

      .image-actions {
        display: flex;
        align-items: center;
        gap: 8px;

        .preview-btn {
          padding: 0;
          margin: 0;
          color: #1f72ea;

          &:hover {
            color: #0e5bc8;
          }
        }
      }
    }
  }

  // 分页组件固定在面板底部，不滚动
  ::v-deep .el-pagination {
    flex-shrink: 0; /* 分页固定，不收缩 */
    margin-top: 15px !important;
    text-align: right;
    // 移除分页自身的任何边框，避免冗余
    border: none !important;
  }
}

// 弹窗底部按钮区 - 核心：只保留这一条顶部边框
.dialog-footer {
  text-align: right;
  padding-top: 10px;
  flex-shrink: 0; /* 按钮区固定，不收缩 */
  border-top: 1px solid #ebeef5; /* 唯一保留的分隔线 */
  margin-top: 10px; /* 微调间距，让分隔线和分页的距离更美观 */
  border-bottom: none !important; /* 兜底：确保无底部边框 */
}

/* 全屏预览样式 */
.full-screen-image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.9);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden; /* 禁用预览弹窗滚动 */
}

.full-screen-image-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.full-screen-close-btn {
  position: absolute;
  top: -40px;
  right: 0;
  color: #fff;
  font-size: 20px;
  width: 40px;
  height: 40px;
  opacity: 0.8;

  &:hover {
    opacity: 1;
  }
}

.full-screen-img {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
  border-radius: 4px;
}

.full-screen-img-name {
  text-align: center;
  color: #fff;
  margin-top: 15px;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 100%;
}
</style>
