<template>
  <a-card :bordered="false" style="height: 100%">
    <div class="j-table-operator" style="width: 100%">
<!--      <a-button preIcon="ant-design:sync-outlined" @click="loadRootTreeData">刷新</a-button>-->
      <a-button type="primary" preIcon="ant-design:sync-outlined" @click="syncProjectInfo">同步项目</a-button>
      <template v-if="currentRegion !=null">
        <a-button preIcon="ant-design:sync-outlined" @click="syncRegionInfo">同步区域</a-button>
      </template>
    </div>
    <a-spin :spinning="loading">
      <!--区域树-->
      <template v-if="treeData.length > 0">
        <a-tree
          v-if="!treeReloading"
          :clickRowToExpand="false"
          :treeData="treeData"
          :selectedKeys="selectedKeys"
          :checkStrictly="checkStrictly"
          :load-data="loadChildrenTreeData"
          :checkedKeys="checkedKeys"
          v-model:expandedKeys="expandedKeys"
          @select="onSelect"
        >
        </a-tree>
      </template>
      <a-empty v-else description="暂无数据" />
    </a-spin>
  </a-card>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useMethods } from '/@/hooks/system/useMethods';
  const { createMessage } = useMessage();
  import { queryProjectTreeSync, queryRegionTreeSync, syncProject, syncRegion } from '@/views/iot/tplink/camera/camera.api';

  const emit = defineEmits(['select', 'rootTreeData']);
  const loading = ref<boolean>(false);
  // 区域树列表数据
  const treeData = ref<any[]>([]);
  // 当前选中的项
  const checkedKeys = ref<any[]>([]);
  // 当前展开的项
  const expandedKeys = ref<any[]>([]);
  // 当前选中的项
  const selectedKeys = ref<any[]>([]);
  // 树组件重新加载
  const treeReloading = ref<boolean>(false);
  // 树父子是否关联
  const checkStrictly = ref<boolean>(true);
  // 当前选中的区域
  const currentRegion = ref<any>(null);

  // 加载顶级区域信息
  async function loadRootTreeData() {
    try {
      loading.value = true;
      treeData.value = [];
      const result = await queryProjectTreeSync();
      if (Array.isArray(result)) {
        treeData.value = result;
      }
      if (expandedKeys.value.length === 0) {
        autoExpandParentNode();
      } else {
        if (selectedKeys.value.length === 0) {
          let item = treeData.value[0];
          if (item) {
            // 默认选中第一个
            setSelectedKey(item.id, item);
          }
        } else {
          emit('select', currentRegion.value);
        }
      }
      emit('rootTreeData', treeData.value);
    } finally {
      loading.value = false;
    }
  }

  loadRootTreeData();

  /**
   * 加载子级区域信息
   */
  async function loadChildrenTreeData(treeNode) {
    try {
      const result = await queryRegionTreeSync({
        parentId: treeNode.dataRef.id,
        projectId: treeNode.dataRef.projectId,
      });
      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];
      emit('rootTreeData', 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];
      }
      // 默认选中第一个
      setSelectedKey(item.id, item);
      reloadTree();
    } else {
      emit('select', null);
    }
  }

  /**
   * 重新加载树组件，防止无法默认展开数据
   */
  async function reloadTree() {
    await nextTick();
    treeReloading.value = true;
    await nextTick();
    treeReloading.value = false;
  }

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

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

  /**
   * 同步项目
   */
  async function syncProjectInfo(){
    await syncProject();
    await loadRootTreeData();
  }

  /**
   * 同步区域
   */
  async function syncRegionInfo(){
    let data = currentRegion.value;
    if (data == null) {
      createMessage.warning('请先选择一个区域');
      return;
    }
    const record = { projectId: data.projectId };
    await syncRegion(record);
    await loadRootTreeData();
  }

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

<style lang="less" scoped>

  :deep(.ant-card-body){
    padding: 24px 0px 0px 24px;
  }

</style>
