<template>
  <el-card shadow="hover">
    <el-table v-loading="loading" :data="tempParmsList" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id">
      <el-table-column v-if="tableShow" align="center" label="行类型" prop="rowType"></el-table-column>
      <el-table-column align="center" label="附件名称" prop="originalName"></el-table-column>
      <el-table-column align="center" label="Sheet名称" prop="fileSheetName" />
      <el-table-column align="center" label="参数变量" prop="parameterName">
        <template #default="scope">
          <el-input v-if="scope.row.rowType === 'children'" v-model="scope.row.name" placeholder="参数" style="margin-left: 80px; width: 130px" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="参数名称" prop="parameterDesc"></el-table-column>
      <el-table-column align="center" label="参数类型" prop="parameterType"></el-table-column>
      <el-table-column align="center" label="变量值" prop="previewValue">
        <template #default="scope">
          <el-input v-if="scope.row.parameterType === 'text'" v-model="scope.row.previewValue" placeholder="变量值" @blur="handleBlur(scope.row)" />
          <el-button
            v-if="scope.row.parameterType === 'table' && scope.row.previewId === null"
            icon="Plus"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:addsub']"
            @click="handleAddSub(scope.row)"
          >新增子项
          </el-button>
          <el-button
            v-if="scope.row.parameterType === 'table' && scope.row.previewId !== null"
            icon="Search"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:selectsub']"
            @click="handleSelectSub(scope.row)"
          >查看子项
          </el-button>

          <el-button
            v-if="scope.row.parameterType === 'list' && scope.row.previewId === null"
            icon="Plus"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:addlistsub']"
            @click="handleAddListSub(scope.row)"
          >维护子项
          </el-button>
          <el-button
            v-if="scope.row.parameterType === 'list' && scope.row.previewId !== null"
            icon="Search"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:selectlistsub']"
            @click="handleSelectListSub(scope.row)"
          >查看子项
          </el-button>

          <el-button
            v-if="scope.row.parameterType === 'image' && scope.row.previewId === null"
            icon="Plus"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:addimagesub']"
            @click="handleAddImageSub(scope.row)"
          >维护子项
          </el-button>
          <el-button
            v-if="scope.row.parameterType === 'image' && scope.row.previewId !== null"
            icon="Search"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:selectimagesub']"
            @click="handleSelectImageSub(scope.row)"
          >查看子项
          </el-button>
          <el-button
            v-if="scope.row.parameterType === 'block'"
            icon="Edit"
            size="mini"
            type="text"
            v-hasPermi="['print:temp:editblock']"
            @click="handleEditBlock(scope.row)"
          >编辑区块
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

<!--  <el-dialog v-model="dialogBlockSub.visible" :title="dialogBlockSub.title" append-to-body width="800px">-->
<!--    <el-card shadow="hover">-->
<!--      &lt;!&ndash; 区块树形结构展示 &ndash;&gt;-->
<!--      <div class="block-tree" v-loading="blockLoading">-->
<!--        &lt;!&ndash; 顶级区块 &ndash;&gt;-->
<!--        <div-->
<!--          v-for="parentNode in blockTree"-->
<!--          :key="parentNode.elementId"-->
<!--          class="top-level-node"-->
<!--        >-->
<!--          <div class="node-header">-->
<!--            <span class="node-name">{{ parentNode.elementName }}</span>-->
<!--            <el-tag size="small">{{ parentNode.elementType }}</el-tag>-->
<!--          </div>-->

<!--          &lt;!&ndash; 根区块值 &ndash;&gt;-->
<!--          <div class="block-value-input">-->
<!--            <span class="value-label">区块值:</span>-->
<!--            <el-input-->
<!--              v-model="blockValues[parentNode.elementId]"-->
<!--              placeholder="请输入区块值"-->
<!--              size="small"-->
<!--            />-->
<!--          </div>-->

<!--          &lt;!&ndash; 直接子节点 &ndash;&gt;-->
<!--          <div-->
<!--            v-for="childNode in parentNode.children"-->
<!--            :key="childNode.elementId"-->
<!--            class="child-node"-->
<!--          >-->
<!--            <div class="node-header">-->
<!--              <span class="node-name">{{ childNode.elementName }}</span>-->
<!--              <el-tag size="small">{{ childNode.elementType }}</el-tag>-->
<!--            </div>-->

<!--            &lt;!&ndash; 文本节点编辑 &ndash;&gt;-->
<!--            <div-->
<!--              v-if="childNode.elementType === 'text'"-->
<!--              class="text-editor"-->
<!--            >-->
<!--              <div-->
<!--                v-for="(val, index) in blockValues[childNode.elementId]"-->
<!--                :key="index"-->
<!--                class="value-group"-->
<!--              >-->
<!--                <span class="value-label">值 {{ index + 1 }}:</span>-->
<!--                <el-input-->
<!--                  v-model="blockValues[childNode.elementId][index]"-->
<!--                  placeholder="请输入值"-->
<!--                  size="small"-->
<!--                  class="value-input"-->
<!--                />-->
<!--                <el-button-->
<!--                  v-if="index > 0"-->
<!--                  type="danger"-->
<!--                  icon="Delete"-->
<!--                  size="small"-->
<!--                  @click="removeValueGroup(childNode.elementId, index)"-->
<!--                ></el-button>-->
<!--              </div>-->

<!--              &lt;!&ndash; 文本节点添加按钮 &ndash;&gt;-->
<!--              <el-button-->
<!--                type="primary"-->
<!--                size="small"-->
<!--                icon="Plus"-->
<!--                @click="addValueGroup(childNode.elementId)"-->
<!--              >添加值</el-button>-->
<!--            </div>-->

<!--            &lt;!&ndash; 区块节点 &ndash;&gt;-->
<!--            <div-->
<!--              v-else-if="childNode.elementType === 'block'"-->
<!--              class="block-container"-->
<!--            >-->
<!--              &lt;!&ndash; 区块值的单独输入框（只允许一个值） &ndash;&gt;-->
<!--              <div class="block-value-input">-->
<!--                <span class="value-label">区块值:</span>-->
<!--                <el-input-->
<!--                  v-model="blockValues[childNode.elementId]"-->
<!--                  placeholder="请输入区块值"-->
<!--                  size="small"-->
<!--                />-->
<!--              </div>-->

<!--              &lt;!&ndash; 区块内的子节点 &ndash;&gt;-->
<!--              <div-->
<!--                v-for="grandChild in childNode.children"-->
<!--                :key="grandChild.elementId"-->
<!--                class="grandchild-node"-->
<!--              >-->
<!--                <div class="node-header">-->
<!--                  <span class="node-name">{{ grandChild.elementName }}</span>-->
<!--                  <el-tag size="small">{{ grandChild.elementType }}</el-tag>-->
<!--                </div>-->

<!--                &lt;!&ndash; 三级文本节点编辑 &ndash;&gt;-->
<!--                <div-->
<!--                  v-if="grandChild.elementType === 'text'"-->
<!--                  class="text-editor"-->
<!--                >-->
<!--                  <div-->
<!--                    v-for="(val, index) in blockValues[grandChild.elementId]"-->
<!--                    :key="index"-->
<!--                    class="value-group"-->
<!--                  >-->
<!--                    <span class="value-label">值 {{ index + 1 }}:</span>-->
<!--                    <el-input-->
<!--                      v-model="blockValues[grandChild.elementId][index]"-->
<!--                      placeholder="请输入值"-->
<!--                      size="small"-->
<!--                      class="value-input"-->
<!--                    />-->
<!--                    <el-button-->
<!--                      v-if="index > 0"-->
<!--                      type="danger"-->
<!--                      icon="Delete"-->
<!--                      size="small"-->
<!--                      @click="removeValueGroup(grandChild.elementId, index)"-->
<!--                    ></el-button>-->
<!--                  </div>-->

<!--                  &lt;!&ndash; 三级文本节点添加按钮 &ndash;&gt;-->
<!--                  <el-button-->
<!--                    type="primary"-->
<!--                    size="small"-->
<!--                    icon="Plus"-->
<!--                    @click="addValueGroup(grandChild.elementId)"-->
<!--                  >添加值</el-button>-->
<!--                </div>-->

<!--                &lt;!&ndash; 三级区块节点编辑 &ndash;&gt;-->
<!--                <div-->
<!--                  v-else-if="grandChild.elementType === 'block'"-->
<!--                  class="block-container"-->
<!--                >-->
<!--                  <div class="block-value-input">-->
<!--                    <span class="value-label">区块值:</span>-->
<!--                    <el-input-->
<!--                      v-model="blockValues[grandChild.elementId]"-->
<!--                      placeholder="请输入区块值"-->
<!--                      size="small"-->
<!--                    />-->
<!--                  </div>-->
<!--                </div>-->
<!--              </div>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
<!--      </div>-->

<!--      &lt;!&ndash; 操作按钮 &ndash;&gt;-->
<!--      <div class="block-actions">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          @click="saveBlockValues"-->
<!--        >保存区块值</el-button>-->
<!--        <el-button @click="dialogBlockSub.visible = false">取消</el-button>-->
<!--      </div>-->
<!--    </el-card>-->
<!--  </el-dialog>-->
  <el-dialog v-model="dialogBlockSub.visible" :title="dialogBlockSub.title" append-to-body width="800px">
    <el-card shadow="hover">
      <!-- 全局添加值按钮 -->
      <div class="global-actions">
        <el-button
          type="primary"
          size="small"
          icon="Plus"
          @click="addValueGroupToAllTextNodes"
        >添加值组</el-button>
      </div>

      <!-- 区块树形结构展示 -->
      <div class="block-tree" v-loading="blockLoading">
        <!-- 顶级区块 -->
        <div
          v-for="parentNode in blockTree"
          :key="parentNode.elementId"
          class="top-level-node"
        >
          <div class="node-header">
            <span class="node-name">{{ parentNode.elementName }}</span>
            <el-tag size="small">{{ parentNode.elementType }}</el-tag>
          </div>

          <!-- 直接子节点 -->
          <div
            v-for="childNode in parentNode.children"
            :key="childNode.elementId"
            class="child-node"
          >
            <div class="node-header">
              <span class="node-name">{{ childNode.elementName }}</span>
              <el-tag size="small">{{ childNode.elementType }}</el-tag>
            </div>

            <!-- 文本节点编辑 -->
            <div
              v-if="childNode.elementType === 'text'"
              class="text-editor"
            >
              <div
                v-for="(val, index) in blockValues[childNode.elementId]"
                :key="index"
                class="value-group"
              >
                <span class="value-label">值 {{ index + 1 }}:</span>
                <el-input
                  v-model="blockValues[childNode.elementId][index]"
                  placeholder="请输入值"
                  size="small"
                  class="value-input"
                />
                <el-button
                  v-if="index > 0"
                  type="danger"
                  icon="Delete"
                  size="small"
                  @click="removeValueGroup(childNode.elementId, index)"
                ></el-button>
              </div>
            </div>

            <!-- 区块节点 - 仅显示标签不再有输入框 -->
            <div
              v-else-if="childNode.elementType === 'block'"
              class="block-container"
            >
              <!-- 区块内的子节点 -->
              <div
                v-for="grandChild in childNode.children"
                :key="grandChild.elementId"
                class="grandchild-node"
              >
                <div class="node-header">
                  <span class="node-name">{{ grandChild.elementName }}</span>
                  <el-tag size="small">{{ grandChild.elementType }}</el-tag>
                </div>

                <!-- 三级文本节点编辑 -->
                <div
                  v-if="grandChild.elementType === 'text'"
                  class="text-editor"
                >
                  <div
                    v-for="(val, index) in blockValues[grandChild.elementId]"
                    :key="index"
                    class="value-group"
                  >
                    <span class="value-label">值 {{ index + 1 }}:</span>
                    <el-input
                      v-model="blockValues[grandChild.elementId][index]"
                      placeholder="请输入值"
                      size="small"
                      class="value-input"
                    />
                    <el-button
                      v-if="index > 0"
                      type="danger"
                      icon="Delete"
                      size="small"
                      @click="removeValueGroup(grandChild.elementId, index)"
                    ></el-button>
                  </div>
                </div>

                <!-- 三级区块节点 - 仅显示标签不再有输入框 -->
                <div
                  v-else-if="grandChild.elementType === 'block'"
                  class="block-container"
                >
                  <!-- 无输入框 -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="block-actions">
        <el-button
          type="primary"
          @click="saveBlockValues"
        >保存区块值</el-button>
        <el-button @click="dialogBlockSub.visible = false">取消</el-button>
      </div>
    </el-card>
  </el-dialog>
  <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="800px">
    <div>
      <el-card shadow="hover">
        <div style="display: flex; align-items: center">
          <el-table :data="tableData" border style="flex: 1">
            <el-table-column v-for="(col, index) in columns" :key="index" :label="col.label" :prop="col.prop">
              <template #default="scope">
                <el-input v-model="scope.row[col.prop]" placeholder="请输入内容" />
              </template>
            </el-table-column>
          </el-table>
          <el-button style="margin-left: 10px" type="primary" @click="addColumn">列值增加</el-button>
        </div>
        <div style="margin-top: 10px">
          <el-button type="primary" @click="addRow">行增加</el-button>
        </div>
      </el-card>
      <el-card shadow="hover">
        <el-button v-hasPermi="['print:temp:addsub']" type="primary" @click="handleAddSubValues">保存</el-button>
      </el-card>
    </div>
  </el-dialog>

  <el-dialog v-model="dialogListSub.visible" :title="dialogListSub.title" append-to-body width="800px">
    <div>
      <el-card shadow="hover">
        <div style="display: flex; align-items: center">
          <el-table :data="ListSubData" border style="flex: 1">
            <el-table-column v-for="(col, index) in columns" :key="index" :label="col.label" :prop="col.prop">
              <template #default="scope">
                <el-input v-model="scope.row[col.prop]" placeholder="请输入内容" />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 10px">
          <el-button type="primary" @click="addListSubRow">行增加</el-button>
        </div>
      </el-card>
      <el-card shadow="hover">
        <el-button v-hasPermi="['print:temp:addlistsub']" type="primary" @click="handleAddListSubValues">保存</el-button>
      </el-card>
    </div>
  </el-dialog>

  <el-dialog v-model="dialogImageSub.visible" :title="dialogImageSub.title" append-to-body width="850px">
    <div>
      <el-card shadow="hover">
        <el-form
          ref="imageRef"
          v-loading="imageLoading"
          :model="imageParams"
          :rules="imageRules"
          :inline="true"
          label-width="80px"
          label-position="left"
        >
          <el-row>
            <el-form-item  label="模版id" prop="templateId">
              <el-input v-model="imageParams.templateId" />
            </el-form-item>
            <el-form-item  label="变量名称" prop="parameterName">
              <el-input v-model="imageParams.parameterName" />
            </el-form-item>
            <el-form-item  label="预览ID" prop="previewId">
              <el-input v-model="imageParams.previewId" />
            </el-form-item>
            <el-form-item  label="附件id" prop="attachmentId">
              <el-input v-model="imageParams.attachmentId" />
            </el-form-item>
            <el-form-item label="图片类型" prop="imageType">
              <el-select v-model="imageParams.imageType" placeholder="请选择图片类型">
                <el-option v-for="dict in print_image_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="图片长度" prop="width">
              <el-input v-model="imageParams.width" placeholder="请输入图片长度" clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="图片高度" prop="high">
              <el-input v-model="imageParams.high" placeholder="请输入图片高度" clearable />
            </el-form-item>
            <el-form-item label="测试数据" prop="imageCode">
              <el-input v-model="imageParams.imageCode" placeholder="请输入测试数据" clearable />
            </el-form-item>
          </el-row>
        </el-form>
      </el-card>
      <el-card shadow="hover">
        <el-button type="primary" v-hasPermi="['print:temp:addimagesub']" @click="handleAddImageSubValues">保存</el-button>
      </el-card>
    </div>
  </el-dialog>
</template>

<script lang="ts" name="TemplateView" setup>
import {
  addImageSub,
  quryPrintViews,
  quryTemplateExcelSubTables, quryTemplateImageSub,
  quryTemplateListSub,
  quryTemplateViewsListValues,
  quryTemplateViewsTableValues,
  saveTemplateViewsListValues,
  saveTemplateViewsTableValues,
  saveTemplateViewsValue,
  templetCompleted,
  templetPreview,
  quryTemplateBlockContent,
  quryBlockPreviewValues,
  saveTemplateViewsBlockValues
} from '@/api/print/template';
import { RouteLocationNormalized } from 'vue-router';
import { addDept, updateDept } from '@/api/system/dept';
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { serializeBlockValues, deserializeBlockValues } from '@/utils/blockSerializer';

const router = useRouter();
const { proxy } = getCurrentInstance();
const { print_image_type } = toRefs<any>(proxy?.useDict('print_image_type'));

// === 区块编辑相关逻辑开始 ===
interface BlockNode {
  elementId: string | number;
  elementName: string;
  elementType: string; // 关键字段：类型标识
  children?: BlockNode[];
}

const dialogBlockSub = reactive({
  visible: false,
  title: ''
});
const blockTree = ref<BlockNode[]>([]);
// 修改点：支持字符串（区块）和数组（文本）
const blockValues = ref<Record<string | number, any>>({});
const renderCount = ref(1);
const blockLoading = ref(false);
const currentBlock = ref<any>(null);
const currentBlockRow = ref<any>(null);


// 为所有文本节点添加一组值
const addValueGroupToAllTextNodes = () => {
  // 遍历blockTree的所有节点，找到文本节点并添加值
  blockTree.value.forEach(parentNode => {
    traverseNodesAndAddValue(parentNode);
  });

  // 更新渲染计数
  renderCount.value += 1;
};

// 递归遍历节点，为文本节点添加值
const traverseNodesAndAddValue = (node: BlockNode) => {
  if (node.elementType === 'text') {
    if (!blockValues.value[node.elementId]) {
      blockValues.value[node.elementId] = [''];
    } else {
      blockValues.value[node.elementId].push('');
    }
  }

  // 递归处理子节点
  if (node.children) {
    node.children.forEach(child => traverseNodesAndAddValue(child));
  }
};


// 统一的区块编辑方法
const handleEditBlock = async (row: any) => {
  try {
    resetBlockData();
    blockLoading.value = true;

    const structureRes = await quryTemplateBlockContent({
      templateId: row.templateId,
      parameterName: row.parameterName
    });
    blockTree.value = buildTreeStructure(structureRes.data.nodes);
    if (row.previewId != null) {
      const valuesRes = await quryBlockPreviewValues({
        previewId: row.previewId
      });
      blockValues.value = deserializeBlockValues(valuesRes.data.data);

      // === 新增：根据类型处理值 ===
      processValuesByType();
    } else {
      initBlockValues(blockTree.value);
      renderCount.value = 1;
    }
    currentBlockRow.value = { ...row };
    blockLoading.value = false;
    dialogBlockSub.visible = true;
    dialogBlockSub.title = `区块参数 - ${row.parameterName}`;

    currentBlock.value = {
      ...row
    };
  } catch (error) {
    blockLoading.value = false;
    proxy.$modal.msgError('加载区块数据失败: ' + error.message);
  }
};
// === 新增函数：根据类型处理值 ===
const processValuesByType = () => {
  blockTree.value.forEach(traverseNodes);

  function traverseNodes(node: BlockNode) {
    // 处理block类型字段
    if (node.elementType === 'block' &&
      Array.isArray(blockValues.value[node.elementId])
    ) {
      // 将数组转换为字符串
      blockValues.value[node.elementId] = blockValues.value[node.elementId].join('');
    }

    // 处理text类型字段
    if (node.elementType === 'text' &&
      typeof blockValues.value[node.elementId] === 'string'
    ) {
      // 将字符串转换为数组
      blockValues.value[node.elementId] = [blockValues.value[node.elementId]];
    }

    // 递归处理子节点
    if (node.children) {
      node.children.forEach(traverseNodes);
    }
  }
};
// === 新增函数：处理单值字段 ===
const processSingleValueFields = () => {
  const singleValueFields = ['Company', 'Department']; // 单值字段列表

  blockTree.value.forEach(traverseNodes);

  function traverseNodes(node: BlockNode) {
    // 处理单值文本字段
    if (node.elementType === 'text' &&
      singleValueFields.includes(node.elementName) &&
      Array.isArray(blockValues.value[node.elementId])
    ) {
      // 将数组转换为字符串
      blockValues.value[node.elementId] = blockValues.value[node.elementId].join('');
    }

    // 递归处理子节点
    if (node.children) {
      node.children.forEach(traverseNodes);
    }
  }
};
// 构建树形结构
const buildTreeStructure = (flatData: any[]): BlockNode[] => {
  // 第一步：创建所有节点的映射
  const nodeMap: Record<string | number, BlockNode> = {};
  flatData.forEach((item) => {
    // 使用elementId作为主键
    nodeMap[item.elementId] = {
      elementId: item.elementId,
      elementName: item.elementName,
      elementType: item.elementType,
      children: []
    };
  });

  // 第二步：识别所有根节点 (level=1)
  const roots: BlockNode[] = flatData
    .filter(item => item.level === 1)
    .map(rootItem => nodeMap[rootItem.elementId]);

  // 第三步：建立父子关系 - 使用双重匹配
  flatData.forEach((item) => {
    // 尝试通过parentBlockId匹配
    if (item.parentBlockId && nodeMap[item.parentBlockId]) {
      nodeMap[item.parentBlockId].children?.push(nodeMap[item.elementId]);
    }
    // 如果parentBlockId匹配失败，尝试通过blockName匹配
    else if (item.blockName) {
      const parentNode = Object.values(nodeMap).find(
        node => node.elementName === item.blockName && node.elementType === "block"
      );
      if (parentNode) {
        parentNode.children?.push(nodeMap[item.elementId]);
      }
    }
  });
  // 第三步：建立父子关系后，添加字段类型标识
  flatData.forEach(item => {
    const node = nodeMap[item.elementId];
    // 保留原始类型信息
    node.elementType = item.elementType;
  });

  return roots;
};

// 初始化区块值 - 确保根区块也有值
const initBlockValues = (treeNodes: BlockNode[]) => {
  for (const node of treeNodes) {
    // 根据类型初始化值
    if (node.elementType === 'block') {
      // block类型：单值
      blockValues.value[node.elementId] = '';
    } else if (node.elementType === 'text') {
      // text类型：多值（数组）
      blockValues.value[node.elementId] = Array(renderCount.value).fill('');
    }

    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      initBlockValues(node.children);
    }
  }
};

// 更新渲染次数
const updateRenderCount = (newCount: number) => {
  renderCount.value = newCount;

  // 修改点：更新所有文本值的数组长度
  Object.keys(blockValues.value).forEach(id => {
    // 只处理文本类型
    if (Array.isArray(blockValues.value[id])) {
      const currentCount = blockValues.value[id].length;
      if (newCount > currentCount) {
        for (let i = currentCount; i < newCount; i++) {
          blockValues.value[id].push('');
        }
      } else if (newCount < currentCount) {
        blockValues.value[id] = blockValues.value[id].slice(0, newCount);
      }
    }
  });
};

// 添加整个组的值
const addRenderGroup = () => {
  Object.keys(blockValues.value).forEach(id => {
    if (Array.isArray(blockValues.value[id])) {
      blockValues.value[id].push('');
    }
  });
  renderCount.value += 1;
};

// 为单个文本元素添加值 - 新增函数
const addValueGroup = (elementId: string | number) => {
  if (!blockValues.value[elementId]) {
    blockValues.value[elementId] = [''];
  } else {
    blockValues.value[elementId].push('');
  }
};

// 移除单个文本元素的值 - 新增函数
const removeValueGroup = (elementId: string | number, index: number) => {
  if (blockValues.value[elementId]?.length > 1) {
    blockValues.value[elementId].splice(index, 1);
  }
};

// saveBlockValues ===
const saveBlockValues = async () => {
  if (!currentBlock.value || !currentBlockRow.value) return;

  try {
    const serializedValues = serializeBlockValues(blockValues.value) || ''; // 确保非null值
    const saveData = {
      ...currentBlockRow.value,
      previewId: currentBlock.value.previewId,
      templateId: currentBlockRow.value.templateId,
      attachmentId: currentBlockRow.value.attachmentId,
      parameterName: currentBlock.value.parameterName,
      parameterType: 'block',
      previewValue: serializedValues, // 序列化值

      // 添加调试日志（开发环境）
      ...(process.env.NODE_ENV === 'development' && {
        _debug: JSON.stringify(blockValues.value)
      })
    };

    // 3. 移除可能为空的字段（优化请求体）
    const finalSaveData = removeEmptyProperties(saveData); // 新增空值过滤

    // 4. 发送请求
    await saveTemplateViewsValue(finalSaveData); // 使用过滤后的数据

    proxy.$modal.msgSuccess('区块参数保存成功');
    dialogBlockSub.visible = false;
    loadingPage(templateId.value);
  } catch (error) {
    proxy.$modal.msgError('保存失败: ' + error.message);
  }
};
// === 新增工具函数：过滤空值属性 ===
const removeEmptyProperties = (obj: any) => {
  return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v !== null && v !== undefined && v !== ''));
};
// 重置区块数据
const resetBlockData = () => {
  blockTree.value = [];
  blockValues.value = {};
  renderCount.value = 1;
  currentBlock.value = null;
};
// === 区块编辑相关逻辑结束 ===

// 其他业务逻辑保持不变
const loading = ref(false);
const tableShow = ref(false);
const tempParmsList = ref([]);
const templateId = ref(null);
const tableData = ref<any[]>([]);
const columns = ref([
  { prop: 'head', label: '抬头名' },
  { prop: 'value1', label: '列值1' }
]);
const dialog = reactive({
  visible: false,
  title: ''
});

const ListSubData = ref<any[]>([]);
const dialogListSub = reactive({
  visible: false,
  title: ''
});

const dialogImageSub = reactive({
  visible: false,
  title: ''
});

const validateNumber = (rule: any, value: any, callback: Function) => {
  if (value === '') {
    callback(new Error(rule.message));
  } else if (!/^\d+$/.test(value)) {
    callback(new Error('请输入有效的数字'));
  } else {
    callback();
  }
};
const initImageParams = {
  imageType: undefined,
  high: undefined,
  width: undefined,
  imageCode: undefined,
  templateId: undefined,
  parameterName: undefined,
  previewId: undefined,
  attachmentId: undefined
};
const imageData = reactive({
  imageParams: { ...initImageParams },
  imageRules: {
    imageType: [{ required: true, message: '图片类型类型不能为空', trigger: 'blur' }],
    high: [
      { required: true, message: '图片高度不能为空', trigger: 'blur' },
      { validator: validateNumber, message: '请输入有效的数字', trigger: 'blur' }
    ],
    width: [
      { required: true, message: '图片长度不能为空', trigger: 'blur' },
      { validator: validateNumber, message: '请输入有效的数字', trigger: 'blur' }
    ],
    imageCode: [{ required: true, message: '图片测试数据不能为空', trigger: 'blur' }]
  }
});
const { imageParams, imageRules } = toRefs(imageData);
const imageLoading = ref(false);
const imageRef = ref<any>(null);

const selectRowParameterValue = ref(null);
const selectRowPreviewId = ref(null);
const selectRowAttachmentId = ref(null);
const resetTableData = () => {
  tableData.value = [];
  columns.value = [
    { prop: 'head', label: '抬头名' },
    { prop: 'value1', label: '列值1' }
  ];
  selectRowParameterValue.value = null;
  selectRowPreviewId.value = null;
  selectRowAttachmentId.value = null;
};

const handleAddSub = async (row: any) => {
  resetTableData();
  selectRowParameterValue.value = row.parameterName;
  selectRowPreviewId.value = row.previewId;
  selectRowAttachmentId.value = row.attachmentId;
  if (row.fileSuffix === '.xlsx') {
    const res = await quryTemplateExcelSubTables(row);
    tableData.value = JSON.parse(res.data.tableValues);
  }
  dialog.visible = true;
  dialog.title = '表格参数';
};
const handleSelectSub = async (row: any) => {
  resetTableData();
  selectRowParameterValue.value = row.parameterName;
  selectRowPreviewId.value = row.previewId;
  selectRowAttachmentId.value = row.attachmentId;
  const res = await quryTemplateViewsTableValues(selectRowPreviewId.value);
  const tableValues = JSON.parse(res.data.tableValues);
  const tableRow = tableValues[0] || {};
  if (Object.keys(tableRow).length > 2) {
    for (let i = 0; i < Object.keys(tableRow).length - 2; i++) {
      addColumn();
    }
  }
  tableData.value = JSON.parse(res.data.tableValues);
  dialog.visible = true;
  dialog.title = '表格参数';
};

const addColumn = () => {
  const newColName = `列值${columns.value.length}`;
  const newProp = `value${columns.value.length}`;
  columns.value.push({ prop: newProp, label: newColName });
};

const addRow = () => {
  const newRow = {};
  tableData.value.push(newRow);
};

const loadingPage = async (id: any) => {
  const res = await quryPrintViews(id);
  tempParmsList.value = res.data;
  loading.value = false;
};

const handleBlur = async (row: any) => {
  loading.value = true;
  await saveTemplateViewsValue(row);
  proxy?.$modal.msgSuccess('参数保存成功');
  loadingPage(templateId.value);
};
const handleAddSubValues = async () => {
  await saveTemplateViewsTableValues(
    templateId.value,
    selectRowPreviewId.value,
    selectRowParameterValue.value,
    selectRowAttachmentId.value,
    tableData.value
  );
  proxy?.$modal.msgSuccess('参数保存成功');
  dialog.visible = false;
  loadingPage(templateId.value);
};

const handlePreview = async () => {
  const res = await templetPreview(templateId.value);
  if (res.code === 200) {
    proxy?.$download.oss(res.data.ossId);
  } else {
    proxy?.$modal.msgError(res.msg);
  }
};

const handleCompleted = async () => {
  const res = await templetCompleted(templateId.value);
  if (res.code == 200 && res.data === true) {
    proxy?.$modal.msgSuccess('模版定义已送审');
    Close();
  } else {
    proxy?.$modal.msgError(res.msg);
  }
};

const handleAddListSub = async (row: any) => {
  resetListSub();
  selectRowParameterValue.value = row.parameterName;
  selectRowPreviewId.value = row.previewId;
  selectRowAttachmentId.value = row.attachmentId;
  const res = await quryTemplateListSub(row);
  columns.value = res.data.columnsValues;
  ListSubData.value = res.data.tableValues;
  dialogListSub.visible = true;
  dialogListSub.title = '列表参数';
};

const resetListSub = () => {
  ListSubData.value = [];
  columns.value = [
    { prop: 'head', label: '抬头名' },
    { prop: 'value1', label: '列值1' }
  ];
  selectRowParameterValue.value = null;
  selectRowPreviewId.value = null;
  selectRowAttachmentId.value = null;
  dialogListSub.visible = false;
};

const addListSubRow = () => {
  const newRow = {};
  ListSubData.value.push(newRow);
};

const handleAddListSubValues = async () => {
  await saveTemplateViewsListValues(
    templateId.value,
    selectRowPreviewId.value,
    selectRowParameterValue.value,
    selectRowAttachmentId.value,
    ListSubData.value
  );
  proxy?.$modal.msgSuccess('参数保存成功');
  dialogListSub.visible = false;
  loadingPage(templateId.value);
};

const handleSelectListSub = async (row: any) => {
  resetListSub();
  selectRowParameterValue.value = row.parameterName;
  selectRowPreviewId.value = row.previewId;
  selectRowAttachmentId.value = row.attachmentId;
  const res = await quryTemplateViewsListValues(selectRowPreviewId.value);
  columns.value = res.data.columnsValues;
  ListSubData.value = JSON.parse(res.data.tableValues);
  dialogListSub.visible = true;
  dialogListSub.title = '列表参数';
};

const Close = () => {
  const obj: RouteLocationNormalized = {
    fullPath: '',
    hash: '',
    matched: [],
    meta: undefined,
    name: undefined,
    params: undefined,
    query: undefined,
    redirectedFrom: undefined,
    path: '/print/temp/printTempConstruct'
  } as any;
  proxy?.$tab.closeOpenPage(obj);
};

const resetImageSub = () => {
  Object.assign(imageParams.value, initImageParams);
  imageRef.value?.resetFields();
};

const handleAddImageSub = async (row: any) => {
  resetImageSub();
  imageParams.value.templateId = row.templateId;
  imageParams.value.parameterName = row.parameterName;
  imageParams.value.previewId = row.previewId;
  imageParams.value.attachmentId = row.attachmentId;
  dialogImageSub.visible = true;
  dialogImageSub.title = '图形参数';
};

const handleSelectImageSub = async (row: any) => {
  resetImageSub();
  imageParams.value.previewId = row.previewId;
  const res = await quryTemplateImageSub(row.previewId);
  Object.assign(imageParams.value, res.data.fromValues);

  dialogImageSub.visible = true;
  dialogImageSub.title = '图形参数';
};

const handleAddImageSubValues = () => {
  imageRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await addImageSub(imageParams.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialogImageSub.visible = false;
      await loadingPage(templateId.value);
    }
  });
};

onMounted(() => {
  loading.value = true;
  const route = useRoute();
  templateId.value = route.params.templateId as string | undefined;
  if (templateId.value) {
    loadingPage(templateId.value);
  }
});

defineExpose({
  loadingPage,
  handlePreview,
  handleCompleted
});
</script>

<style scoped>
.block-tree {
  max-height: 60vh;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.top-level-node {
  margin-bottom: 20px;
  border-left: 3px solid #409EFF;
  padding-left: 15px;
}

.child-node {
  margin-left: 30px;
  padding-left: 15px;
  margin-top: 15px;
  border-left: 2px solid #67C23A;
}

.grandchild-node {
  margin-left: 30px;
  margin-top: 10px;
  padding-left: 15px;
}

.node-header {
  display: flex;
  align-items: center;
  margin: 10px 0;
  padding: 8px 5px;
  background: #f5f7fa;
  border-radius: 4px;
}

.node-name {
  font-weight: bold;
  min-width: 120px;
  margin-right: 10px;
}



.text-editor {
  margin: 10px 0;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 4px;
}

.value-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.value-label {
  min-width: 60px;
  font-size: 14px;
  color: #606266;
}

.value-input {
  flex: 1;
  margin-right: 10px;
}

.block-value-input {
  display: flex;
  align-items: center;
  margin: 15px 0;
  padding: 10px;
  background: #ecf5ff;
  border-radius: 4px;
}

.block-actions {
  margin-top: 20px;
  text-align: right;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
/* 区块值输入框样式 - 统一风格 */
.block-value-input {
  display: flex;
  align-items: center;
  margin: 10px 20px;  /* 适当的缩进 */
  padding: 10px 15px;
  background: #f8f8f8;
  border-radius: 4px;
  border-left: 3px solid #e6f7ff;  /* 左侧边框色 */
}

.value-label {
  min-width: 80px;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
}
.global-actions {
  margin-bottom: 15px;
  text-align: right;
}
</style>
