<template>
  <div class="comp-content">
    <div class="content">
      <DragSplit :hideLeft="hideTree" :leftContentWidth="400">
        <template #left>
          <div class="left-content">
            <div class="options">
              <slot name="options" />
            </div>
            <div class="tree-data">
              <el-tree
                v-if="visible"
                v-loading="loading"
                ref="treeRef"
                node-key="id"
                highlight-current
                :load="loadMoreFun"
                lazy
                :props="{
                  label: 'originalName',
                  children: 'children',
                  isLeaf: 'leaf',
                }"
                v-bind="$attrs"
                :current-node-key="currentKey"
                :default-expanded-keys="expandedKeys"
                @node-click="nodeClickFun"
                @current-change="currentChangeFun"
              >
                <template #default="{ data, node }">
                  <div class="tree-item">
                    <div class="icon">
                      <el-icon :size="18">
                        <MessageBox v-if="data.relatedResourceUuidOwnType === NODE_TYPE.PROJECT" />
                        <Share v-else-if="data.relatedResourceUuidOwnType === NODE_TYPE.PHASE" />
                        <Document v-else-if="data.relatedResourceUuidOwnType === NODE_TYPE.TASK" />
                        <Folder v-else />
                      </el-icon>
                    </div>
                    <div class="label" :title="data.originalName">{{ data.originalName }}</div>
                    <div class="actions">
                      <slot name="treeAction" :data="data" :node="node" />
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>
          </div>
        </template>
        <template #right>
          <div class="right-content">
            <div class="top-content">
              <div class="menu">
                <el-breadcrumb separator="/">
                  <el-breadcrumb-item @click="openDirFun(0)">
                    <span class="bread-item">根目录</span>
                  </el-breadcrumb-item>
                  <el-breadcrumb-item
                    v-for="item in navList"
                    :key="item.id"
                    @click="openDirFun(item.id)"
                  >
                    <span class="bread-item">{{ item.originalName }}</span>
                  </el-breadcrumb-item>
                </el-breadcrumb>
              </div>
              <div class="type">
                <el-radio-group v-model="viewType" @change="viewTypeChangeFun">
                  <el-radio value="1" label="文件模式" />
                  <el-radio value="2" label="作业模式" />
                </el-radio-group>
              </div>
              <div v-if="viewType === '1'" class="search" @click="searchFun">
                <el-button :icon="Search" size="small">搜索</el-button>
              </div>
            </div>
            <div class="table">
              <slot name="table" />
            </div>
          </div>
        </template>
      </DragSplit>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { MessageBox, Share, Folder, Search, Document } from '@element-plus/icons-vue';
import { NODE_TYPE } from '@/utils/enum/node';
import DragSplit from '@/components/common/dragSplit/index.vue';

interface Props {
  api: any;
  hideTree?: boolean;
  templateId: any;
  defaultExpandedKeys?: any;
}

const props = withDefaults(defineProps<Props>(), {
  api: null,
  hideTree: false,
  templateId: 0,
  defaultExpandedKeys: [],
});

const emit = defineEmits(['choseNode', 'updateNav', 'search', 'viewTypeChange']);

const treeRef = ref<any>();
const navList = ref<any>([]);
const visible = ref(true);
const viewType = ref('1'); // 1文件模式 2作业模式
const loading = ref(false);

watch(
  () => props.templateId,
  () => {
    reloadFun();
  }
);

const expandedKeys = ref<any>([]);
const currentKey = ref<any>('');
watch(
  () => navList.value,
  (val: any) => {
    const data = val.map((item: any) => {
      return {
        id: item.id,
        originalName: item.originalName,
      };
    });
    localStorage.setItem('DATA_OVERVIEW_NAV_LIST', JSON.stringify(data));
  },
  { deep: true }
);

let navListStorageData: any = JSON.parse(localStorage.getItem('DATA_OVERVIEW_NAV_LIST') || '[]');
const openDefaultExpandedFun = (baseData: any) => {
  if (navListStorageData.length > 0 || props.defaultExpandedKeys.length > 0) {
    // 1s后打开默认节点
    setTimeout(() => {
      if (baseData.length > 0 && props.defaultExpandedKeys.length > 0) {
        const projectData = baseData.find((i: any) => i.id === props.defaultExpandedKeys[0]);
        navListStorageData = projectData ? [projectData] : [];
      }
      navList.value = navListStorageData;
      expandedKeys.value = navList.value.map((i: any) => i.id);
      currentKey.value = navList.value[navList.value.length - 1].id;
    }, 1000);
  }
};

// 加载节点
const loadMoreFun = async (node: any, resolve: any) => {
  loading.value = true;
  const listData: any = await getDataFun(node.data);
  if (node.level >= 1) {
    listData.forEach((item: any) => {
      item.relatedParentUuid = node.data.relatedResourceUuid;
    });
    node.data.children = listData;
    choseNodeFun(node.data);
  } else {
    openDefaultExpandedFun(listData);
  }
  loading.value = false;
  return resolve(listData);
};

// 获取节点数据
const getDataFun = async (data: any) => {
  if (props.api && props.templateId) {
    const params = {
      dimensionTemplateId: props.templateId,
      fileIds: data.fileIds || [],
    };
    const res: any = await props.api(params);
    if (res.code === 200) {
      return res.data;
    } else {
      return [];
    }
  } else {
    return [];
  }
};

// 树形节点点击
const nodeClickFun = (data: any, node: any) => {
  updateNavFun([]);
  getTreeMenuFun(node);
  choseNodeFun(data);
};

// 循环获取父节点
const getTreeMenuFun = (node: any) => {
  if (node.label && node.parent) {
    const data = navList.value;
    data.unshift(node.data);
    updateNavFun(data);
    getTreeMenuFun(node.parent);
  }
};

// 打开目录
const openDirFun = (id: any) => {
  if (id === 0) {
    updateNavFun([]);
    choseNodeFun({ id: 0, fileIds: [] });
    return;
  }
  const node = treeRef.value.getNode(String(id));
  if (node) {
    node.loaded = false;
    node.expand();
    treeRef.value.setCurrentKey(id);
    choseNodeFun(node.data);
  }
};

// 返回上一级
const backFun = () => {
  const data = navList.value[navList.value.length - 2];
  openDirFun(data.id);
};

// 当前节点更改
const currentChangeFun = (data: any, node: any) => {
  updateNavFun([]);
  getTreeMenuFun(node);
};

// 选中节点
const choseNodeFun = (data: any) => {
  emit('choseNode', data);
};

// 导航变更
const updateNavFun = (data: any) => {
  navList.value = data;
  emit('updateNav', data);
};

const reloadFun = () => {
  navList.value = [];
  visible.value = false;
  setTimeout(() => {
    visible.value = true;
  }, 0);
};

const viewTypeChangeFun = (data: any) => {
  emit('viewTypeChange', data);
};

const searchFun = () => {
  emit('search');
};

const reloadNodeFun = (id: any) => {
  const node = treeRef.value.getNode(id);
  if (node) {
    node.loaded = false;
    node.expand();
  }
};

defineExpose({
  backFun,
  openDirFun,
  reloadFun,
  reloadNodeFun,
});
</script>

<style lang="scss" scoped>
.comp-content {
  height: 100%;
  .content {
    position: relative;
    height: 100%;
    display: flex;
    .left-content {
      width: 100%;
      min-height: 100%;
      background-color: var(--el-bg-color);
      border-radius: var(--border-radius-normal);
      padding: var(--padding-normal);
      .tree-item {
        width: calc(100% - 24px);
        height: 100%;
        display: flex;
        .icon {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 26px;
          color: var(--el-color-primary);
        }
        .label {
          flex: 1;
          line-height: 26px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .actions {
          display: flex;
          align-items: center;
          padding-left: var(--padding-normal);
        }
      }
    }
    .right-content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      background-color: var(--el-bg-color);
      border-radius: var(--border-radius-normal);
      padding: 0 var(--padding-normal) var(--padding-normal);
      .top-content {
        display: flex;
        align-items: center;
        padding: 10px 0;
        margin-bottom: 10px;
        border-bottom: solid 1px var(--el-border-color-light);
        .menu {
          flex: 1;
          min-height: 24px;
          margin-right: 20px;
          border-radius: 4px;
          display: flex;
          align-items: center;
          padding: 5px 10px;
          .bread-item {
            color: var(--el-color-primary);
          }
        }
        .type {
          margin-right: 30px;
        }
        .search {
          height: 24px;
          background-color: var(--el-bg-color-page);
          border-radius: 4px;
          display: flex;
          align-items: center;
        }
      }
      .table {
        flex: 1;
        height: 0;
      }
    }
  }
}
</style>
