<template>
  <a-card :bordered="false" style="height: 100%">
    <template #extra>
      <!-- <a-space style="margin-bottom: 10px;" size="Small"> -->
      <a-button v-auth="'system:xzCode:add'" type="primary" preIcon="ant-design:plus-outlined" style="margin-right: 10px;"
        @click="handleCreate">新增</a-button>
      <!-- <a-button preIcon="ant-design:edit-outlined" style="margin-right: 10px;"  @click="handleEdit">修改</a-button> -->
      <a-button v-auth="'system:xzCode:refresh'" preIcon="ant-design:redo-outlined" style="margin-right: 10px;" @click="loadRootTreeData">刷新</a-button>
      <a-popconfirm title="确定要删除该条数据吗?" ok-text="确定" cancel-text="取消" @confirm="deleteTree">
        <a-button v-auth="'system:xzCode:delete'" danger preIcon="ant-design:delete-outlined" style="margin-right: 10px;">删除</a-button>
      </a-popconfirm>
      <!-- </a-space> -->
    </template>
    <a-spin :spinning="treeReloading">
      <!-- <a-input-search placeholder="按部门名称搜索…" style="margin-bottom: 10px" @search="onSearch" allowClear /> -->
      <!--组织机构树-->
      <template v-if="treeData.length > 0">
        <a-tree v-if="!treeReloading" showLine :clickRowToExpand="false" :treeData="treeData" :selectedKeys="selectedKeys"
          :load-data="loadChildrenTreeData" v-model:expandedKeys="expandedKeys" @select="onSelect"
          :field-names="{ children: 'children', title: 'name', key: 'id' }"></a-tree>
      </template>
      <a-empty v-else description="暂无数据" />
    </a-spin>
  </a-card>
  <!-- 新增表单 -->
  <Modal @register="register" @success="handleSuccess" />
</template>

<script lang="ts" setup>
import { inject, nextTick, ref, unref, defineExpose } from 'vue';
import { treeXzbm, treePidXzbm, addXzbm, editXzbm, delXzbm } from '../address.api';
import { searchByKeywords } from '/@/views/system/departUser/depart.user.api';
import { Popconfirm } from 'ant-design-vue';
import Modal from './modal.vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { useModal } from '/@/components/Modal';
const [register, { openModal }] = useModal();
const { createMessage } = useMessage();

const prefixCls = inject('prefixCls');
const emit = defineEmits(['select', 'rootTreeData', 'successTree']);

const loading = ref<boolean>(false);
// 部门树列表数据
const treeData = ref<any[]>([]);
// 当前展开的项
const expandedKeys = ref<any[]>([]);
// 当前选中的项
const selectedKeys = ref<any[]>([]);
// 树组件重新加载
const treeReloading = ref<boolean>(false);
// 当前选中的部门
const currentDepart = ref<any>(null);
// 搜索关键字
const searchKeyword = ref('');
/**
 * 新增事件
 */
function handleCreate() {
  openModal(true, {
    record: {
      pid: treeData.value[0]?.id,
    },
    isUpdate: false,
  });
}

/**
 * 编辑事件
 */
async function handleEdit(record) {
  if (selectedKeys.value.length == 0) {
    createMessage.info('请选择要修改的数据');
    return
  }
  console.log(currentDepart.value);
  openModal(true, {
    record: currentDepart.value,
    isUpdate: true,
  });
}
async function deleteTree() {
  console.log(selectedKeys.value);
  console.log(selectedKeys.value.length);
  if (selectedKeys.value.length !== 1) {
    createMessage.info('请选择需要处理的内容，每次只能选中一条');
  } else {
    await delXzbm({ id: selectedKeys.value[0] });
    loadRootTreeData()
  }
}
// 加载顶级部门信息
async function loadRootTreeData() {
  try {
    loading.value = true;
    treeData.value = [];
    const result = await treeXzbm();
    // console.log(result);
    if (Array.isArray(result)) {
      treeData.value = result;
    }
    if (expandedKeys.value.length === 0) {
      autoExpandParentNode();
    }
  } finally {
    loading.value = false
    emit('successTree', loading.value)

  }
}

loadRootTreeData();
// 加载子级部门信息
async function loadChildrenTreeData(treeNode) {
  try {
    const result = await treePidXzbm({
      pid: treeNode.dataRef.id,
    });
    if (result.length == 0) {
      treeNode.dataRef.isLeaf = true;
    } else {
      treeNode.dataRef.children = result;
      if (expandedKeys.value.length > 0) {
        // 判断获取的子级是否有当前展开的项
        let subKeys: any[] = [];
        for (let key of expandedKeys.value) {
          if (result.findIndex((item) => item.id === key) !== -1) {
            subKeys.push(key);
          }
        }
        if (subKeys.length > 0) {
          expandedKeys.value = [...expandedKeys.value];
        }
      }
    }
    treeData.value = [...treeData.value];
  } catch (e) {
    console.error(e);
  }
  return Promise.resolve();
}

// 自动展开父节点，只展开一级
function autoExpandParentNode() {
  let item = treeData.value[0];
  if (item) {
    if (!item.isLeaf) {
      expandedKeys.value = [item.key];
    }
    reloadTree();
  }
}
function handleSuccess(values) {
  loadRootTreeData()
}
// 重新加载树组件，防止无法默认展开数据
async function reloadTree() {
  await nextTick();
  treeReloading.value = true;
  await nextTick();
  treeReloading.value = false;
}

/**
 * 设置当前选中的行
 */
function setSelectedKey(key: string, data?: object) {
  selectedKeys.value = [key];
  if (data) {
    currentDepart.value = data;
    emit('select', data);
  }
}

// 搜索事件
async function onSearch(value: string) {
  if (value) {
    try {
      loading.value = true;
      treeData.value = [];
      let result = await searchByKeywords({ keyWord: value });
      if (Array.isArray(result)) {
        treeData.value = result;
      }
      autoExpandParentNode();
    } finally {
      loading.value = false;
    }
  } else {
    loadRootTreeData();
  }
  searchKeyword.value = value;
}

// 树选择事件
function onSelect(selKeys, event) {
  if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
    setSelectedKey(selKeys[0], event.selectedNodes[0]);
  } else {
    // 这样可以防止用户取消选择
    setSelectedKey(selectedKeys.value[0]);
  }
}

defineExpose({
  loadRootTreeData,
});
</script>
