<template>
  <el-row class="app-container" style="width: 100%;height: 100%;">
    <el-col :span="4" style="height: 100%">
      <el-card style="height: 100%;overflow: auto;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"
                 :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>
          <template #default="{ node, data }">
            <span style="justify-content: space-between;display: flex;width: 20%;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'"/>
              </div>
              <span style="font-size: 1rem;">{{ node.label }}</span>
              <!--              <div style="margin-left: auto;position: absolute;left:90%;">-->
              <!--                <el-dropdown trigger="hover" @click.stop v-if="currentNodeKey === data.id">-->
              <!--                    &lt;!&ndash; <el-icon class="el-icon&#45;&#45;right" style="color: black;">-->
              <!--                      <plus />-->
              <!--                    </el-icon> &ndash;&gt;-->
              <!--                    <svg-icon icon-class="zhankai"/>-->
              <!--                  <template #dropdown>-->
              <!--                    <el-dropdown-menu>-->
              <!--                      <el-dropdown-item style="display: flex;" @click="add1Level">-->
              <!--                        <el-icon class="el-icon&#45;&#45;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&#45;&#45;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&#45;&#45;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>
    </el-col>
    <el-col :span="20" style="height: 100%">
      <div style="height: 40px;display: flex;justify-content: space-between;align-items: center;">
        <div style="display: flex;align-items: center;">
          <template v-for="(param, index) in params" :key="index">
            <div style="margin-right: 5px;display: flex;align-items: center;">
              <div style="margin-right: 5px;">{{ param.key }}</div>
              <el-input v-model="param.value"></el-input>
            </div>
          </template>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
        </div>
        <el-button @click="handleEdit">编辑配置</el-button>
      </div>
      <div style="height: calc(100% - 40px);">
        <biz-display ref="bizDisplayRef" source="DATA_SET" :config="dataSetConfig"></biz-display>
      </div>
    </el-col>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" destroy-on-close>
      <el-form :model="form" label-position="right" ref="formRef" label-width="120px" :rules="rules">
        <el-form-item label="数据集中文名:" prop="dcName" style="">
          <el-input v-model="form.dcName" style="width: 75%;" placeholder="" resize="none"/>
        </el-form-item>
        <el-form-item label="数据集说明:" prop="dcNote" style="">
          <el-input v-model="form.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="form.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="form.dcSort" :min="1" style="width: 50%;"/>
        </el-form-item>
        <el-form-item label="请求数据" style="max-height: 300px;">
          <div style="width: 100%;height: 100%;background-color: #FAFAFA;overflow: auto;border-radius: 10px;">
            <biz-data-show-config-api v-model="form.queryOptions"></biz-data-show-config-api>
          </div>
        </el-form-item>
        <el-form-item label="展示类型">
          <div
              style="width:100%;max-height: 300px;overflow: auto;background-color: #FAFAFA;border-radius: 10px;padding: 10px;">
            <biz-data-show-config-list :columns="columns"
                                       v-model="form.renderingOptions"></biz-data-show-config-list>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>
  </el-row>
</template>
<script setup>
import {nextTick, onMounted, ref} from 'vue'
import {modelTreeSelect} from "@/api/service/info";
import {dataSetTree, editSet, getDataSourceList, getSetById} from "@/api/register/regCom.js";
import {cloneDeep} from 'lodash'
import BizDataShowConfigApi from "@/views/standardization/bizDataShowConfig/api/index.vue";
import BizDataShowConfigList from "@/views/standardization/bizDataShowConfig/list/index.vue";
import BizDisplay from "@/views/standardization/bizDataShowConfig/show/index.vue";

const total = ref(0)

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = ref({})
const rules = ref({})
const columns = ref([])
const bizDisplayRef = ref(null)
const dataSetConfig = ref(null)
const params = ref({})

const optionsShuLei = ref([
  {
    label: "SQL数据集",
    value: 'SQL'
  },
  {
    label: "API数据集",
    value: 'API'
  },
  {
    label: "文件数据集",
    value: 'FILE'
  },
])
const valueNode = ref('')
const {proxy} = getCurrentInstance();
const data = ref([])
const dialogVisibleData = ref(false)

const parTree = ref(null)
const byNode = ref(false)
const optionsDs = ref([])
const currentNodeKey = ref('')
const dataSel = ref([])
const parAr = ref([])

function handleEdit() {
  getSetById(parTree.value.id).then(res => {
    form.value = res.data.dataSet
  })
  dialogTitle.value = `编辑【${parTree.value.label}】`
  dialogVisible.value = true
}

function submit() {
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      editSet(form.value).then(response => {
        proxy.$modal.msgSuccess("修改成功");
      });
    }
  });
}

function close() {
  form.value = {}
  dialogTitle.value = ''
  dialogVisible.value = false
}

function addDir() {
  byNode.value = true
  valueNode.value = data.value[0].value
  dialogVisibleData.value = true
}

async function getTreeSel() {
  await modelTreeSelect().then(res => {
    dataSel.value = renameTreeProperties(res.data)
    console.log(dataSel.value)
  })
}

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
  })
}

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 getTree() {
  dataSetTree().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 handleNodeClick(node, data) {
  currentNodeKey.value = data.data.id
  parTree.value = data.data

  getSetById(data.data.id).then(res => {
    nextTick(() => {
      let data = res.data.dataSet
      data.id = data.dcCode
      dataSetConfig.value = 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;
}

function handleQuery() {

}


onMounted(() => {
  getTree()
  getOptionsDs()
  getTreeSel()
  // getTable()
});

watch(() => form.value.queryOptions, queryOptions => {
  if (queryOptions) {
    const api = JSON.parse(queryOptions)
    columns.value = api.response
  }
}, {immediate: true, deep: true})

watch(() => dataSetConfig.value, config => {
  const queryOptions = JSON.parse(config.queryOptions)
  const param = [...queryOptions.params, ...queryOptions.body]
  debugger
  params.value = param
}, {deep: true})
</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>