<template>
  <div class="struct-manage h-full">
    <div v-if="perm.BUTTON_Add" class="page-action page-header">
      <t-button theme="primary" @click="handleAdd">
        <template #icon><svg-icon name="add-circle" color="#fff" /></template>
        新增管理节点
      </t-button>
    </div>

    <div class="flex-1 page-wrap">
      <t-enhanced-table
        ref="tableRef"
        v-model:expandedTreeNodes="expandedTreeNodes"
        row-key="id"
        :data="treeTableData"
        :columns="columns"
        :tree="treeConfig"
        :tree-expand-and-fold-icon="treeIcon"
        bordered
      >
        <template #isRoot="{ col, row }">
          {{ row[col.colKey] ? '根节点' : '子节点' }}
        </template>
        <template #enable="{ col, row }">
          <status-tag :value="row[col.colKey]" type="enable"></status-tag>
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.BUTTON_Add"
              theme="primary"
              hover="color"
              @click="handleAdd(row)"
            >
              新增
            </t-link>
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
            <t-link
              v-if="perm.LINK_Enable"
              theme="primary"
              hover="color"
              @click="handleEnable(row)"
            >
              {{ enableFilter(!row.enable) }}
            </t-link>
          </div>
        </template>
      </t-enhanced-table>

      <!-- <t-table
        size="small"
        row-key="id"
        :columns="columns"
        :data="tableData"
        bordered
        v-loading="tableLoading"
      >
        <template #isRoot="{ col, row }">
          {{ row[col.colKey] ? '根节点' : '子节点' }}
        </template>
        <template #enable="{ col, row }">
          <status-tag :value="row[col.colKey]" type="enable"></status-tag>
        </template>
        <template #operate="{ row }">
          <div class="table-operations">
            <t-link
              v-if="perm.BUTTON_Add"
              theme="primary"
              hover="color"
              @click="handleAdd(row)"
            >
              新增
            </t-link>
            <t-link
              v-if="perm.LINK_Update"
              theme="primary"
              hover="color"
              @click="handleEdit(row)"
            >
              修改
            </t-link>
            <t-link
              v-if="perm.LINK_Enable"
              theme="primary"
              hover="color"
              @click="handleEnable(row)"
            >
              {{ enableFilter(!row.enable) }}
            </t-link>
          </div>
        </template>
      </t-table> -->
    </div>

    <AddNodeDialog
      v-if="perm.BUTTON_Add || perm.LINK_Update"
      v-model:visible="showAddNodeDialog"
      :curRow="curRow"
      :orgTreeList="tableData || []"
      @success="run"
    ></AddNodeDialog>
  </div>
</template>

<script setup lang="jsx" name="StructManage">
import { computed, ref, reactive, nextTick } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { useRequest } from 'vue-request';
import { getOrgStructList, toggleOrgNodeStatus } from '@/api/user';
import AddNodeDialog from './add-node-dialog.vue';
import { enableFilter } from '@/utils/filter';
import { omit } from 'lodash';
import usePermission from '@/hooks/usePermission';
import { ChevronRightIcon, ChevronDownIcon } from 'tdesign-icons-vue-next';
const { perm } = usePermission();
const showAddNodeDialog = ref(false);
const curRow = ref({});
const tableRef = ref();
const treeConfig = reactive({
  treeNodeColumnIndex: 0,
  indent: 25,
  expandTreeNodeOnClick: true,
  defaultExpandAll: true,
});
const treeIcon = (h, { type, row }) => {
  return type === 'expand' ? <ChevronRightIcon /> : <ChevronDownIcon />;
};
const expandedTreeNodes = ref([]);
const columns = [
  { colKey: 'name', title: '管理节点' },
  { colKey: 'isRoot', title: '类型', width: 100 },
  { colKey: 'parentName', title: '父节点' },
  { colKey: 'enable', title: '状态', width: 120 },
  {
    title: '管理',
    colKey: 'operate',
    fixed: 'right',
    width: 160,
  },
];

const {
  data: orgData,
  loading: tableLoading,
  runAsync: run,
} = useRequest(getOrgStructList);
run().then(() => {
  nextTick(() => {
    tableRef.value?.expandAll();
  });
});

const tableData = computed(() => {
  let orgList = [];
  const getData = (list, parent) => {
    list.forEach((item) => {
      orgList.push({
        ...omit(item, ['children']),
        ...(parent || { parentName: '-' }),
        isRoot: !parent,
      });

      if (item.children && item.children.length) {
        getData(item.children, { parentId: item.id, parentName: item.name });
      }
    });
  };
  getData(orgData.value || []);

  return orgList;
});
const setParentName = (list = [], name, isLevel1 = false) => {
  let arr = list.map((item) => {
    if (isLevel1) {
      item.parentName = '-';
    } else {
      item.parentName = name;
    }
    item.children = setParentName(item.children, item.name, false);
    return item;
  });
  return arr;
};
const treeTableData = computed(() => {
  return setParentName(orgData.value || [], '-', true);
});

const handleAdd = (row = null) => {
  if (row) {
    curRow.value = {
      parentId: row.id,
      parentName: row.name,
    };
  } else {
    curRow.value = { parentId: '', parentName: '' };
  }
  showAddNodeDialog.value = true;
};
const handleEdit = (row) => {
  curRow.value = row;
  showAddNodeDialog.value = true;
};

const handleEnable = async (row) => {
  const res = await toggleOrgNodeStatus({
    id: row.id,
    enable: !row.enable,
  }).catch(() => {});

  if (!res) return;
  MessagePlugin.success('操作成功');
  run();
};

const handleDelete = (row) => {
  console.log(row);
};
</script>
