<template>
  <div style="width: 99%;display: flex;margin-left: 1%;background-color:#F5F8F9;;">
    <el-card style="width: 18%;height: 100%;overflow: auto;height: 85vh;background-color: white;overflow-x: hidden;" shadow="never">
      <template #header>
      <div class="card-header" style="display: flex;align-items: center;justify-content: space-between;">
        <span>目录：</span>
        <div>
          <el-icon @click="addDir" style="cursor: pointer;color: #409EFF;"><Plus /></el-icon>
        </div>
      </div>
    </template>
      <el-tree :expand-on-click-node="false" ref="treeRef" :filter-node-method="filterNode" :current-node-key="currentNodeKey" class="treeLeft" 
      :data="data" @node-click="handleNodeClick" node-key="id" style="margin-left: -10%;margin-top: 0%;width: 120%;background-color: transparent;" default-expand-all :key="valueKet">
          <template #default="{ node, data }">
            <span  style="justify-content: space-between;display: flex;width: 30%;align-items: center;margin-left: 1%;">
              <div class="custom-tree-node" style="align-items: center;line-height: 1.5;">
                <svg-icon icon-class="model"  v-if="data.nodeType=='SET'"/>
                <svg-icon icon-class="model2"  v-if="data.nodeType=='TREE'"/>
                <span style="font-size: 1rem;">{{ node.label }}</span>
              </div>
              <div style="margin-right: 1%;position: absolute;left:90%;">
                <el-dropdown trigger="hover" @click.stop v-if="currentNodeKey === data.id">
                    <!-- <el-icon class="el-icon--right" style="color: black;">
                      <plus />
                    </el-icon> -->
                    <svg-icon icon-class="zhankai"/>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item style="display: flex;" @click="add1Level">
                        <el-icon class="el-icon--right" style="color: black;">
                          <CirclePlus />
                        </el-icon>
                        <div>
                          添加同级
                        </div>
                      </el-dropdown-item>
                      <el-dropdown-item style="display: flex;"  @click="addNextLevel">
                        <el-icon class="el-icon--right" style="color: black;">
                          <Connection />
                        </el-icon>
                        <div>
                          新建下级
                        </div>
                      </el-dropdown-item>
                      <divider/>
                      <el-dropdown-item style="display: flex;"  @click="delAll" divided>
                        <el-icon class="el-icon--right" style="color: black;">
                          <CircleClose />
                        </el-icon>
                        <div>
                          删除节点
                        </div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </span>
          </template>
        </el-tree>
    </el-card>
    <div style="width: 80%;margin-left: 1%;background-color: white;">
        <div style="display: flex;justify-content: space-between;width: 100%;align-items: center;margin-left: 0%;padding: 1%;">
            <div style="display: flex;width: 50%;align-items: center;">
                <div>
                    名称
                </div>
                <el-input size="mini" v-model="dcName" style="width: 30%;margin-left: 1%;"/>
                <el-button type="primary" @click="getTable" size="mini" style="margin-left:1%;">查询</el-button>
            </div>
            <el-button type="primary" @click="showAdd" size="mini" style="margin-left:1%;" :disabled="!parTree">新增</el-button>
        </div>
      <el-table 
        :data="tableData" 
        style="width: 99%;margin-left: 1%;margin-top: 0.5%;"
        :cell-style="{ padding:'5px' }"
        :header-cell-style="{height: heightAll*0.01+'px',}"
        :row-style="{ fontSize: '16px',textAlign:'center'}"
        border 
        :height="tableheight">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="dcName" label="名称:">
        </el-table-column>
        <el-table-column prop="dcType" label="分类"/>
        <el-table-column prop="dcNote" label="说明"/>>
        <el-table-column prop="address" label="操作" width="250">
            <template #default="scope">
                <div style="display: flex;justify-content: space-between;width: 100%;">
                    <el-button type="primary" @click="showPei(scope.row)" size="mini" text style="margin-left: 0%;">数据项配置</el-button>
                    <el-button type="primary" @click="showEdit(scope.row)" size="mini" text style="margin-left:0%;">编辑</el-button>
                    <el-button @click="delRow(scope.row)" type="danger" text size="mini" style="margin-left: 0%;">删除</el-button>
                </div>
            </template>
        </el-table-column>
      </el-table>
      <div style="float: right;margin-top: 0.5%;margin-right: 1%;">
          <!-- <el-pagination
            small
            v-model='currentPage'
            @current-change="changePage"
            background
            layout="prev, pager, next"
            :total="total"
            class="mt-4"
          /> -->
        </div>
    </div>
  </div>
  <el-dialog :title="title" @close="clearForm" v-model="dialogVisible" title="" width="30%"  destroy-on-close :key="tableKey">
    <el-form :label-width="140" label-position="right" :disabled="isEdit" style="margin-left: 5%;margin-top: 2%;"  :model="formZu" class="demo-form-inline" ref="formRefZu" :rules="rulesZu">
      <el-form-item label="数据集中文名:" prop="dcName" style="">
        <el-input v-model="formZu.dcName" style="width: 75%;" placeholder=""  resize="none"/>
      </el-form-item>
      <el-form-item label="数据集说明:" prop="dcNote" style="">
        <el-input v-model="formZu.dcNote" style="width: 75%;" placeholder="" type="textarea" :row="2" resize="none"/>
      </el-form-item>
      <el-form-item label="数据集类型:" prop="dcType" style="">
        <el-select
          v-model="formZu.dcType"
          class="noBorSel"
          placeholder=""
          style="width: 75%;margin-left: 0%;"
          >
              <el-option
              v-for="item in optionsShuLei"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="排序:" prop="dcSort">
        <el-input-number v-model="formZu.dcSort" :min="1" style="width: 50%;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="dialogVisible = false">取消</el-button>
        <el-button v-if="isAddTa" type="primary" @click="addTa" size="mini">
          提交
        </el-button>
        <el-button v-if="!isAddTa" type="primary" @click="saveEditTa" size="mini">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog @close=""  v-model="dialogVisibleTree" title="sql配置管理" width="60%" destroy-on-close :key="tableKey" @opened="refreshEditor">
    <div style="display: flex;align-items: center;width: 100%;">
      <div>
        数据源：
      </div>
      <div style="width: 15%;">
        <el-select
        v-model="dsCodeSql"
        size="mini"
        style="width: 100%;margin-left: 1%;"
        >
            <el-option
            v-for="item in optionsDs"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
      </div>
    </div>
    <div style="border: solid  1px #e9e9eb;margin-top:1%;">
      <Codemirror 
      v-model:value="codeSQl" 
      :options="cmOptions" 
      height="100px"
      ref="cmRef"
      style="margin-top: 0%;"
    />
    </div>
    <div style="margin-top:0%;">
      <div style="display: flex;justify-content: space-between;align-items: center;">
        
      </div>
      <el-button @click="testSql" style="margin-top: -3%;left: 93%;z-index:555;position: absolute;" type="info" plain size="mini">测试</el-button>
      <el-button v-if="activeName=='first'" @click="addCan" style="position: absolute;right: 1%;margin-top: 2%;" type="success" size="mini" plain>新增字段</el-button>
      <el-tabs
        v-model="activeName"
        type="card"
        class="demo-tabs"
        style="margin-top: 2%;"
        @tab-click="handleClick"
      >
        
        <el-tab-pane label="参数" name="first">
          <div style="display: flex;width: 100%;margin-top: 0%;">
            
          </div>
          <el-table 
          style="margin-top: 1%;width: 98%;"
          :data="tableDataCan" 
          :cell-style="{ textAlign: 'center',padding:'2px 0' }"
          :header-cell-style="{ textAlign: 'center'}"
          :row-style="{ height: heightAll*0.01+'px',fontSize: '16px',textAlign:'center'  }"
          border >
              <el-table-column prop="itemName" label="字段编码" width="200">
                  <template #default="scope">
                      <el-input placeholder="(必填)" type="primary" class="noBor" v-model="scope.row.paramCode" size="mini" text style="margin-left: 0%;"></el-input>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="字段名称">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.paramName" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="字段类型(必填)">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.paramType" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="长度" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.paramLength" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="默认值" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.paramValue" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="说明" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.paramNote" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="主键" width="80">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-checkbox v-model="scope.row.fieldIspri" label="" size="large" />
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="address" label="操作" width="100">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-button type="danger" @click="delCan(scope.$index)" size="mini" text style="margin-left: 0%;">删除</el-button>
                      </div>
                  </template>
              </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="结果集" name="second">
          <el-tree :expand-on-click-node="false" ref="treeRefReturun" :filter-node-method="filterNode" :current-node-key="currentNodeKey" class="treeLeft" 
          :data="dataTreeReturn" @node-click="" node-key="id" style="margin-left: 1%;margin-top: 0%;width: 50%;background-color: transparent;"
            default-expand-all :key="valueKet" :props="defaultProps">
            <template #default="{ node, data }">
              <span style="justify-content: space-between;display: flex;width: 30%;align-items: center;margin-left: 1%;" @mouseenter="setId(data)">
                <div class="custom-tree-node" style="align-items: center;line-height: 1.5;font-size: 10px;">
                  <span style="font-size: 1rem;">{{ data.fieldCode }}</span>
                </div>
                <div style="position: absolute;left:40%;">
                  <div style="color: #67C23A;" v-if="data.fieldType=='string'">
                    string
                  </div>
                  <div style="color: #E6A23C;" v-else-if="data.fieldType=='array'">
                    array
                  </div>
                  <div style="color: #F56C6C;" v-else-if="data.fieldType=='number'">
                    number
                  </div>
                  <div style="color: #909399;" v-else>
                    {{ data.fieldType }}
                  </div>
                </div>
                <div style="margin-right: 1%;position: absolute;left:60%;">
                  <el-dropdown trigger="hover">
                      <svg-icon icon-class="zhankai"/>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item style="display: flex;" @click="add1LevelTree">
                          <el-icon class="el-icon--right" style="color: black;">
                            <CirclePlus />
                          </el-icon>
                          <div>
                            添加同级
                          </div>
                        </el-dropdown-item>
                        <el-dropdown-item style="display: flex;"  @click="addNextLevelTree">
                          <el-icon class="el-icon--right" style="color: black;">
                            <Connection />
                          </el-icon>
                          <div>
                            新建下级
                          </div>
                        </el-dropdown-item>
                        <divider/>
                        <el-dropdown-item style="display: flex;"  @click="delNode" divided>
                          <el-icon class="el-icon--right" style="color: black;">
                            <CircleClose />
                          </el-icon>
                          <div>
                            删除
                          </div>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div style="margin-right: 1%;position: absolute;left:70%;">
                  <div style="">
                    <span style="font-size: 1rem;">{{ data.fieldName }}</span>
                  </div>
                </div>
              </span>
            </template>
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="预览" name="third">
          <div style="overflow: auto;height: 20vh;margin-top: -1%;">
            <el-input placeholder="" :rows="8" type="textarea" v-model="testSqlResult" size="mini" text style="margin-top: 1%;width: 98%;" ></el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div>
      </div>
  </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleTree = false">取消</el-button>
        <el-button type="primary" @click="addPei" size="mini">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog @close="clearForm" v-model="dialogVisibleData" title="新增数据项" width="30%"  destroy-on-close :key="tableKey">
    <el-form :label-width="100" label-position="right" :disabled="isEdit" style="margin-left: 5%;margin-top: 2%;"  :model="formTree" class="demo-form-inline" ref="formRefTree" :rules="rulesTree">
      <el-form-item label="名称:" prop="itemName" style="">
        <el-input v-model="formTree.itemName" style="width: 75%;" placeholder=""  resize="none"/>
      </el-form-item>
      <el-form-item label="说明:" prop="itemNotes">
        <el-input v-model="formTree.itemNotes" style="width: 75%;" placeholder=""  resize="none"/>
      </el-form-item>
      <el-form-item label="节点:" prop="itemNotes" v-if="byNode">
        <el-tree-select
          v-model="valueNode"
          :data="data"
           check-strictly
          :render-after-expand="true"
          style="width: 75%;"
        />
      </el-form-item>
      <el-form-item label="级别:" prop="itemNotes" v-if="byNode">
        <el-radio-group v-model="radioLev" class="ml-4">
          <el-radio label="1" size="small">同级</el-radio>
          <el-radio label="2" size="small">子级</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序:" prop="itemNo">
        <el-input-number v-model="formTree.itemNo" :min="1" style="width: 50%;"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleData = false">取消</el-button>
        <el-button type="primary" @click="addataXiang" size="mini">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog @close=""  v-model="dialogVisibleApi" title="api配置管理" width="60%" destroy-on-close :key="tableKey">
    <div style="display: flex;align-items: center;width: 100%;">
      <div>
        API：
      </div>
      <div style="width: 18%;">
        <el-tree-select
          v-model="valueSel"
          :data="dataSel"
          :render-after-expand="false"
          style="margin-left:1%;width: 100%;"
        />
      </div>
    </div>
    <div style="margin-top:0%;">
      <div style="display: flex;justify-content: space-between;align-items: center;">
        
      </div>
      <el-button style="margin-top: 2%;left: 92%;z-index:555;position: absolute;" type="info" plain size="mini">测试</el-button>
      <el-button v-if="activeName=='first'" @click="addCan" style="position: absolute;right: 1%;margin-top: 2%;" type="success" size="mini" plain>新增字段</el-button>
      <el-tabs
        v-model="activeName"
        type="card"
        class="demo-tabs"
        style="margin-top: 2%;"
        @tab-click="handleClick"
      >
        
        <el-tab-pane label="参数" name="first">
          <div style="display: flex;width: 100%;margin-top: 0%;">
            <!-- <el-button  @click="addCan" style="margin-top: 0%;" type="success" size="mini" plain>新增字段</el-button> -->
          </div>
          <el-table 
          style="margin-top: 1%;width: 98%;"
          :data="tableDataCan" 
          :cell-style="{ textAlign: 'center',padding:'2px 0' }"
          :header-cell-style="{ textAlign: 'center'}"
          :row-style="{ height: heightAll*0.01+'px',fontSize: '16px',textAlign:'center'  }"
          border >
              <el-table-column prop="itemName" label="字段编码" width="200">
                  <template #default="scope">
                      <el-input placeholder="(必填)" type="primary" class="noBor" v-model="scope.row.paramCode" size="mini" text style="margin-left: 0%;"></el-input>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="字段名称">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.paramName" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="字段类型(必填)">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.paramType" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="长度" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.paramLength" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="默认值" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.paramValue" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="说明" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.paramNote" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="主键" width="80">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-checkbox v-model="scope.row.fieldIspri" label="" size="large" />
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="address" label="操作" width="100">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-button type="danger" @click="delCan(scope.$index)" size="mini" text style="margin-left: 0%;">删除</el-button>
                      </div>
                  </template>
              </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="结果集" name="second">
          <el-tree :expand-on-click-node="false" ref="treeRefReturun" :filter-node-method="filterNode" :current-node-key="currentNodeKey" class="treeLeft" 
          :data="dataTreeReturn" @node-click="" node-key="id" style="margin-left: 1%;margin-top: 0%;width: 50%;background-color: transparent;"
            default-expand-all :key="valueKet" :props="defaultProps">
            <template #default="{ node, data }">
              <span style="justify-content: space-between;display: flex;width: 30%;align-items: center;margin-left: 1%;" @mouseenter="setId(data)">
                <div class="custom-tree-node" style="align-items: center;line-height: 1.5;font-size: 10px;">
                  <span style="font-size: 1rem;">{{ data.fieldCode }}</span>
                </div>
                <div style="position: absolute;left:40%;">
                  <div style="color: #67C23A;" v-if="data.fieldType=='string'">
                    string
                  </div>
                  <div style="color: #E6A23C;" v-else-if="data.fieldType=='array'">
                    array
                  </div>
                  <div style="color: #F56C6C;" v-else-if="data.fieldType=='number'">
                    number
                  </div>
                  <div style="color: #909399;" v-else>
                    {{ data.fieldType }}
                  </div>
                </div>
                <div style="margin-right: 1%;position: absolute;left:60%;">
                  <el-dropdown trigger="hover">
                      <svg-icon icon-class="zhankai"/>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item style="display: flex;" @click="add1LevelTree">
                          <el-icon class="el-icon--right" style="color: black;">
                            <CirclePlus />
                          </el-icon>
                          <div>
                            添加同级
                          </div>
                        </el-dropdown-item>
                        <el-dropdown-item style="display: flex;"  @click="addNextLevelTree">
                          <el-icon class="el-icon--right" style="color: black;">
                            <Connection />
                          </el-icon>
                          <div>
                            新建下级
                          </div>
                        </el-dropdown-item>
                        <divider/>
                        <el-dropdown-item style="display: flex;"  @click="delNode" divided>
                          <el-icon class="el-icon--right" style="color: black;">
                            <CircleClose />
                          </el-icon>
                          <div>
                            删除
                          </div>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div style="margin-right: 1%;position: absolute;left:70%;">
                  <div style="">
                    <span style="font-size: 1rem;">{{ data.fieldName }}</span>
                  </div>
                </div>
              </span>
            </template>
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="预览" name="third">
          <div style="overflow: auto;height: 20vh;margin-top: -1%;">
            <el-input placeholder="" :rows="8" type="textarea" v-model="JsonAdd" size="mini" text style="margin-top: 1%;width: 98%;" ></el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div>
          
          
      </div>
  </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="mini" @click="dialogVisibleTree = false">取消</el-button>
        <el-button type="primary" @click="addPei" size="mini">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog @close=""  v-model="dialogVisibleFile" title="文件配置管理" width="60%" destroy-on-close :key="tableKey">
    <div style="display: flex;align-items: center;width: 100%;">
      <div>
        文件类型：
      </div>
      <div style="width: 18%;">
        <el-select
        v-model="fileType"
        size="mini"
        style="width: 100%;margin-left: 1%;"
        >
            <el-option
            v-for="item in optionsFileTy"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
      </div>
      <!-- <div style="margin-left:2% ">
        文件格式：
      </div>
      <div style="width: 18%;;">
        <el-select
        v-model="valueDs"
        size="mini"
        style="width: 100%;margin-left: 1%;"
        >
            <el-option
            v-for="item in optionsFilege"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
      </div> -->
    </div>
    <el-divider/>
    <div style="display: flex;align-items: center;width: 100%;">
      
    </div>
    <div style="margin-top:0%;">
      <div style="display: flex;justify-content: space-between;align-items: center;">
        
      </div>
      <el-button style="margin-top: 2%;left: 92%;z-index:555;position: absolute;" type="info" plain size="mini">测试</el-button>
      <el-tabs
        v-model="activeName"
        type="card"
        class="demo-tabs"
        style="margin-top: 2%;"
        @tab-click="handleClick"
      >
        
        <el-tab-pane label="参数" name="first">
          <el-upload
              ref="uploadRef"
              :limit="1"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :on-change="handleChange"
              :file-list="fileList"
              :action="upload.url + '?file=' + upload.updateSupport"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
          >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <el-link style="margin-top: 1%;" type="primary" @click="download">{{fileName}}</el-link>
        </el-tab-pane>
        <el-tab-pane label="结果集" name="second">
          <el-tree :expand-on-click-node="false" ref="treeRefReturun" :filter-node-method="filterNode" :current-node-key="currentNodeKey" class="treeLeft" 
          :data="dataTreeReturn" @node-click="" node-key="id" style="margin-left: 1%;margin-top: 0%;width: 50%;background-color: transparent;"
            default-expand-all :key="valueKet" :props="defaultProps">
            <template #default="{ node, data }">
              <span style="justify-content: space-between;display: flex;width: 30%;align-items: center;margin-left: 1%;" @mouseenter="setId(data)">
                <div class="custom-tree-node" style="align-items: center;line-height: 1.5;font-size: 10px;">
                  <span style="font-size: 1rem;">{{ data.fieldCode }}</span>
                </div>
                <div style="position: absolute;left:40%;">
                  <div style="color: #67C23A;" v-if="data.fieldType=='string'">
                    string
                  </div>
                  <div style="color: #E6A23C;" v-else-if="data.fieldType=='array'">
                    array
                  </div>
                  <div style="color: #F56C6C;" v-else-if="data.fieldType=='number'">
                    number
                  </div>
                  <div style="color: #909399;" v-else>
                    {{ data.fieldType }}
                  </div>
                </div>
                <div style="margin-right: 1%;position: absolute;left:60%;">
                  <el-dropdown trigger="hover">
                      <svg-icon icon-class="zhankai"/>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item style="display: flex;" @click="add1LevelTree">
                          <el-icon class="el-icon--right" style="color: black;">
                            <CirclePlus />
                          </el-icon>
                          <div>
                            添加同级
                          </div>
                        </el-dropdown-item>
                        <el-dropdown-item style="display: flex;"  @click="addNextLevelTree">
                          <el-icon class="el-icon--right" style="color: black;">
                            <Connection />
                          </el-icon>
                          <div>
                            新建下级
                          </div>
                        </el-dropdown-item>
                        <divider/>
                        <el-dropdown-item style="display: flex;"  @click="delNode" divided>
                          <el-icon class="el-icon--right" style="color: black;">
                            <CircleClose />
                          </el-icon>
                          <div>
                            删除
                          </div>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <div style="margin-right: 1%;position: absolute;left:70%;">
                  <div style="">
                    <span style="font-size: 1rem;">{{ data.fieldName }}</span>
                  </div>
                </div>
              </span>
            </template>
          </el-tree>
        </el-tab-pane>
        <el-tab-pane label="预览" name="third">
          <div style="overflow: auto;height: 20vh;margin-top: -1%;">
            <el-input placeholder="" :rows="8" type="textarea" v-model="JsonAdd" size="mini" text style="margin-top: 1%;width: 98%;" ></el-input>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div>
          
          
      </div>
  </div>
    <template #footer>
      <span class="dialog-footer"> 
        <el-button size="mini" @click="dialogVisibleTree = false">取消</el-button>
        <el-button type="primary" @click="addPei" size="mini">
          提交
        </el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog @close="clear" title="" v-model="dialogVisibleTreeEdit" width="55%" destroy-on-close :key="tableKey">
      <el-button  @click="addCanAdd" style="margin-top: 1%;" type="success" size="mini" :disabled="isEdit" plain>新增参数</el-button>
      <el-table 
          style="margin-top: 1%;width: 98%;"
          :data="tableDataCanAdd" 
          :cell-style="{ textAlign: 'center',padding:'2px 0' }"
          :header-cell-style="{ textAlign: 'center'}"
          :row-style="{ height: heightAll*0.01+'px',fontSize: '16px',textAlign:'center'  }"
          border >
              <el-table-column prop="itemName" label="字段编码" width="200">
                  <template #default="scope">
                      <el-input placeholder="(必填)" type="primary" class="noBor" v-model="scope.row.fieldCode" size="mini" text style="margin-left: 0%;"></el-input>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="字段名称">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.fieldName" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="字段类型">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="" type="primary" class="noBor" v-model="scope.row.fieldType" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="长度" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.fieldLength" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="默认值" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.fieldDefault" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="说明" >
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input type="primary" class="noBor" v-model="scope.row.fieldDesc" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="主键" width="80">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-checkbox v-model="scope.row.fieldIspri" label="" size="large" />
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="address" label="操作" width="100">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-button type="danger" @click="delCanAdd(scope.$index)" size="mini" text style="margin-left: 0%;">删除</el-button>
                      </div>
                  </template>
              </el-table-column>
          </el-table>
      <template #footer>
          <span class="dialog-footer">
            <el-button size="mini" @click="dialogVisibleTreeEdit = false">取消</el-button>
            <el-button type="primary" @click="addToTree" size="mini">
              确定
            </el-button>
        </span>
      </template>
    </el-dialog>
</template>
<script   setup>
import { reactive } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { modelTreeSelect } from "@/api/service/info";
import { cateTree,addCate,delCate,fieldAll,addSet,dataSetList,editSet,fieldAdd,delField,getDataSourceList,delSet,dataJisql,
  dataJiApi,dataJiFile,dataJiSql,getDataJiSql, getDataJiApi,getDataJiFile,getDataJiParam,getDataJiParamRe,addJiFan,addJiCan
  } from "@/api/register/regCom.js";
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import Codemirror from 'codemirror-editor-vue3';
import { getToken } from "@/utils/auth";
import { cloneDeep } from 'lodash'
import 'codemirror/lib/codemirror.css'; // 核心样式
import 'codemirror/theme/dracula.css';  // 主题
import 'codemirror/mode/sql/sql.js'; 
import { id } from 'element-plus/es/locales.mjs';
const code = ref('const example = "Hello, CodeMirror!"');
const cmRef = ref(null)
const optionsFileTy = ref([
  {
    value:'excel',
    label:'excel'
  },
  {
    value:'csv',
    label:'csv'
  },
  {
    value:'txt',
    label:'txt'
  },
])
const cmOptions = {
  mode: 'x-sql',
  hintOptions: {
    completeSingle: false,
    tables: {
      users: ['id', 'name', 'email'],   // 自定义表字段提示
      products: ['id', 'price', 'stock']
    }
  }
};
const downLink = ref('')
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: '',
  // 设置上传的请求头部 
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/common/upload"
});
const tableDataCan = ref([])
const optionsShuLei = ref([
  {label:"SQL数据集",
    value:'SQL数据集'
  },
  {label:"API数据集",
    value:'API数据集'
  },
  {label:"文件数据集",
    value:'文件数据集'
  },
])
const valueNode = ref('')
const radioLev = ref('1')
const dsCodeSql = ref('')
const activeName = ref('first')
const uploadRef = ref(null);
const dialogVisibleApi = ref(false)
const dialogVisibleFile = ref(false)
const valueSel = ref('')
const { proxy } = getCurrentInstance();
const data =  ref([])
const title =  ref([])
const titleTree =  ref([])
const dialogVisibleData = ref(false)
const currentPage =  ref(1)
const total =  ref(1)
const tableData = ref([])
const tableheight = window.innerHeight*0.78
const heightAll = window.innerHeight
const dialogVisible = ref(false)
const dialogVisibleTreeEdit = ref(false)
const parLevTree = ref(1)
const isAdd = ref(false)
const isAddTa = ref(false)
const treeId = ref('');
const dcName =ref() 
const parDel = ref({})
const parTree = ref(null)
const fileName = ref('')
const dataTreeReturn = ref([])
const codeSQl = ref('')
const fileType = ref('')
const dialogVisibleTree = ref(false)
const parDcCode = ref('')
const formZu = ref({
  cateId:'',
  dcName:'',
  dcType:'',
  dcSort:1,
  dcNote:''
});
const byNode = ref(false)
const optionsDs = ref([])
const testSqlResult = ref('')
const currentNodeKey = ref('')
const rulesZu = reactive({
  dcName: [{ required: true, message: '必填', trigger: 'blur' }],
  dcType: [{ required: true, message: '必填', trigger: 'blur' }],
  dcSort: [{ required: true, message: '必填', trigger: 'blur' }],
});
const formRefZu = ref();
const tableDataCanAdd = ref([])
const idCount = ref(500)
const formTree = ref({
  itemName:'',
  itemNo:'',
  itemNotes:'',
});
const parType = ref('')
const defaultProps = ref({
  children: 'children',
})
const dataSel = ref([])
const parMeta = ref({})
const rulesTree = reactive({
  itemName: [{ required: true, message: '必填', trigger: 'blur' }],
  itemNo: [{ required: true, message: '必填', trigger: 'blur' }]
});
const formRefTree = ref();
const parDscode = ref('')
const parLev = ref(1)
const parAr = ref([])
const parTreeId = ref('')
const parTreeParentId = ref('')
function clear(){
  tableDataCanAdd.value = []
}
async function delNode(){
  removeNodeById(dataTreeReturn.value,parTreeId.value)
}
function removeNodeById(tree, targetId) {
  // 检查树是否为空
  if (!tree || !Array.isArray(tree) || tree.length === 0) {
    return false;
  }

  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    
    // 如果找到目标节点
    if (node.id === targetId) {
      tree.splice(i, 1); // 从数组中删除该节点
      return true; // 返回删除成功
    }
    
    // 如果当前节点有子节点，递归遍历子节点
    if (node.children && node.children.length > 0) {
      const isRemoved = removeNodeById(node.children, targetId);
      if (isRemoved) {
        return true; // 如果在子树中成功删除，直接返回
      }
    }
  }
  
  return false; // 未找到目标节点
}
function setId(data){
  parTreeId.value = data.id
  parTreeParentId.value = data.parentId
}
function addDir() {
  byNode.value = true
  valueNode.value = data.value[0].value
  dialogVisibleData.value = true
}
function add1LevelTree(){
  dialogVisibleTreeEdit.value = true
  parLev.value = 1
}
function addNextLevelTree(){
  dialogVisibleTreeEdit.value = true
  parLev.value = 2
}
function testSql(){
  if(!dsCodeSql.value){
    proxy.$modal.msgWarning("数据源编码不能为空");
  }
  else if(!codeSQl.value){
    proxy.$modal.msgWarning("sql语句不能为空");
  }
  else{
    var par = {
      dsCode:dsCodeSql.value,
      sql:codeSQl.value
    }
    dataJisql(par).then(res=>{
      if(res.code===200){
        proxy.$modal.msgSuccess(res.msg);
        testSqlResult.value = res.msg
      }
    })
  }
  
}
function download(){
  var url = window.location.host + downLink.value
  console.log(url)
  const link = document.createElement('a');
  link.href = 'http://' + url.toString();
  link.download = downLink.value; // 自定义文件名（可选）
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}
async function getTreeSel(){
  await modelTreeSelect().then(res=>{
    dataSel.value = renameTreeProperties(res.data)
    console.log(dataSel.value)
  })
}
function filterModelNodes(nodes) {
  if (!Array.isArray(nodes)) return [];
  
  const result = [];
  for (const node of nodes) {
    // 递归处理子节点（如果有）
    const filteredChildren = node.children ? filterModelNodes(node.children) : [];
    
    if (node.nodeType === 'MODEL') {
      // 保留当前节点，并更新其子节点
      node.value = node.id
      result.push({
        ...node,
        children: filteredChildren
      });
    } else {
      // 删除当前节点，将其子节点提升到当前层级
      result.push(...filteredChildren);
    }
  }
  return result;
}
function getOptionsDs(){
  getDataSourceList().then(res=>{
    optionsDs.value = res.rows
    optionsDs.value.forEach(item=>{
        item.label = item.dsDbname
        item.value = item.dsCode
    })
    total.value = res.total
  })
}
const refreshEditor = () => {
  nextTick(() => {
    cmRef.value?.refresh(); // 关键调用
  });
};
function delAll(){
    proxy.$modal.confirm('是否确认删除？').then(function () {
        return delCate(parTree.value.id);
    }).then(() => {
        getTree();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {});
}
function addToTree() {
  if(parLev.value === 1){
    parTreeParentId.value
    if(tableDataCanAdd.value){
      tableDataCanAdd.value.forEach(item=>{
        if(item.fieldIspri===true){
          item.fieldIspri = '1'
        }
        if(item.fieldIspri===true){
          item.fieldIspri = '0'
        }
        item.parentId = parTreeId.value
        item.dcCode = parDcCode.value
        addSiblingNode(dataTreeReturn.value,parTreeId.value,item)
      })
      dialogVisibleTreeEdit.value = false
      }
  }
  if(parLev.value === 2){
    tableDataCanAdd.value.forEach(item=>{
      item.parentId = parTreeId.value
      item.dcCode = parDcCode.value
      addChildNode(dataTreeReturn.value,parTreeId.value,item)
    })
    dialogVisibleTreeEdit.value = false
  }
  console.log(findNode(dataTreeReturn.value,parTreeParentId.value))
}
function flattenTreeWithArrayIndex(treeData, parentId = 0, result = []) {
    for (const node of treeData) {
        // 创建新节点对象，避免污染原数据
        const newNode = {
            id: node.id,
            parentId: parentId,
            dcCode:parDcCode.value,
            fieldCode: node.fieldCode,
            fieldName: node.fieldName,
            fieldType: node.fieldType,
            fieldLength: node.fieldLength,
            fieldDesc: node.fieldDesc,
            fieldDefault: node.fieldDefault,
            fieldIspri: node.fieldIspri,
            isArray: node.isArray,
            arrayIndex: node.arrayIndex
            // 可根据需要添加或删除其他属性
        };
        result.push(newNode);
        // 处理当前节点的子节点
        if (node.children && node.children.length > 0) {
            idCount.value++
            if (node.fieldType === 'array') {
                // 为 array 类型节点创建中间索引层级
                var par = idCount.value
                const middleNode = {
                    id: par, // 使用随机ID
                    parentId: node.id,
                    dcCode:parDcCode.value,
                    fieldCode: '[0]',
                    fieldName: node.fieldName,
                    fieldType: node.fieldType,
                    fieldLength: node.fieldLength,
                    fieldDesc: node.fieldDesc,
                    fieldDefault: node.fieldDefault,
                    fieldIspri: node.fieldIspri,
                    isArray: null, // 通常不是数组
                    arrayIndex: 0 // 数组索引
                };
                result.push(middleNode);
                // 递归处理子节点，并将中间层节点作为它们的父节点
                flattenTreeWithArrayIndex(node.children, par, result);
            } else {
                // 非 array 类型节点，直接递归处理子节点
                flattenTreeWithArrayIndex(node.children, node.id, result);
            }
        }
    }
    return result;
}
function findNode(nodes, targetId, mode = 'id') {
  if (!Array.isArray(nodes)) return null;
  
  for (const node of nodes) {
    // 检查当前节点是否匹配目标
    if ((mode === 'id' && node.id === targetId) || (mode === 'parentId' && node.parentId === targetId)) {
      return node;
    }
    // 如果该节点有子节点，则递归搜索其子树
    if (node.children && node.children.length > 0) {
      const found = findNode(node.children, targetId, mode);
      if (found) return found;
    }
  }
  return null; // 未找到
}
function addChildNode(treeData, parentId, newNode) {
  const parentNode = findNode(treeData, parentId, 'id');
  if (!parentNode) {
    console.warn(`未找到ID为 ${parentId} 的父节点`);
    return false;
  }
  
  // 初始化父节点的children数组（如果不存在）
  if (!Array.isArray(parentNode.children)) {
    parentNode.children = [];
  }
  
  // 将新节点添加到父节点的children数组中
  parentNode.children.push(newNode);
  return true;
}
function addSiblingNode(treeData, siblingId, newNode) {
  // 1. 首先找到目标兄弟节点
  const siblingNode = findNode(treeData, siblingId, 'id');
  console.log(siblingNode)
  if (!siblingNode) {
    console.warn(`未找到ID为 ${siblingId} 的兄弟节点`);
    return false;
  }
  
  // 2. 找到兄弟节点的父节点（通过parentId查找）
  const parentNode = findNode(treeData, siblingNode.parentId, 'id');
  console.log(parentNode)
  if (!parentNode&&siblingNode) {
    newNode.id = (idCount.value++)*10
    treeData.push(newNode);
    return true;
  }
  
  // 3. 将新节点添加到父节点的children数组中
  if (!Array.isArray(parentNode.children)) {
    parentNode.children = [];
  }
  parentNode.children.push(newNode);
  return true;
}
function addValueField(nodes) {
  if (!Array.isArray(nodes)) return;
  
  for (const node of nodes) {
    // 添加value字段，其值等于id
    node.value = node.id;
 
    // 如果存在子节点，递归处理
    if (node.children && Array.isArray(node.children)) {
      addValueField(node.children);
    }
  }
}
const flattenTree = (nodes) => {
  const result = [];
  const stack = [...nodes];
  while (stack.length) {
    const node = stack.pop();
    result.push({ id: node.id, pid: node.pid }); // 只提取 id 和 pid
    if (node.children && node.children.length) {
      stack.push(...node.children);
    }
  }
  return result;
};
function addataXiang(){
  console.log(data.value)
  if(byNode.value===true){
    if(radioLev.value==='2'){
      formTree.value.catePid = valueNode.value
    }
    else{
      var par = ''
      parAr.value.forEach(item => {
        if (item.id === valueNode.value) {
          par = item.pid
        }
      })
      formTree.value.catePid = par
    }
    addCate(formTree.value).then(res=>{
        if(res.code===200){
            proxy.$modal.msgSuccess("修改成功");
            getTree()
            dialogVisibleData.value = false
        }
    })
  }
  else{
    if(parLev.value===1){
        formTree.value.catePid = parTree.value.pid
    }
    else{
        formTree.value.catePid = parTree.value.id
    }
    addCate(formTree.value).then(res=>{
        if(res.code===200){
            proxy.$modal.msgSuccess("修改成功");
            getTree()
            dialogVisibleData.value = false
        }
    })
  }
}
function add1Level(){
    byNode.value = false
    parLevTree.value = 1
    dialogVisibleTreeEdit.value = true
}
function addNextLevel(){
    byNode.value = false
    parLevTree.value = 2
    dialogVisibleTreeEdit.value = true
}
async function addPei(){
  
  if(parType.value==='SQL数据集'){
    console.log(dataTreeReturn.value)
    console.log(flattenTreeWithArrayIndex(dataTreeReturn.value))
    var parDia = false
    var parDia1 = false
    await addJiFan(flattenTreeWithArrayIndex(dataTreeReturn.value)).then(res=>{
      if(res.code===200){
        parDia = true
      }
    })
    await addJiCan(tableDataCan.value).then(res=>{
      if(res.code===200){
        parDia1 = true
      }
    })
    var par = {
      dsCode:dsCodeSql.value,
      dcCode:parDcCode.value,
      runSql:codeSQl.value
    }
    await dataJiSql(par).then(res=>{
      if(res.code===200&&parDia&&parDia1){
        proxy.$modal.msgSuccess("编辑成功");
        dialogVisibleTree.value = false
      }
    })
  }
  if(parType.value==='API数据集'){
    console.log(dataTreeReturn.value)
    console.log(flattenTreeWithArrayIndex(dataTreeReturn.value))
    var parDia = false
    var parDia1 = false
    await addJiFan(flattenTreeWithArrayIndex(dataTreeReturn.value)).then(res=>{
      if(res.code===200){
        parDia = true 
      }
    })
    await addJiCan(tableDataCan.value).then(res=>{
      if(res.code===200){
        parDia1 = true
      }
    })
    var par = {
      srvId:valueSel.value,
      dcCode:parDcCode.value,
    }
    await dataJiApi(par).then(res=>{
      if(res.code===200&&parDia&&parDia1){
        proxy.$modal.msgSuccess("编辑成功");
        dialogVisibleApi.value = false
      }
    })
  }
  if(parType.value==='文件数据集'){
    await addJiFan(flattenTreeWithArrayIndex(dataTreeReturn.value)).then(res=>{
      if(res.code===200){
        parDia = true
      }
    })
    proxy.$refs["uploadRef"].submit();
  }
}
async function handleFileSuccess(response, file, fileList){
  var par = {
    dcCode:parDcCode.value,
    fileType:fileType.value,
    filePath:response.fileName,
    originalFilename:response.originalFilename
  }
  await dataJiFile(par).then(res=>{
    if(res.code===200){
      proxy.$modal.msgSuccess("编辑成功");
      dialogVisibleFile.value = false
    }
  })
};
function buildTree1(list, rootParentId = 0) {
  // 1. 创建一个映射（字典）以便通过id快速查找节点，并为每个节点初始化children数组
  const nodeMap = {};
  const tree = [];
  
  // 初始化映射，每个节点初始时都有空的孩子数组
  list.forEach(item => {
    nodeMap[item.id] = { ...item, children: [] };
  });
  
  // 2. 遍历数组，根据parentId将节点放入父节点的children中
  list.forEach(item => {
    const node = nodeMap[item.id];
    const parentId = item.parentId;
    
    if (parentId === rootParentId) {
      // 如果parentId是根父ID（默认为0），则作为根节点直接添加到树中
      tree.push(node);
    } else {
      // 否则，尝试找到父节点并将当前节点加入其children数组
      const parentNode = nodeMap[parentId];
      if (parentNode) {
        parentNode.children.push(node);
      } else {
        // 可选：处理parentId不存在于列表中的情况（孤儿节点）
        // 这里选择将其提升为根节点，你也可以选择其他处理方式，如console.warn报警
        tree.push(node);
      }
    }
  });
  
  // 3. 返回构建好的树
  return tree;
}
function dfsRecursive(node, parent = null, grandParent = null) {
  if (!node) return;
   const reg = /\[\d+\]/;
   console.log(2)
  if (parent && reg.test(parent.fieldCode)) {
    console.log(1)
    grandParent.children = []
    grandParent.children.push(parent);
    parent.children.forEach(child => {
      child.parentId = grandParent.id
      grandParent.children.push(child);
    });
    grandParent.children.splice(0,1)
  }
  if(node.children){
    node.children.forEach(child => {
      dfsRecursive(child, node, parent);
    });
  }
  return node;
}
async function showPei(row){
  parDcCode.value = row.dcCode
  parType.value = row.dcType
  var par = {
    dcCode:row.dcCode,
  }
  await getDataJiParam(par).then(res=>{
    if(res.code===200){
      tableDataCan.value = res.data
    }
  })
  await getDataJiParamRe(par).then(res=>{
    if(res.code===200){
      dataTreeReturn.value = res.data
      // dataTreeReturn.value = []
      // var par = {
      //     id:idCount.value,
      //     parentId:0,
      //     fieldCode:'data',
      //     fieldType:'array',
      //   }
      //   dataTreeReturn.value.push(par)
      if(dataTreeReturn.value.length === 0){
        var par = {
          id:idCount.value,
          parentId:0,
          fieldCode:'data',
          fieldType:'array',
        }
        dataTreeReturn.value.push(par)
      }
      else{
        const fullTree = buildTree1(res.data)
        console.log(fullTree)
        fullTree.forEach((item,index) => {
          if(item.children && item.children.length > 0){
            item = dfsRecursive(item)
          }
        });
        dataTreeReturn.value = fullTree
      }
    }
  })
  if(row.dcType==='SQL数据集'){
    dialogVisibleTree.value = true
    getDataJiSql(row.dcCode).then(res=>{
      if(res.code===200){
        dsCodeSql.value = res.data.dsCode
        codeSQl.value = res.data.runSql
      }
    })
  }
  if(row.dcType==='API数据集'){
    dialogVisibleApi.value = true
    getDataJiApi(row.dcCode).then(res=>{
      if(res.code===200){
        codeSQl.value = res.data.runSql
      }
    })
  }
  if(row.dcType==='文件数据集'){
    dialogVisibleFile.value = true
   getDataJiFile(row.dcCode).then(res=>{
      if(res.code===200){
        downLink.value = res.data.filePath
        fileName.value = res.data.originalFilename
      }
    })
    
  }
  parMeta.value = row
  var par = {
    dsCode:parDscode.value,
    metaTable:row.metaTable,
  }
  // getMetaFiele(par).then(res=>{
  //   tableDataCanAdd.value = res.data
  //   tableDataCanAdd.value.forEach(item=>{
  //   if(item.fieldIspri==='1'){
  //     item.fieldIspri = true
  //   }
  //   if(item.fieldIspri==='2'){
  //     item.fieldIspri = false 
  //   }
  // })
  // })
}
function clearForm(){
  tableDataCan.value = []
  activeName.value = 'first'
  dataTreeReturn.value = []
}
function addCan(){
    var par = {
        dcCode:parDcCode.value,
    }
    tableDataCan.value.push(par) 
}
function delCan(index){
  tableDataCan.value.splice(index, 1)
}
function addCanAdd(){
    var par = {
        id: idCount.value++,
        dcCode:parDcCode.value,
    }
    tableDataCanAdd.value.push(par) 
}
function delCanAdd(index){
  tableDataCanAdd.value.splice(index, 1)
}
function getTable(){
  var par = {
    cateId:currentNodeKey.value,
  }
  dataSetList(par).then(res=>{
    tableData.value = res.rows
  })
}
function showAdd(){
  isAddTa.value = true
  title.value = '新增'
  dialogVisible.value = true
}
function showEdit(row){
  isAddTa.value = false
  title.value = '编辑'
  dialogVisible.value = true
  formZu.value = row
}
function showAddTree(){
  isAdd.value = true
  titleTree.value = '新增节点'
  dialogVisibleTree.value = true
}
function clearFromTree(){
  formTree.value = {
    itemName:'',
    catePid:'',
    itemNo:'',
    itemNotes:''
  }
}
function getTree(){
  cateTree().then(res=>{
    data.value = res.data
    data.value.forEach(item=>{
      item.value = item.id
      item.id = item.id
    })
    addValueField(data.value)
    parAr.value = flattenTree(data.value);
  })
}
function addTa(){
  formRefZu.value.validate(async (valid) => {
      if(valid){
        formZu.value.cateId = currentNodeKey.value
        await addSet(formZu.value).then(res=>{
        if(res.code===200){
          proxy.$modal.msgSuccess("新增成功");
          getTable()
          dialogVisible.value = false
        }
      })
    }
  }); 
}
function saveEditTa(){
  formRefZu.value.validate(async (valid) => {
      if(valid){
        editSet(formZu.value).then(res=>{
        if(res.code===200){
            proxy.$modal.msgSuccess("修改成功");
            dialogVisible.value = false
            getTable()
        }
    })
    }
  });
  
}
function delRow(row) {
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delSet(row.dcCode);
  }).then(() => {
    getTable();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};
async function addTree(){
  formRefTree.value.validate(async (valid) => {
    await addDataCate(formTree.value).then(res=>{
      if(res.code===200){
        proxy.$modal.msgSuccess("新增成功");
        getTree()
        dialogVisibleTree.value = false
      }
    })
  });
}
function saveEditTree(){
  editCate(formTree.value).then(res=>{
    if(res.code===200){
      proxy.$modal.msgSuccess("修改成功");
      dialogVisibleTree.value = false
      getTree()
    }
  })
}
function handleNodeClick(node, data){
    currentNodeKey.value = data.data.id
    parTree.value = data.data
    getTable()
}
function delTree(node, data) {
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delCate(data.id);
  }).then(() => {
    getTree();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
};
function editTree(node, data){
  console.log(data)
  titleTree.value = '编辑'
  isAdd.value = false
  dialogVisibleTree.value = true
  getCateDe(data.id).then(res=>{
    formTree.value = res.data
  })
  console.log(node, data)
}
function renameTreeProperties(tree) {
  // 深拷贝避免修改原始数据（可选，根据需求）
  const newTree = cloneDeep(tree); // 使用 lodash
  // 或：const newTree = JSON.parse(JSON.stringify(tree)); // 原生方法（不兼容函数等）

  // 递归处理函数
  const processNode = (node) => {
    // 重命名属性
    if ('cateName' in node) {
      node.label = node.cateName;
      delete node.cateName;
    }
    if ('id' in node) {
      node.value = node.id;
      delete node.id;
    }

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

  // 遍历根节点
  newTree.forEach(rootNode => processNode(rootNode));
  return newTree;
}
onMounted(() => {
  getTree()
  getOptionsDs()
  getTreeSel()
  // getTable()
});

</script>
<style scoped>
:deep(.svg-icon) {
  outline: none;
}
:deep(.svg-icon svg) {
  stroke: none;
}
:deep(.el-tree-node__expand-icon) {
  margin-left:5%; /* 向右推动图标 */
}
:deep(.el-table__body tr:hover > td) {
  background-color: #eaf7ff !important;
}
 :deep(.treeLeft) .el-tree-node__content {
  width: 100%;
  display: flex !important;
  height: 30px !important;
  align-items: center;
  padding-top: 0 !important;
}
:deep(.treeLeft) .el-tree-node__content:hover {
  background-color: #ecf5ff;
}
:deep(.treeLeft) .el-tree-node__content:active {
    background-color: #d9ecff !important;
  }

  /* 选中态（Active） */
:deep(.treeLeft) .el-tree-node.is-current > .el-tree-node__content {
    background-color: #c6e2ff !important;
  }
.drag-handle {
  cursor: move;
}

.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}

/* 防止文字选中 */
:deep(.el-table__row) {
  user-select: none;
  -webkit-user-select: none;
}
</style>
<style scoped lang="scss">


.el-table .el-table__row td {
  height: 60px !important; /* 行高 */
}
.custom-tree-node {
  display: flex;       /* 启用 Flex 布局 */
  align-items: center; /* 垂直居中 */
  gap: 6px;            /* 图标与文字间距 */
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center; 
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>