<template>
  <div style="width: 100%;;display: flex;">
    <div style="width: 15%;;background-color: #F2F6FC;max-height: 85vh;overflow: auto;">
      <div style="display: flex;padding-top: 1%;padding-top: 5%;">
        <el-input
          v-model="inputNode"
          style="width:75%;margin-left: 5%;background-color: #ebeef5;"
          class="w-50 m-2"
          :prefix-icon="Search" 
        />
        <!-- <el-button style="margin-left: 2%;width: 10%;background-color: #F7F7F7" :icon="Filter"/> -->
        <el-button type="primary" @click="showAdd" style="margin-left: 5%;width: 10%;" :icon="Plus"/>
      </div>
      <!-- <Plus style="width: 1em; height: 1em; margin-left:90%;cursor: pointer;color: #337ecc;" @click="showAddTree"/> -->
      <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: 5%;margin-top: 5%;width: 90%;background-color: transparent;" default-expand-all :key="valueKet">
          <template #default="{ node, data }">
            <span  style="justify-content: space-between;display: flex;width: 100%;align-items: center;" >
              <div class="custom-tree-node">
                  <!-- <el-tag v-if="data.nodeType=='MODEL'" class="ml-2" type="warning">模型</el-tag> -->
                   <svg-icon icon-class="model2" style="color: #eebe77;" v-if="data.nodeType=='MODEL'"/>
                  <!-- <el-tag  class="ml-2">
                    服务
                  </el-tag> -->
                  <svg-icon icon-class="model" dstyle="color: #13E03B;" v-if="data.nodeType=='SERVICE'"/>
                  <svg-icon svg-icon icon-class="cate" style="color: red;" v-if="data.nodeType=='TREE'"/>
                <span>{{ node.label }}</span>
              </div>
              <div style="margin-right: 1%;position: absolute;margin-left: 75%;">
                <el-dropdown trigger="hover" @click.stop v-if="currentNodeKey === data.id&&data.nodeType!=='SERVICE'">
                    <el-icon class="el-icon--right" style="color: black;">
                      <plus />
                    </el-icon>
                  <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>
    </div>
    <div style="width: 84%;margin-left: 1%;padding-top: 1%;" class="tab-container">
        <div style="overflow: auto;height: 80vh;">
                  <div style="display: flex;margin-top: 1%;">
                    <el-button type="primary" @click="saveEditService" style="margin-left: 80%;z-index: 1000;" :disabled="isEdit">提交</el-button>
                    <el-button type="danger" @click="delSer" style="margin-left: 1%;z-index: 1000;" :disabled="isEdit">删除</el-button>
                  </div>
                    <el-form size="mini" :key="tableKey" style="margin-top: -2%;width: 98%;"  :model="formJi" label-position="right" ref="formRefJi" label-width="120px" :rules="rulesJi">
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="服务名称:" prop="name" style="">
                                  <div style="display: flex;width: 100%;justify-content: space-between;">
                                    <el-input :disabled="isEdit" v-model="formJi.name" style="width: 100%;"/>
                                  </div>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                              <el-form-item label="接口类型:" prop="" style="">
                                <div style="display: flex;width: 100%;justify-content: space-between;">
                                  <el-select
                                    v-model="formJi.type"
                                    :disabled="isEdit"
                                        style="width: 100%;margin-left: 0%;"
                                    >
                                        <el-option
                                        v-for="item in optionsType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                                  <div style="display: flex;">
                                    
                                  </div>
                                </div>
                                    
                                </el-form-item>
                            </el-col>
                      </el-row>
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="接口地址:" prop="url" style=""> 
                                  <el-input
                                  v-model="formJi.url"
                                  :disabled="isEdit"
                                  style="width: 100%;"
                                  placeholder=""
                                  class="input-with-select"
                                  >
                                </el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="请求方式:" prop="" style="">
                                    <el-select
                                    v-model="formJi.rqtype"
                                    :disabled="isEdit"
                                        style="width: 100%;margin-left: 0%;"
                                    >
                                        <el-option
                                        v-for="item in optionsRqtype"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                      </el-row>
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="响应类型:" prop="" style="display: flex; align-items: center;">
                                <el-radio-group :disabled="isEdit" v-model="formJi.rptype" class="ml-4" style="display: inline-flex; align-items: center;">
                                  <el-radio label="1" size="large" style="display: inline-flex; align-items: center;">
                                    <span style="position: relative; top: -1px">JSON</span>
                                  </el-radio>
                                  <el-radio label="2" size="large" style="display: inline-flex; align-items: center;">
                                    <span style="position: relative; top: -1px">XML</span>
                                  </el-radio>
                                  <el-radio label="3" size="large" style="display: inline-flex; align-items: center;">
                                    <span style="position: relative; top: -1px">HTML</span>
                                  </el-radio>
                                </el-radio-group>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="服务分类:" prop="cateCode" style="">
                                    <el-cascader :disabled="isEdit" v-model="formJi.cateCode" :options="cascaderOptions" clearable style="width: 100%;"></el-cascader>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="8">
                                <el-form-item label="请求方式:" prop="name" style="">
                                    <el-select
                                    v-model="formJi.type"
                                    :disabled="isEdit"
                                        style="width: 100%;margin-left: 0%;"
                                    >
                                        <el-option
                                        v-for="item in optionsType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col> -->
                      </el-row>
                      <el-row :gutter="48">
                            <el-col :span="13">
                              <el-form-item label="服务说明:">
                                  <el-input :disabled="isEdit" v-model="formJi.intro" style="width: 100%;" :rows="3" resize="none" type="textarea"/>
                              </el-form-item>
                            </el-col>
                      </el-row>
                        
                    </el-form>
                    <div style="margin-top: 2%;">
                        <div style="display: flex;justify-content: space-between;align-items: center;">
                          <div>
                            请求参数
                          </div>
                          <div style="display: flex;justify-content: flex-end;margin-right: 2%;">
                            <el-button  @click="addPa" style="margin-top: 1%;" type="success" size="mini" :disabled="isEdit" plain>新增参数</el-button>
                          </div>
                        </div>
                        <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="参数字段(必填)">
                                    <template #default="scope">
                                        <div style="width: 100%;display: flex;">
                                            <el-input :disabled="isEdit" placeholder="请填写参数编码" type="primary" class="noBor" v-model="scope.row.paramCode" size="mini" text style="margin-left: 0%;border: transparent;"></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="itemName" label="参数名称(必填)">
                                    <template #default="scope">
                                        <div style="width: 100%;">
                                            <el-input :disabled="isEdit" 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="参数类型(必填)" width="200">
                                    <template #default="scope">
                                        <div style="width: 100%;">
                                            <el-select
                                            v-model="scope.row.paramType"
                                            class="noBorSel"
                                            :disabled="isEdit"
                                            placeholder=""
                                            style="width: 100%;margin-left: 0%;"
                                            >
                                                <el-option
                                                v-for="item in optionsCan"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                                />
                                    </el-select>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="itemName" label="参数说明" >
                                    <template #default="scope">
                                        <div style="width: 100%;">
                                            <el-input type="primary" :disabled="isEdit" 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="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>
                            
                        </div>
                    </div>
                    <div style="margin-top: 2%;">
                        <div style="display: flex;justify-content: space-between;align-items: center;">
                          <div>
                            返回参数
                          </div>
                          <div style="display: flex;justify-content: flex-end;margin-right: 2%;">
                          </div>
                        </div>
                        <div style="width: 98%;margin-left: 0%;height: 25vh;margin-top: 1%;overflow: auto;border: 1px solid #eee;">
                          <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;">{{ node.label }}</span>
                                </div>
                                <div style="position: absolute;left:40%;">
                                  <div style="color: #67C23A;" v-if="data.paramType=='string'">
                                    string
                                  </div>
                                  <div style="color: #E6A23C;" v-else-if="data.paramType=='array'">
                                    array
                                  </div>
                                  <div style="color: #F56C6C;" v-else-if="data.paramType=='number'">
                                    number
                                  </div>
                                  <div style="color: #909399;" v-else>
                                    {{ data.paramType }}
                                  </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="delAllTree" 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.paramName   }}</span>
                                  </div>
                                </div>
                              </span>
                            </template>
                          </el-tree>
                        </div>
                    </div>
                    <div style="margin-top: 2%;">
                        <!-- <div>返回响应</div> -->
                        <div style="color: #909399;margin-left: 7%;margin-top:1%;">此处填写本服务接口响应信息描述</div>
                        <el-tabs type="card" style="margin-top: -1.5%;width: 98%;">
                            <el-tab-pane label="响应内容">
                                <div style="display: flex; flex-direction: column;">
                                    <!-- <el-tree  :data="data" :props="defaultProps" @node-click="handleNodeClick" style="margin-top: 1%;margin-left: 2%;background-color: #F7F7F7;background-color: transparent;width: 15%;" default-expand-all>
                                        <template #default="{ node, data }">
                                            <span style="display: flex;justify-content: space-between;width: 100%;align-items: center;">
                                                <span><el-input v-model="node.label" size="mini"/></span>
                                                <span style="display: flex;align-items: center;">
                                                    <el-tooltip
                                                        class="box-item"
                                                        effect="light"
                                                        content="是否必填"
                                                        placement="top-start"
                                                    >
                                                    <el-checkbox v-model="checked1" label="" size="large" />
                                                    </el-tooltip>
                                                    <el-select
                                                        v-model="formJi.type"
                                                        :disabled="isEdit"
                                                        style="width: 100%;margin-left: -1%;"
                                                    >
                                                        <el-option
                                                        v-for="item in optionsType"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value"
                                                        />
                                                    </el-select>
                                                    <el-tooltip
                                                        class="box-item"
                                                        effect="light"
                                                        content="是否允许null"
                                                        placement="top-start"
                                                    >
                                                    <el-checkbox v-model="checked1" label="" size="large" />
                                                    </el-tooltip>
                                                </span>
                                            </span>
                                        </template>
                                    </el-tree> -->
                                   </div>
                            </el-tab-pane>
                        </el-tabs>
                        <div style="overflow: auto;height: 20vh;margin-top: -1%;">
                          <el-input @change="byWay" :disabled="isEdit" placeholder="请输入示例" :rows="8" type="textarea" v-model="dataJsonXiang" size="mini" text style="margin-top: 0%;width: 98%;" ></el-input>
                        </div>
                    </div>
                    <div style="margin-top: 2.5%;margin-left: 0%;padding-bottom: 1%;">
                    
                    <el-tabs type="card" style="margin-top: -1.5%;width: 98%;">
                        <el-tab-pane label="使用说明">
                             
                        </el-tab-pane>
                    </el-tabs>
                    <el-input :disabled="isEdit" placeholder="请输入示例" :rows="8" type="textarea" v-model="example" size="mini" text style="margin-top: -1%;width: 98%;" ></el-input>
                </div>
                </div>
        <el-dialog @close="clearAdd" v-model="dialogVisible" title="新增节点" width="70%" destroy-on-close :key="tableKey">
          <div style="overflow: auto;height: 80vh;">
                    <el-form size="mini" :key="tableKey" style="margin-top: 1%;width: 98%;"  :model="formAdd" label-position="right" ref="formRefAdd" label-width="120px" :rules="rulesAdd">
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="服务名称:" prop="name" style="">
                                  <div style="display: flex;width: 100%;justify-content: space-between;">
                                    <el-input v-model="formAdd.name" style="width: 100%;"/>
                                  </div>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                              <el-form-item label="接口类型:" prop="" style="">
                                <div style="display: flex;width: 100%;justify-content: space-between;">
                                  <el-select
                                    v-model="formAdd.type"
                                    :disabled="isEdit"
                                        style="width: 100%;margin-left: 0%;"
                                    >
                                        <el-option
                                        v-for="item in optionsType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                                  <div style="display: flex;">
                                    
                                  </div>
                                </div>
                                    
                                </el-form-item>
                            </el-col>
                      </el-row>
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="接口地址:" prop="url" style=""> 
                                  <el-input
                                  v-model="formAdd.url"
                                  style="width: 100%;"
                                  placeholder=""
                                  class="input-with-select"
                                  >
                                </el-input>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="请求方式:" prop="" style="">
                                    <el-select
                                    v-model="formAdd.rqtype"
                                    :disabled="isEdit"
                                        style="width: 100%;margin-left: 0%;"
                                    >
                                        <el-option
                                        v-for="item in optionsRqtype"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                      </el-row>
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="所属模型:" prop="mdid" style="">
                                <el-tree-select
                                  v-model="formAdd.mdid"
                                  :data="optionsMdid"
                                  check-strictly
                                  :render-after-expand="false"
                                  style="width: 100%"
                                />
                                <!-- <el-select
                                v-model="formAdd.mdid"
                                    style="width: 100%;margin-left: 0%;"
                                >
                                    <el-option
                                    v-for="item in optionsMdid"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.id"
                                    />
                                </el-select> -->
                      </el-form-item>
                            </el-col>
                      </el-row>
                      <el-form-item label="排序:" prop="dcSort">
                        <el-input-number v-model="formAdd.sort" :min="1" style="width: 15%;"/>
                      </el-form-item>
                      <el-row :gutter="48">
                            <el-col :span="10">
                              <el-form-item label="响应类型:" prop="" style="display: flex; align-items: center;">
                                <el-radio-group v-model="formAdd.rptype" class="ml-4" style="display: inline-flex; align-items: center;">
                                  <el-radio label="1" size="large" style="display: inline-flex; align-items: center;">
                                    <span style="position: relative; top: -1px">JSON</span> <!-- 微调文字位置 -->
                                  </el-radio>
                                  <el-radio label="2" size="large" style="display: inline-flex; align-items: center;">
                                    <span style="position: relative; top: -1px">XML</span>
                                  </el-radio>
                                  <el-radio label="3" size="large" style="display: inline-flex; align-items: center;">
                                    <span style="position: relative; top: -1px">HTML</span>
                                  </el-radio>
                                </el-radio-group>
                              </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="服务分类:" prop="cateCode" style="">
                                    <el-cascader v-model="formAdd.cateCode" :options="cascaderOptions" :props="props1" clearable style="width: 100%;"></el-cascader>
                                </el-form-item>
                            </el-col>
                            <!-- <el-col :span="8">
                                <el-form-item label="请求方式:" prop="name" style="">
                                    <el-select
                                    v-model="formJi.type"
                                    :disabled="isEdit"
                                        style="width: 100%;margin-left: 0%;"
                                    >
                                        <el-option
                                        v-for="item in optionsType"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-col> -->
                      </el-row>
                      <el-row :gutter="48">
                            <el-col :span="13">
                              <el-form-item label="服务说明:">
                                  <el-input v-model="formAdd.intro" style="width: 100%;" :rows="3" resize="none" type="textarea"/>
                              </el-form-item>
                            </el-col>
                      </el-row>
                        
                    </el-form>
                    <div style="margin-top: 2%;">
                        <div style="display: flex;justify-content: space-between;align-items: center;">
                          <div>
                            请求参数
                          </div>
                          <div style="display: flex;justify-content: flex-end;margin-right: 2%;">
                            <el-button  @click="addCanAdd" style="margin-top: 1%;" type="success" size="mini" plain>新增参数</el-button>
                          </div>
                        </div>
                        <div>
                            <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="参数字段">
                                    <template #default="scope">
                                        <div style="width: 100%;">
                                            <el-input placeholder="请填写参数编码" type="primary" class="noBor" v-model="scope.row.parCode" size="mini" text style="margin-left: 0%;border: transparent;"></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.parName" size="mini" text style="margin-left: 0%;"></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="itemName" label="参数类型" width="200">
                                    <template #default="scope">
                                        <div style="width: 100%;">
                                            <el-select
                                            v-model="scope.row.parType"
                                            class="noBorSel"
                                            placeholder=""
                                            style="width: 100%;margin-left: 0%;"
                                            >
                                                <el-option
                                                v-for="item in optionsCan"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value"
                                                />
                                    </el-select>
                                        </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.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.parNote" size="mini" text style="margin-left: 0%;"></el-input>
                                        </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>
                          </div>
                    </div>
                    <div style="margin-top: 2%;">
                        <!-- <div>返回响应</div> -->
                        <div style="color: #909399;margin-left: 8%;margin-top:1%;">此处填写本服务接口响应信息描述</div>
                        <el-tabs type="card" style="margin-top: -2%;width: 98%;">
                            <el-tab-pane label="响应内容">
                                <div style="display: flex; flex-direction: column;">
                                   </div>
                            </el-tab-pane>
                        </el-tabs>
                        <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: 0%;width: 98%;" ></el-input>
                        </div>
                    </div>
                    <div style="margin-top: 2.5%;margin-left: 0%;padding-bottom: 1%;">
                    
                    <el-tabs type="card" style="margin-top: -1.5%;width: 98%;">
                        <el-tab-pane label="使用说明">
                             
                        </el-tab-pane>
                    </el-tabs>
                    <el-input placeholder="请输入示例" :rows="8" type="textarea" v-model="exampleAdd" size="mini" text style="margin-top: -1%;width: 98%;" ></el-input>
                </div>
                </div>
                <template #footer>
                  <span class="dialog-footer">
                    <el-button size="mini" @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="addSer" size="mini">
                      提交
                    </el-button>
                </span>
              </template>
        </el-dialog>
        <el-dialog @close="clearFromLev" title="添加目录" v-model="dialogVisibleLevel" width="30%" destroy-on-close :key="tableKey">
          <el-form size="mini" :key="tableKey" style="margin-top: 1%;width: 90%;"  :model="formLev" label-position="right" ref="formRefLev" label-width="120px" :rules="rulesLev">
            <el-form-item label="名称:" prop="itemName" style="">
              <el-input v-model="formLev.itemName" style="width: 100%;"/>
            </el-form-item>
            <el-form-item label="说明:" prop="itemNotes" style="">
              <el-input v-model="formLev.itemNotes" style="width: 100%;"/>
            </el-form-item>
            <el-form-item label="排序:" prop="itemNo" style="">
              <el-input-number v-model="formLev.itemNo" style="width: 100%;" :min="1" :max="10000" @change="handleChange" />
            </el-form-item>
          </el-form>
          <template #footer>
              <span class="dialog-footer">
                <el-button size="mini" @click="dialogVisibleLevel = false">取消</el-button>
                <el-button type="primary" @click="saveAdd1Level" size="mini" v-if="show1Lev">
                  提交
                </el-button>
                <el-button type="primary" @click="saveAddNextLevel" size="mini" v-if="!show1Lev">
                  提交
                </el-button>
            </span>
          </template>
        </el-dialog>
        <el-dialog @close="clearFromLev" title="添加目录" v-model="dialogVisibleTree" width="55%" destroy-on-close :key="tableKey">
          <el-button  @click="addTreePar" style="margin-top: 1%;" type="success" size="mini" :disabled="isEdit" plain>新增参数</el-button>
          <el-table 
          style="margin-top: 1%;width: 98%;"
          :data="tableDataCanAddTree" 
          :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="参数字段">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-input placeholder="请填写参数编码" type="primary" class="noBor" v-model="scope.row.paramCode" size="mini" text style="margin-left: 0%;border: transparent;"></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.paramName" size="mini" text style="margin-left: 0%;"></el-input>
                      </div>
                  </template>
              </el-table-column>
              <el-table-column prop="itemName" label="参数类型" width="200">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-select
                          v-model="scope.row.paramType"
                          class="noBorSel"
                          placeholder=""
                          style="width: 100%;margin-left: 0%;"
                          >
                              <el-option
                              v-for="item in optionsCan"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                              />
                  </el-select>
                      </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.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="address" label="操作" width="100">
                  <template #default="scope">
                      <div style="width: 100%;">
                          <el-button type="danger" @click="delTreeAdd(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="dialogVisibleTree = false">取消</el-button>
                <el-button type="primary" @click="addToTree" size="mini">
                  确定
                </el-button>
            </span>
          </template>
        </el-dialog>
    </div>
  </div>
</template>
<script   setup>
import {getCatalog} from "@/api/service/catalog";
import { Plus,Search,Filter,Promotion,Check  } from '@element-plus/icons-vue'
import { reactive } from 'vue'
import { modelTreeSelect,getSerDe,addService,addParam,editService,editParam,addServiceParam,delService,getTreeDe,addTree,deTree,getServiceReturn,postReturnlist } from "@/api/service/info";
import { ref, onMounted, onUnmounted, nextTick,onBeforeMount } from 'vue';
import JsonViewer from 'vue-json-viewer'
import 'vue-json-viewer/style.css' 
import  JsonEditorVue from 'json-editor-vue3'
import { cloneDeep } from 'lodash'
import { useClipboard } from "@vueuse/core";

const { proxy } = getCurrentInstance();
const JsonAdd= ref(JSON.stringify({ data: "初始值1" }))
const exampleAdd = ref('')
const dialogVisibleLevel = ref(false)
const dialogVisieTree = ref(false)
const detail = ref({
  name:'',
  rqtype:'',
  rptype:''
})
const tableDataCanAddTree = ref([
])
const dataTreeReturn = ref([
])
const show1Lev = ref(true)
const inputNode =ref('')
const isEdit = ref(true)
const dataReturn = ref({})
const optionsCan = ref([
  {
    label:"string",
    value:'string'
  },
  {
    label:"int",
    value:'int'
  },
  {
    label:"boolean",
    value:'boolean'
  },
  {
    label:"array",
    value:'array'
  },
  {
    label:"object",
    value:'object'
  },
  {
    label:"number",
    value:'number'
  },
  {
    label:"null",
    value:'null'
  },
  {
    label:"any",
    value:'any'
  },
  
])
const parTreeId = ref('')
const parTreeParentId = ref('')
const currentNodeKey = ref('')
const options =  ref([
    {label:'开发中',
    value:'1'
    },
    {label:'运行中',
    value:'2'
    },
])
const dataJsonXiang = ref()
const parTree = ref({})
const valueKet = ref(0)
const tableDataCan = ref([
    {
      paramName:'',
      paramCode:'',
      paramType:'',
      paramNote:''
    }
])
const optionsMdid = ref([])
const optionsRqtype = ref([
    {label:'GET',
    value:'GET'
    },
    {label:'POST',
    value:'POST'
    },
])
const defaultProps = ref({
  children: 'children',
  label: 'paramCode'
})
const optionsType=  ref([
    {label:'RESTful',
    value:'RESTful'
    },
    {label:'WebService',
    value:'WebService'
    },
    {label:'HTTP',
    value:'HTTP'
    },
    {label:'WebSocket',
    value:'WebSocket'
    },
])
const data =  ref([])
const select =  ref('1')
const activeName =  ref('first')
const title =  ref('')
const titleTree =  ref('')
const currentPage =  ref(1)
const total =  ref(1)
const tableData = ref([])
const tableheight = window.innerHeight*0.7
const heightAll = window.innerHeight
const dialogVisible = ref(false)
const dialogVisibleTree = ref(false)
const isAdd = ref(false)
const isAddTa = ref(false)
const treeId = ref('');
const valueSta = ref('1');
const example = ref('');
const tableDataCanAdd = ref([
  {
      itemName:'',
      itemCode:'',
      paramType:'',
      paramNote:''
    }
])
const formZu = ref({
  itemName:'',
  itemTp:'',
  itemEn:'',
  itemTp:'',
  itemDataTp:'',
  itemDefaultVal:'',
  itemUnit:'',
  itemNotes:'',
});
const parId= ref('')
const formJi = ref({
  name:'',
  cateCode:'',
  type:'',
  url:'',
  rqtype:'',
  rptype:'',
  intro:'',
});
const rulesJi = reactive({
  name: [{ required: true, message: '必填', trigger: 'blur' }],
  url: [{ required: true, message: '必填', trigger: 'blur' }],
  cateCode: [{ required: true, message: '必填', trigger: 'blur' }],
});
const byWhich = ref('input');
const formRefJi = ref();
const formAdd = ref({
  name:'',
  cateCode:'',
  type:'',
  url:'',
  rqtype:'',
  rptype:'',
  intro:'',
  mdid:''
});
const rulesAdd = reactive({
  mdid: [{ required: true, message: '必填', trigger: 'blur' }],
  name: [{ required: true, message: '必填', trigger: 'blur' }],
  url: [{ required: true, message: '必填', trigger: 'blur' }],
  cateCode: [{ required: true, message: '必填', trigger: 'blur' }],
});
const formRefAdd = ref();
const treeRef = ref(null);
const formTree = ref({
  itemName:'',
  catePid:'',
  itemNo:'',
  itemNotes:''
});
const rulesTree = reactive({
  itemNo: [{ required: true, message: '必填', trigger: 'blur' }],
  catePid: [{ required: true, message: '必填', trigger: 'blur' }],
  itemName: [{ required: true, message: '必填', trigger: 'blur' }],
});
const formRefTree = ref();
const formLev = ref({
  itemName:'',
  itemNo:'',
  itemNotes:'',
});
const rulesLev = reactive({
  itemNotes: [{ required: true, message: '必填', trigger: 'blur' }],
  itemNo: [{ required: true, message: '必填', trigger: 'blur' }],
  itemName: [{ required: true, message: '必填', trigger: 'blur' }],
});
const formRefLev = ref();
const cascaderOptions = ref([])
const props1 = ref({
  checkStrictly: true,
})
const detailJson = ref([])
const parLev = ref(1)
watch(inputNode, (val) => {
  treeRef.value?.filter(val); // 调用树的过滤方法
});
const filterNode = (value, data) => {
  if (!value) return true; // 空搜索时显示所有节点
  return data.label.includes(value); // 检查节点标签是否包含关键字
};

const copied = ref(false);
function byWay() {
  byWhich.value = 'input'
}
function addToTree() {
  byWhich.value = 'tree'
  if(parLev.value === 1){
    parTreeParentId.value
    if(tableDataCanAddTree.value){
      tableDataCanAddTree.value.forEach(item=>{
        item.parentId = parTreeId.value
        item.srvId = parId.value
        addSiblingNode(dataTreeReturn.value,parTreeId.value,item)
      })
      dialogVisibleTree.value = false
      }
  }
  if(parLev.value === 2){
    tableDataCanAddTree.value.forEach(item=>{
      item.parentId = parTreeId.value
      item.srvId = parId.value
      addChildNode(dataTreeReturn.value,parTreeId.value,item)
    })
    dialogVisibleTree.value = false
  }
  console.log(findNode(dataTreeReturn.value,parTreeParentId.value))
}
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');
  if (!siblingNode) {
    console.warn(`未找到ID为 ${siblingId} 的兄弟节点`);
    return false;
  }
  
  // 2. 找到兄弟节点的父节点（通过parentId查找）
  const parentNode = findNode(treeData, siblingNode.parentId, 'id');
  if (!parentNode) {
    console.warn(`未找到ID为 ${siblingNode.parentId} 的父节点（兄弟节点的父节点）`);
    return false;
  }
  
  // 3. 将新节点添加到父节点的children数组中
  if (!Array.isArray(parentNode.children)) {
    parentNode.children = [];
  }
  parentNode.children.push(newNode);
  return true;
}
function setId(data){
  parTreeId.value = data.id
  parTreeParentId.value = data.parentId
}
function addTreePar(){
  tableDataCanAddTree.value.push({
    id:Math.random()
  })
}
function delTreeAdd(index){
  tableDataCanAddTree.value.splice(index, 1)
}
async function copyUrl(){
  try {
    await navigator.clipboard.writeText(detail.value.url);
    copied.value = true;
    console.log(detail.url.value,copied.value)
    setTimeout(() => (copied.value = false), 2000); // 2秒后提示消失
  } catch (err) {
    console.error("复制失败", err);
  }
};
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 add1LevelTree(){
  dialogVisibleTree.value = true
  parLev.value = 1
}
function addNextLevelTree(){
  dialogVisibleTree.value = true
  parLev.value = 2
}
function clearAdd(){
  dialogVisible.value = false
  formAdd.value = {
    name:'',
    cateCode:'',
    type:'',
    url:'',
    rqtype:'',
    rptype:'',
    intro:'',
    mdid:''
  }
  tableDataCanAdd.value = []
  JsonAdd.value = ''
  exampleAdd.value = ''
}
function delAll(){
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return deTree(parTree.value.id);
  }).then(() => {
    getTreeLeft();
    proxy.$modal.msgSuccess("删除成功");
    dialogVisibleLevel.value = false
  }).catch(() => {});
}
function clearFromLev(){
  formLev.value = {
    itemName:'',
    itemNo:'',
    itemNotes:'',
  }
  tableDataCanAddTree.value = []
}
function addNextLevel(){
  dialogVisibleLevel.value = true
  show1Lev.value = false
}
function saveAddNextLevel(){
   formRefLev.value.validate((valid) => {
    if(valid){
      var par = formLev.value
      par.treeType = parTree.value.nodeType
      par.treePid = parTree.value.id
      addTree(par).then(res=>{
        if(res.code===200){
          proxy.$modal.msgSuccess("新增成功");
          getTreeLeft()
          dialogVisibleLevel.value = false
        }
      })
    }
  });
}
function add1Level(){
  dialogVisibleLevel.value = true
  show1Lev.value = true
}
function saveAdd1Level(){
  formRefLev.value.validate((valid) => {
    if(valid){
      var par = formLev.value
      par.treeType = parTree.value.nodeType
      par.treePid = parTree.value.pid
      addTree(par).then(res=>{
        if(res.code===200){
          proxy.$modal.msgSuccess("新增成功");
          getTreeLeft()
          dialogVisibleLevel.value = false
        }
      })
    }
  });
}
async function delSer(){
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delService(parId.value);
  }).then(() => {
    getTreeLeft();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 辅助函数：根据值获取参数类型
function getParamType(value) {
    if (Array.isArray(value)) {
        return 'Array';
    } else if (value === null) {
        return 'Null';
    } else {
        return typeof value === 'object' ? 'Object' : capitalizeFirstLetter(typeof value);
    }
}

// 辅助函数：首字母大写
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

// 辅助函数：根据参数代码获取参数名称（可根据需要扩展映射关系）
function getParamName(paramCode) {
    const nameMap = {
        'typhoonId': '台风编码',
        'typhoonName': '台风名称',
        'data': '数据体'
        // 可以添加更多映射
    };
    return nameMap[paramCode] || '';
}
async function saveEditService(){
  console.log(JsonAdd.value)
  var valid
  await formRefJi.value.validate((valid1) => {
    valid = valid1
  });
  console.log(valid)
  if(valid){
    console.log()
    var par = formJi.value
    par.example = example.value
    par.rpcontent = dataJsonXiang.value
    par.cateCode = par.cateCode[0]
    var validTable = true
    for (const item of tableDataCan.value) {
      if (item.paramCode.length === 0 || item.paramName.length === 0 || item.paramType.length === 0) {
          proxy.$modal.msgError("请填写必填项！");
          validTable = false
          break;
      }
    }
    if(validTable){
      await editService(par).then(res=>{
        if(res.code===200){
          var parCan = tableDataCan.value
          parCan.forEach(item => {
            item.srvId = parId.value
          });
          addServiceParam(parCan).then(res1=>{
            if(res1.code===200){
              proxy.$modal.msgSuccess("修改成功");
              getTreeLeft()
            }
          })
        }
      })
      // 处理返回值
      if(byWhich.value==='input'){
        var par = JSON.parse(dataJsonXiang.value)
        var par1 = transformDynamicDataToTree(par)
        // par1.length = par1.length - 1
        console.log(par1)
        postReturnlist(par1).then(res=>{
          if(res.code===200){
            proxy.$modal.msgSuccess("新增成功");
            getTreeLeft()
          }
        })
      }
      if(byWhich.value==='tree'){
        var par = JSON.parse(JSON.stringify(dataTreeReturn.value))
        par.forEach((item,index) => {
          if(item.children && item.children.length > 0){
            item = setArry(item)
          }
        });
        par.forEach((item,index) => {
          if(item.children && item.children.length > 0){
            item = setArrayId(item)
          }
        });
        postReturnlist(par).then(res=>{
          if(res.code===200){
            proxy.$modal.msgSuccess("新增成功");
            getTreeLeft()
          }
        })
      }
    }
  }
}
async function addSer(){
  console.log(JsonAdd.value)
  var valid
  await formRefAdd.value.validate((valid1) => {
    valid = valid1
  });
  console.log(valid) 
  if(valid){
    var par = formAdd.value
    par.example = exampleAdd.value
    par.rpcontent = JsonAdd.value
    par.cateCode = par.cateCode[0]
    console.log(par)
    await addService(par).then(res=>{
      if(res.code===200){
        var parCan = tableDataCanAdd.value
        if(parCan.length !== 0){
          parCan.forEach((item,index) => {
            item.srvId = res.data.srvId
            if(item.paramName===''){
              parCan.splice(index, 1)
            }
          });
          addServiceParam(parCan).then(res1=>{
          if(res1.code===200){
              proxy.$modal.msgSuccess("新增成功");
              getTreeLeft()
            }
          })
        }
        
      }
    })
    
    
  }

}
function showAdd(){
  dialogVisible.value = true
}
async function handleNodeClick(node,data,event){
  parTree.value = data.data
  currentNodeKey.value = data.data.id
  isEdit.value = false
  parId.value = data.data.id
  await getSerDe(data.data.id).then(res=>{
    detail.value = res.data.ptService
    tableDataCan.value = res.data.list
    dataJsonXiang.value = res.data.ptService.rpcontent
    formJi.value = res.data.ptService
    example.value = res.data.ptService.example
  })
  detail.value.nodeType = data.data.nodeType
  var par = {
    srvId:data.data.id
  }
  console.log(JSON.parse(dataJsonXiang.value))
  getServiceReturn(par).then(res=>{
    const fullTree = buildTree1(res.data)
    fullTree.forEach((item,index) => {
      if(item.children && item.children.length > 0){
        item = dfsRecursive(item)
      }
    });
    dataTreeReturn.value = fullTree
    console.log(dataTreeReturn.value)
    // var par = JSON.parse(JSON.stringify(fullTree))
    // var par1 = transformDynamicDataToTree(par)
    // par1.length = par1.length - 1
    // par.forEach((item,index) => {
    //   if(item.children && item.children.length > 0){
    //     item = setArry(item)
    //   }
    // });
    // par.forEach((item,index) => {
    //   if(item.children && item.children.length > 0){
    //     item = setArrayId(item)
    //   }
    // });
  })
}
function setArry(node, parent = null, grandParent = null) {
  if (!node) return;
  var par = {
    "id": Math.random(),
    "parentId": Math.random(),
    "srvId": parId.value,
    "paramCode": "[0]",
    "paramName": null,
    "paramType": "object",
    "paramValue": "",
    "paramFormat": null,
    "paramNote": null,
    "isArray": null,
    "children": []
  }
  if(parent && parent.paramType === 'array' && parent.children.length > 0){
    parent.children.push(par)
    parent.children = modifyArray(parent.children)
    parent.children.length = 1
  }
  if(node.children){
      node.children.forEach(child => {
      setArry(child, node, parent);
    });
  }
  return node;
}
function setArrayId(node, parent = null, grandParent = null) {
  if (!node) return;
  console.log(node,parent)
  node.parentId = parent ? parent.id : Math.random();
  if(node.children){
      node.children.forEach(child => {
      setArrayId(child, node, parent);
    });
  }
  return node;
}
function modifyArray(originalArray) {
  // 1. 找到所有 paramCode 为 '[0]' 的对象
  const targetObjects = originalArray.filter(item => item.paramCode === '[0]');
  
  // 检查是否存在符合条件的对象
  if (targetObjects.length === 0) {
    console.log("没有找到 paramCode 为 '[0]' 的对象");
    return originalArray; // 或者根据需求进行其他处理
  }
  
  // 获取最后一个 paramCode 为 '[0]' 的对象
  const lastTargetObject = targetObjects[targetObjects.length - 1]; // [7](@ref)
  
  // 2. 找到所有 paramCode 不为 '[0]' 的对象
  const objectsToAdd = originalArray.filter(item => item.paramCode !== '[0]');
  
  // 3. 确保目标对象的 children 属性存在且为数组
  if (!lastTargetObject.children) {
    lastTargetObject.children = []; // 如果不存在则初始化
  }
  
  objectsToAdd.forEach(obj => {
    lastTargetObject.children.push(obj);
  });
  const newArray = originalArray.filter(item => item.paramCode === '[0]');
  
  // 返回修改后的新数组
  return newArray;
}

function transformDynamicDataToTree(sourceData) {
    let idCounter = 1; // ID计数器，确保每个节点有唯一ID
    const result = []; // 最终返回的结果数组

    // 辅助函数：为对象中的每个属性推断类型
    function inferType(value) {
        if (value === null) return 'null';
        if (Array.isArray(value)) return 'array';
        if (typeof value === 'object') return 'object'; 
        if (typeof value === 'number') {
            // 简单区分整数和浮点数（可根据需要调整）
            return Number.isInteger(value) ? 'int' : 'float';
        }
        if (typeof value === 'boolean') return 'boolean';
        return 'string'; // 默认字符串类型
    }

    // 辅助函数：生成带层级的节点
    function createNode(parentId, paramCode, paramValue, paramType, paramName = null, arrayIndex = null, isArray = null) {
        const node = {
            createBy: null,
            createTime: null,
            updateBy: null,
            updateTime: null,
            remark: null,
            id: idCounter++,
            parentId: parentId,
            srvId: parId.value, // 使用传入的服务ID或示例值
            paramCode: paramCode,
            paramName: paramName, // 可选的友好名称
            paramType: paramType,
            paramValue: paramValue !== null && paramValue !== undefined ? String(paramValue) : '', // 确保值为字符串或空
            paramFormat: null,
            paramNote: null,
            isArray: isArray,
            arrayIndex: arrayIndex,
            sort: idCounter // 简单地用ID作为排序，可根据需要调整
        };
        // 移除可能为null的字段，保持整洁（可选）
        Object.keys(node).forEach(key => {
            if (node[key] === null) {
                delete node[key];
            }
        });
        return node;
    }

    // 1. 处理根级的"data"属性（如果存在且是数组）
    if (sourceData.data && Array.isArray(sourceData.data)) {
        // 创建根节点 (data array)
        const dataRootNode = createNode(0, "data", "", "array", "数据体", null, "1");
        result.push(dataRootNode);
        const dataRootId = dataRootNode.id; // 记录根节点ID

        // 遍历data数组中的每一项
        sourceData.data.forEach((dataItem, dataIndex) => {
            if (typeof dataItem === 'object' && dataItem !== null) {
                // 为数组中的每一项（如台风对象）创建一个节点，其父节点是dataRootId
                const arrayItemNode = createNode(dataRootId, `[${dataIndex}]`, "", "object", null, dataIndex, null);
                result.push(arrayItemNode);
                const arrayItemId = arrayItemNode.id; // 记录当前数组项节点ID

                // 遍历该项的所有属性（如typhoonId, typhoonName）
                for (const [key, value] of Object.entries(dataItem)) {
                    const propNode = createNode(arrayItemId, key, value, inferType(value), null, null, null);
                    result.push(propNode);
                }
            } else {
                // 处理data数组中是非对象的情况（如基本类型）
                const arrayItemNode = createNode(dataRootId, `[${dataIndex}]`, sourceData.data[dataIndex], inferType(sourceData.data[dataIndex]), null, dataIndex, null);
                result.push(arrayItemNode);
            }
        });
    }

    // 2. 处理源数据中的其他根级属性（排除已经处理的data）
    for (const [key, value] of Object.entries(sourceData)) {
        // 跳过已经处理过的data属性、null和undefined，以及非自有属性
        if (key === 'data' || value === null || value === undefined || !sourceData.hasOwnProperty(key)) continue;

        const rootPropNode = createNode(0, key, value, inferType(value), null, null, null);
        result.push(rootPropNode);
    }

    // 3. 特别处理源数据中值为null或undefined的根级属性（如果需要保留这些信息）
    for (const key in sourceData) {
        if (sourceData[key] === null && sourceData.hasOwnProperty(key) && key !== 'data') {
            const nullNode = createNode(0, key, "", "null", null, null, null);
            result.push(nullNode);
        }
    }

    return result;
}

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+\]/;
  if (parent && reg.test(parent.paramCode)) {
    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 getTreeLeft(){
  var par
  await modelTreeSelect().then(res=>{
    par = res.data
    data.value = res.data
  })
  optionsMdid.value = filterModelNodes(par)
  console.log(optionsMdid.value)
}
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 ('cateCode' in node) {
      node.value = node.cateCode;
      delete node.cateCode;
    }

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

  // 遍历根节点
  newTree.forEach(rootNode => processNode(rootNode));
  return newTree;
}
function fetchData() {
  getCatalog().then((r) => {
    cascaderOptions.value = renameTreeProperties(buildTree(r.data))
    console.log(cascaderOptions.value)
  });
}
function buildTree(flatData, rootValue = '0') {
  const nodeMap = new Map();
  const tree = [];
  flatData.forEach(item => {
    nodeMap.set(item.cateCode, { ...item, children: [] });
  });
  for (const [code, node] of nodeMap) {
    const parentCode = node.catePcode;
    if (parentCode === rootValue || !parentCode) {
      tree.push(node);
      continue;
    }
    const parent = nodeMap.get(parentCode);
    if (parent) {
      parent.children.push(node);
    } else {
      console.warn(`Orphan node detected: ${code}. Parent ${parentCode} not found`);
    }
  }

  return tree;
}
function addPa(){
    var par = {
      paramName:'',
      paramNote:'',
      paramType:'',
      paramCode:''
    }
    tableDataCan.value.push(par)
}
function delCan(index){
  tableDataCan.value.splice(index, 1)
}
function addCanAdd(){
    var par = {
        parName:''
    }
    tableDataCanAdd.value.push(par)
}
function delCanAdd(index){
  tableDataCanAdd.value.splice(index, 1)
}
onMounted(() => {
  fetchData()
  getTreeLeft()
});

</script>
<style scoped>

.noBorSel :deep(.el-select__wrapper){
  box-shadow: none !important; /* 去除阴影边框 */
  border: 1px solid transparent !important; /* 设置透明边框 */
  background-color: transparent !important; /* 可选：透明背景 */
}
.noBor :deep(.el-input__wrapper) {
  box-shadow: none !important; /* 去除阴影边框 */
  border: 1px solid transparent !important; /* 设置透明边框 */
  background-color: transparent !important; /* 可选：透明背景 */
}
/* 节点垂直间距 */
:deep(.el-tree-node) {
  margin-bottom:5px !important; /* 增大节点间距 */
}
.el-popover.custom-popover {
  min-width: 50px;
  padding: 8px; /* 可选：调整内边距 */
}
</style>
<style>
.dot {
  width: 20px;          /* 控制圆点直径 */
  height: 20px;
  background-color: #333; /* 实心颜色 */
  border-radius: 50%;    /* 关键属性 */
  display: inline-block; /* 确保与其他元素并排 */
}
/* 全局透明样式（不使用 scoped） */
.transparent-select .el-select__wrapper {
  background-color: transparent !important;
  border-color: transparent !important;
  box-shadow: none !important;
}

.transparent-select .el-select__selection {
  background-color: transparent;
}

/* 处理悬停和聚焦状态 */
.transparent-select .el-select__wrapper:hover,
.transparent-select .el-select__wrapper.is-focused {
  border-color: transparent !important;
  box-shadow: none !important;
}

/* 下拉箭头图标 */
.transparent-select .el-select__caret {
  color: rgba(0, 0, 0, 0.5); /* 半透明图标 */
}
</style>
<style scoped>
:deep(.svg-icon) {
  outline: none;
}
:deep(.svg-icon svg) {
  stroke: none;
}
:deep(.treeLeft) .el-tree-node__content {
  display: flex !important;
  height: 28px;                  /* 按设计稿调整高度 */
  align-items: center;
  padding-top: 0 !important;
}
:deep(.treeLeft) .el-tree-node__content:hover {
  background-color: #e9e9eb;
}
:deep(.treeLeft) .el-tree-node__content:active {
    background-color: rgka(69,157,255,0.1) !important;
  }

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

.tab-container {
  height: 100vh; /* 关键：父容器明确高度 */
  display: flex;
  flex-direction: column;
}
.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">

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