<template>
  <div class="app-container">
    <!-- 上层输入框 -->
    <DynamicForm :formItems="formItems" @query="queryTree" @reset="resetForm" />
    <!-- 上层按钮 -->
    <DynamicButtonGroup :buttons="buttons" />
    <!-- 中间渲染 -->
    <!--  -->
    <el-table v-loading="loading" :data="tableList" ref="tableRef" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="树形表主键" align="center" prop="treeTablePrimaryKey" />
      <el-table-column label="树形表名" align="center" prop="treeTableName" />
      <el-table-column label="树形表格别名" align="center" prop="treeDesc" />
      <el-table-column label="树形递归列" align="center" prop="treeTableDgl" />
      <el-table-column label="树形条件" align="center" prop="treeTableCondition" />
      <el-table-column label="绑定表名称" align="center" prop="tableNameDes" />
      <el-table-column label="绑定表id" align="center" prop="tableId" />
      <!-- <el-table-column label="表格描述" align="center" prop="dtNotes" />
      <el-table-column label="时间格式" align="center" prop="timeFormat" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" plain size="small">
              处理<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                </el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
  </div>
</template>
<script>
import DynamicForm from './components/DynamicForm.vue';
import DynamicButtonGroup from './components/DynamicButtonGroup.vue';
import { listTreeTable, removeTreeTable } from "@/api/treeTable/tableList";
import { delMenu } from "@/api/system/menu";

// import Treeselect from "@riophae/vue-treeselect";

// import { delForm, addForm, updateForm, listForm } from "@/api/treeTable/form";
// import { getMenuList, addMenu, getRouters } from "@/api/menu.js";
// import {addGroup, listGroup, getTable, delGroup, updataGroup } from "@/api/relateTable/index.js";
export default {
  name: "TreeTable",
  components: {
    DynamicForm,
    DynamicButtonGroup,
  },
  data() {
    return {
      // 总条数
      total: 0,
      //输入框配置
      formItems: [{
        label: '树形表名',
        prop: 'treeTableName',
        attrs: {
          placeholder: '请输入树形表名',
          clearable: true,
        },
      },{
        label: '表格别名',
        prop: 'treeDesc',
        attrs: {
          placeholder: '请输入树形表格别名',
          clearable: true,
        },
      }],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      //标记，2增加3修改4查看
      mode: 4,
      // 遮罩层
      loading: true,
      tableList: [],
      // 选中数组(包含所有数据)
      selection: [],
      // 多选框勾选数据
      tempSelection: [],
      // 查询参数
      queryParams: {
        treeTableName: '',
        pageNum: 1,
        pageSize: 10,

      },
    };
  },
  created() {
    this.getList();

  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.getList(); // 当导航被确认后，调用 getList 方法
    });
  },
  computed: {
    buttons() {
      return [
        {
          label: '新增',
          type: 'primary',
          plain: true,
          icon: 'el-icon-plus',
          size: 'mini',
          click: this.handleAdd,
        },
        {
          label: '修改',
          type: 'success',
          plain: true,
          icon: 'el-icon-edit',
          size: 'mini',
          disabled: this.single,
          click: this.handleUpdate,
        },
        {
          label: '删除',
          type: 'danger',
          plain: true,
          icon: 'el-icon-delete',
          size: 'mini',
          disabled: this.multiple,
          click: this.handleBatchDelete,
        }
      ];
    }
  },
  methods: {
    getList() {
      this.loading = true;
      this.tempSelection = JSON.parse(JSON.stringify(this.selection));
      // 
      listTreeTable(this.queryParams).then((response) => {
        console.log('response', response)
        // response.rows = response.rows.filter(
        //   (item) => !this.tempSelection.find((val) => val.tId == item.tId)
        // );
        // this.tableList = [...this.tempSelection, ...response.rows];
        this.tableList = response.rows;
        this.total = response.total;
        this.loading = false;
        // if (this.tempSelection.length) {
        //   this.$nextTick(() => {
        //     this.tempSelection.forEach((item) => {
        //       this.$refs.tableRef.toggleRowSelection(item);
        //     });
        //   });
        // }
      });
    },
    /* 输入框查询 */
    queryTree(queryParams) {
      this.queryParams = queryParams
      console.log('[输入框查询]', this.queryParams)
      this.getList()
    },
    /* 输入框重置 */
    resetForm() {
      console.log('输入框已重置');
    },
    // 选择多条
    handleSelectionChange(selection) {
      this.selection = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /* ---------按钮事件start---------*/
    // 新增
    handleAdd() {
      console.log('新增按钮被点击');
      this.mode = 2
      this.$router.push({
        path: "/system/fromModel/index/treeTableMange",
        query: {
          mode: this.mode // mode
        }
      });
    },
    // 修改 
    handleUpdate(rowData) {
      let row;
      if (rowData instanceof PointerEvent || rowData instanceof Event) {
        row = this.selection[0]
      } else {
        row = rowData
      }
      if(row){
        this.mode = 3
      this.$router.push({
        path: "/system/fromModel/index/treeTableMange",
        query: {
          mode: this.mode, // mode
          editorId: row.id,
          editorTableId: Number(row.tableId),
          treeTableKey: row.treeTableKey,
        }
      });
      }
     
    },
    // 删除
    handleDelete(row) {
      console.log('删除按钮被点击', row.id, row);
      this.$modal
        .confirm(
          '是否确认删除编号为"' +
          row.id +
          '"的数据项？删除后菜单中相关数据也将删除!'
        )
        .then(async () => {
          let res = await delMenu(row.menuId);
          if (res.code == 200) {
            await removeTreeTable(row.id);
          } else {
            return Promise.reject(new Error('删除菜单失败'));
          }
        }
        ).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch((e) => {
          console.log(e);
        });
    },
    /* ---------按钮事件end---------*/
    // 删除多条
    handleBatchDelete() {
      if (this.selection.length === 0) {
        this.$message.warning('请先选择要删除的记录');
        return;
      }
      let str = this.selection.map(item => item.id).join(',');
      let strList = this.selection.map(item => item.id)
      let menuIds = this.tableList
        .filter(tableItem => this.selection.some(selectionItem => selectionItem.id === tableItem.id))
        .map(tableItem => tableItem.menuId);
      console.log('menuIds', menuIds)
      this.$modal
        .confirm(
          '是否确认删除编号为"' +
          str +
          '"的数据项？删除后菜单中相关数据也将删除!'
        )
        .then(async () => {
          let res = await delMenu(menuIds);
          if (res.code == 200) {
            for (let item of strList) { // 使用 for...of 循环
              try {
                await removeTreeTable(item);
              } catch (error) {
                console.error('删除过程中出现错误:', error);
                return Promise.reject(error); // 错误发生时抛出异常
              }
            }
          } else {
            return Promise.reject(new Error('删除菜单失败'));
          }
        }
        ).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch((e) => {
          console.log(e);
        });
    },
  },
};
</script>
<style scoped>
.tree_table_context {
  display: flex;

  height: 100%
}

.tree_table_left {
  flex: 35%;
}

.tree_table_right {
  flex: 65%;
}
</style>
