<template>
  <div class="manual-contents">
    <div class="manual-contents-actionbar">
      <div class="manual-contents-actionbar-left">
        <div class="actionbar-item">
          <Checkbox
            v-model:checked="checkedState.checkAll"
            :indeterminate="checkedState.indeterminate"
            @change="onCheckAllChange"
          />
          <span v-if="checkedState.indeterminate"> 已选择{{ checkedKeys.length }}个</span>
          <span v-else> 所有文档</span>
        </div>
        <div class="actionbar-item" @click="onCollapseAll">
          <PicCenterOutlined /> 全部折叠
        </div>
        <div class="actionbar-item" @click="onExpandAll">
          <PicLeftOutlined /> 全部展开
        </div>
        <div class="actionbar-item" @click="onAdd(0, 'atricle')">
          <PlusCircleOutlined /> 添加文档
        </div>
        <div class="actionbar-item" @click="onAdd(0, 'group')">
          <PlusSquareOutlined /> 添加分组
        </div>
        <div class="actionbar-item">
          <Select
            show-search
            size="small"
            placeholder="请输入搜索内容"
            style="width: 200px"
            v-model:value="searchArticle"
            @change="changeSelect"
          >
            <SelectOption v-for="opt in listData" :key="opt.id">
              {{ opt.title }}
            </SelectOption>
          </Select>
        </div>
      </div>
      <div
        class="manual-contents-actionbar-right"
        v-if="checkedKeys.length"
      >
        <Button
          type="danger"
          size="small"
        >删除</Button>
      </div>
    </div>
    <Tree
      class="draggable-tree"
      v-model:selectedKeys="selectedKeys"
      v-model:checkedKeys="checkedKeys"
      v-model:expandedKeys="expandedKeys"
      draggable
      block-node
      checkable
      :tree-data="treeData"
      @dragenter="onDragEnter"
      @drop="onDrop"
      @dragend="onDragend"
      @dragstart="onDragstart"
      :fieldNames="{
        key: 'id',
      }"
    >
      <template #title="node">
        <div class="tree-node-title">
          <div class="tree-title-left">
            <Input v-if="showTreeInput.id === node.id" v-model:value="showTreeInput.value" v-focus size="small" placeholder="small size" @blur="onBlur" />
            <span v-else @click.stop @dblclick="onEdit(node)">{{ node.title }}</span>
          </div>
          <div class="tree-title-right">
            <span class="article-time">{{ dateTimeFormat(node.updateTime) }}</span>
            <span class="article-operate">
              <EyeOutlined @click.stop="onView(node)" />
              <Dropdown>
                <PlusSquareOutlined />
                <template #overlay>
                  <Menu>
                    <MenuItem key="1">
                      <template #icon>
                        <ContainerOutlined />
                      </template>
                      <span>新建文档</span>
                    </MenuItem>
                    <MenuItem key="2">
                      <template #icon>
                        <DatabaseOutlined />
                      </template>
                      <span>新建分组</span>
                    </MenuItem>
                    <MenuItem key="3">
                      <template #icon>
                        <EditOutlined />
                      </template>
                      <span>编辑文档</span>
                    </MenuItem>
                    <MenuDivider />
                    <MenuItem key="4">
                      <template #icon>
                        <HighlightOutlined />
                      </template>
                      <span>重命名</span>
                    </MenuItem>
                    <MenuItem key="5">
                      <template #icon>
                        <DeleteOutlined />
                      </template>
                      <span>删除</span>
                    </MenuItem>
                  </Menu>
                </template>
              </Dropdown>
            </span>
          </div>
        </div>
      </template>
    </Tree>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRaw, watch, onMounted } from 'vue';
import { Button, Input, Tree, Checkbox, Select, SelectOption, Dropdown, Menu, MenuItem, MenuDivider, message } from 'ant-design-vue';
import { EyeOutlined, PlusSquareOutlined, PlusCircleOutlined, PicLeftOutlined, PicCenterOutlined, ContainerOutlined, DatabaseOutlined, EditOutlined, HighlightOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import type { AntTreeNodeDragEnterEvent, AntTreeNodeDropEvent, TreeProps } from 'ant-design-vue/es/tree';
import { useRouter, useRoute } from 'vue-router';
import { addManualArticleApi, getManualArticleListApi } from '@/apis/manual';
import { listToTree } from "@/utils";
import moment from "moment";

export default defineComponent({
  name: 'manual-contents',
  components: { Button, Input, Tree, Checkbox, Select, SelectOption, Dropdown, Menu, MenuItem, MenuDivider, EyeOutlined, PlusSquareOutlined, PlusCircleOutlined, PicLeftOutlined, PicCenterOutlined, ContainerOutlined, DatabaseOutlined, EditOutlined, HighlightOutlined, DeleteOutlined },
  props: {
    formId: { type: Number },
  },
  directives: {
    // 在模板中启用 v-focus
    focus: {
      mounted: (el) => el.focus()
    }
  },
  setup(props, ctx) {
    const route = useRoute();
    const checkedState = reactive({
      indeterminate: false,
      checkAll: false,
    });
    const searchArticle = ref();
    const listData = ref<any>([]);
    const treeData = ref<TreeProps['treeData']>([]);
    const selectedKeys = ref<string[]>([]);
    const checkedKeys = ref<string[]>([]);
    const expandedKeys = ref<string[]>([]);
    const showTreeInput = reactive({
      id: undefined,
      value: ''
    });

    onMounted(() => {
      // 
    });

    watch(
      [() => checkedKeys.value, () => listData.value],
      () => {
        checkedState.indeterminate = !!checkedKeys.value.length  && checkedKeys.value.length < listData.value.length;
        checkedState.checkAll = checkedKeys.value.length === listData.value.length;
      },
    );
    
    const dateTimeFormat = (dateTime: string) => {
      return dateTime ? moment(dateTime).format('YYYY-MM-DD HH:mm:ss') : '';
    };

    const getManualArticleList = async () => {
      const id = toRaw(props.formId) as number;
      const data = await getManualArticleListApi(id);
      listData.value = data;
      treeData.value = listToTree(data, 'parentId');
    };

    watch(() => props.formId, () => getManualArticleList(), { immediate: true });

    const onCheckAllChange = () => {
      let arr = [];
      if (checkedState.checkAll) {
        arr = listData.value.map((item: any) => item.id);
      }
      checkedKeys.value = arr;
      checkedState.indeterminate = false;
    };
    
    const onCollapseAll = () => {
      expandedKeys.value = [];
    };

    const onExpandAll = () => {
      const keys = listData.value.filter((item: any) => item.children && item.children.length > 0).map((item: any) => item.id);
      expandedKeys.value = keys;
    };

    const onAdd = async (parentId: number, type: string) => {
      const title = type == 'atricle' ? '新增文档' : '新增分组';
      const formData = {
        title,// 文章名称
        explain: '',// 说明
        manuals: props.formId,// 属于哪个手册
        content: '',// 内容
        type,// 类型 分组|文章
        parentId,// 父级id
        authorityUser: [],// 具有权限的用户
        authorityRole: [],// 具有权限的角色
        resourceAuthority: false,// 资源是否可下载
        index: 0,// 排名
        // 资源量
        video: 0,
        audio: 0,
        image: 0,
        model: 0,
      };
      const data = await addManualArticleApi(formData);
      message.success(`${title}创建成功`);
      await getManualArticleList();
      selectedKeys.value = [data.id];
    };

    const onEdit = (node: any) => {
      // 
      console.log('onEdit', node);
      showTreeInput.id = node.id;
      showTreeInput.value = node.title;
      selectedKeys.value = [node.id];
    };

    const onBlur = () => {
      // 
    };

    const onView = (node: any) => {
      console.log('onView', node);
    };
    
    const getPathRelations: any = (id: any, arr: any = []) => {
      for (let i = 0; i < listData.value.length; i++) {
        const item = listData.value[i];
        if (item.id === id && item.parentId) {
          const index = arr.indexOf(item.parentId)
          if (index === -1) {
            arr.push(item.parentId);
            return getPathRelations(item.parentId, arr);
          }
          return arr;
        }
      }
    }

    const changeSelect = (key: any) => {
      getPathRelations(key, expandedKeys.value);
      selectedKeys.value = [key];
    };

    const onDragEnter = (info: AntTreeNodeDragEnterEvent) => {
      console.log(info);
      // expandedKeys 需要展开时
      // expandedKeys.value = info.expandedKeys;
    };

    const onDrop = (info: AntTreeNodeDropEvent) => {
      console.log(info);
      // const dropKey = info.node.key;
      // const dragKey = info.dragNode.key;
      // const dropPos = info.node.pos.split('-');
      // const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
      // const loop = (data: TreeProps['treeData'], key: string | number, callback: any) => {
      //   data.forEach((item, index) => {
      //     if (item.key === key) {
      //       return callback(item, index, data);
      //     }
      //     if (item.children) {
      //       return loop(item.children, key, callback);
      //     }
      //   });
      // };
      // const data = [...treeData.value];

      // // Find dragObject
      // let dragObj: TreeDataItem;
      // loop(data, dragKey, (item: TreeDataItem, index: number, arr: TreeProps['treeData']) => {
      //   arr.splice(index, 1);
      //   dragObj = item;
      // });
      // if (!info.dropToGap) {
      //   // Drop on the content
      //   loop(data, dropKey, (item: TreeDataItem) => {
      //     item.children = item.children || [];
      //     /// where to insert 示例添加到头部，可以是随意位置
      //     item.children.unshift(dragObj);
      //   });
      // } else if (
      //   (info.node.children || []).length > 0 && // Has children
      //   info.node.expanded && // Is expanded
      //   dropPosition === 1 // On the bottom gap
      // ) {
      //   loop(data, dropKey, (item: TreeDataItem) => {
      //     item.children = item.children || [];
      //     // where to insert 示例添加到头部，可以是随意位置
      //     item.children.unshift(dragObj);
      //   });
      // } else {
      //   let ar: TreeProps['treeData'] = [];
      //   let i = 0;
      //   loop(data, dropKey, (_item: TreeDataItem, index: number, arr: TreeProps['treeData']) => {
      //     ar = arr;
      //     i = index;
      //   });
      //   if (dropPosition === -1) {
      //     ar.splice(i, 0, dragObj);
      //   } else {
      //     ar.splice(i + 1, 0, dragObj);
      //   }
      // }
      // treeData.value = data;
    };

    const onDragend = () => {
      //
    };

    const onDragstart = () => {
      //
    };

    return {
      checkedState,
      searchArticle,
      listData,
      treeData,
      selectedKeys,
      checkedKeys,
      expandedKeys,
      showTreeInput,
      dateTimeFormat,
      onCollapseAll,
      onExpandAll,
      onAdd,
      onEdit,
      onBlur,
      onView,
      onCheckAllChange,
      changeSelect,
      onDragEnter,
      onDrop,
      onDragend,
      onDragstart,
    };
  },
});
</script>
<style lang="less" scoped>
.manual-contents {
  width: 100%;
  border-radius: 8px;
  background-color: #f4f4f4;
  overflow: hidden;
  &-actionbar {
    width: 100%;
    padding: 6px 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #27a1ac;
    color: white;
    font-weight: 700;
    &-left,
    &-right {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
    }
    &-left {
      .actionbar-item {
        margin: 0 10px;
        cursor: pointer;
        .anticon {
          margin-right: 4px;
        }
      }
    }
  }
  /deep/ .draggable-tree {
    min-height: 200px;
    background-color: #f4f4f4;
    padding: 10px 10px 10px 0;
    .ant-tree-treenode {
      padding: 2px 0;
      line-height: 28px;
      &.ant-tree-treenode-selected {
        border: 2px solid #008cff;
        border-radius: 2px;
      }
      .ant-tree-node-content-wrapper {
        &.ant-tree-node-selected {
          background-color: transparent;
        }
        .ant-tree-title {
          .tree-node-title {
            display: flex;
            justify-content: space-between;
            .tree-title-left {

            }
            .tree-title-right {
              .article-time {
                display: inline-block;
              }
              .article-operate {
                display: none;
                > .anticon {
                  font-size: 16px;
                  margin: 0 4px;
                }
              }
            }
          }
        }
      }
      &:hover {
        .article-time {
          display: none !important;
        }
        .article-operate {
          display: inline-block !important;
        }
      }
    }
  }
}
</style>
