<template>
  <el-row class="full-height">
    <!-- 左侧树 -->
    <el-col :span="5" class="left-panel">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree
              :option="treeOption"
              :data="treeData"
              @node-click="nodeClick"
            />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>

    <!-- 右侧表格 -->
    <el-col :span="19" class="right-panel">
      <basic-container class="right-basic">
        <avue-crud
          :option="option"
          v-model="form"
          :search.sync="search"
          :data="data"
          :table-loading="loading"
          ref="crud"
          @search-change="searchChange"
          @search-reset="searchReset"
          @refresh-change="refreshChange"
        >
          <!-- 自定义操作列 -->
          <template #operate="{ row }">
            <el-button type="primary" size="mini" plain @click="shareRow(row)">
              <i class="el-icon-share"></i>分享
            </el-button>
          </template>
        </avue-crud>
      </basic-container>
    </el-col>
  </el-row>

  <Share
    v-if="shareDialogVisible"
    :rowData="shareRowData"
    title="分享接口"
    :width="1000"
    :height="1000"
    @closeDialog="shareDialogVisible = false"
  />
</template>

<script>
import Share from "./share1.vue";
import { getLeftTreeListAPI, getListDataSetAPI } from "@/api/data-collect/file-share-manage";

export default {
  name: "DataSetManage",
  components: {
    Share
  },
  data() {
    return {
      loading: false,
      form: {},
      search: { keyword: "" },
      data: [],
      rawData: [],
      option: {
        height: "calc(100vh - 280px)",
        border: true,
        index: true,
        tip: false,
        searchShow: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        viewBtn: false,
        selection: false,
        columnBtn: true, // 禁止 Avue 自动生成操作列
        menu: false, // 禁止 Avue 自动生成菜单列
        searchMenuSpan: 6, // 搜索表单每项占据的栅格数
        column: [
          {
            label: "请输入名称",
            prop: "keyword",
            search: true,
            type: "input",
            placeholder: "请输入名称",
            hide: true,
            searchLabelWidth: 100, // 设置标签固定宽度
          }
        ]
      },

      treeDeptId: "0",
      treeData: [],
      treeOption: {
        nodeKey: "id",
        menu: false,
        addBtn: false,
        props: { label: "title", children: "children" }
      },

      shareDialogVisible: false,
      shareRowData: null,
    };
  },

  mounted() {
    this.loadFullTree();
    this.loadDatasetNoPaging();
  },

  methods: {
    // 加载左侧树
    loadFullTree() {
      getLeftTreeListAPI(0)
        .then(res => {
          const rows = res.data.rows || [];
          const formatted = rows.map(item => ({
            id: item.code,
            title: item.name,
            children: (item.kyDataClassifyList || []).map(c => ({
              id: c.id.toString(),
              title: c.dataTypeName
            }))
          }));
          this.treeData = [
            { id: "-1", title: "数据汇集管理", children: formatted }
          ];
        })
        .catch(err => {
          console.error("加载左树失败", err);
          this.treeData = [];
        });
    },

    nodeClick(node) {
      this.treeDeptId = node.id;
      this.loadDatasetNoPaging();
    },

    // 加载右侧表格数据
    async loadDatasetNoPaging() {
      this.loading = true;
      try {
        const res = await getListDataSetAPI(this.treeDeptId);
        const row = res.data?.rows?.[0];
        let arr = [];

        if (!row || !row.dataJson) {
          this.setColumnsEmpty();
          this.rawData = [];
          this.data = [];
          return;
        }

        try {
          arr = JSON.parse(row.dataJson);
        } catch {
          arr = JSON.parse(row.dataJson.replace(/\r\n/g, "").replace(/\n/g, ""));
        }

        if (!Array.isArray(arr) || arr.length < 1) {
          this.setColumnsEmpty();
          this.rawData = [];
          this.data = [];
          return;
        }

        const header = arr[0];
        const content = arr.slice(1);

        const columns = Object.keys(header)
          .filter(k => k !== "id")
          .map(k => ({
            label: header[k],
            prop: k,
            minWidth: 140,
            showOverflowTooltip: true,
            overHidden: true
          }));

        // 最终列配置：搜索列 + 数据列 + 自定义操作列
        this.option.column = [
          this.option.column[0], // 搜索列
          ...columns,
          {
            label: "操作",
            prop: "operate",
            width: 100,
            fixed: "right",
            type: "slot"
          }
        ];

        this.rawData = content;
        this.data = [...content];
      } catch (err) {
        console.error("加载数据失败", err);
        this.setColumnsEmpty();
        this.rawData = [];
        this.data = [];
      } finally {
        this.loading = false;
      }
    },

    // 没有数据时列配置：搜索列 + 自定义操作列
    setColumnsEmpty() {
      this.option.column = [
        this.option.column[0],
        {
          label: "操作",
          prop: "operate",
          width: 100,
          fixed: "right",
          type: "slot"
        }
      ];
    },

    searchChange(params, done) {
      const keyword = (params.keyword || "").toString().trim().toLowerCase();
      if (!keyword) {
        this.data = [...this.rawData];
        done && done();
        return;
      }
      this.data = this.rawData.filter(row =>
        Object.keys(row).some(k => k !== "id" && String(row[k] || "").toLowerCase().includes(keyword))
      );
      done && done();
    },

    searchReset() {
      this.search.keyword = "";
      this.data = [...this.rawData];
    },

    refreshChange() {
      this.data = [...this.rawData];
    },

    shareRow(row) {
      this.shareRowData = row;
      this.shareDialogVisible = true; // 打开弹窗

    }
  }
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}
</style>
