<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="navigationId"
        :columns="columns"
        :datasource="datasource"
        :parse-data="parseData"
        :need-page="false"
        :customRow="customRow"
        :expand-icon-column-index="1"
        :expanded-row-keys="expandedRowKeys"
        :scroll="{ x: 1200 }"
        cache-key="proNavigationTable"
        @done="onDone"
        @expand="onExpand"
      >
        <template #toolbar>
          <a-space>
            <a-button type="primary" class="ele-btn-icon" @click="openEdit()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>新建</span>
            </a-button>
            <a-button type="dashed" class="ele-btn-icon" @click="expandAll">
              展开全部
            </a-button>
            <a-button type="dashed" class="ele-btn-icon" @click="foldAll">
              折叠全部
            </a-button>
            <a-divider type="vertical" />
            <a-radio-group v-model:value="position" @change="reload">
              <a-radio-button :value="1">顶部</a-radio-button>
              <a-radio-button :value="2">底部</a-radio-button>
            </a-radio-group>
            <a-divider type="vertical" />
            <!-- 搜索表单 -->
            <a-input-search
              allow-clear
              v-model:value="searchText"
              placeholder="请输入搜索关键词"
              @search="reload"
              @pressEnter="reload"
            />
          </a-space>
        </template>
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.key === 'path'">
            <span class="ele-text-placeholder">{{ record.path }}</span>
          </template>
          <template v-if="column.key === 'component'">
            <template v-if="!isDirectory(record)">
              <span class="ele-text-placeholder">{{ record.component }}</span>
            </template>
            <template v-else>
              <span></span>
            </template>
          </template>
          <template v-if="column.key === 'type'">
            <a-tag v-if="isExternalLink(record.path)" color="red">外链</a-tag>
            <a-tag v-else-if="index === 0" color="orange">首页</a-tag>
            <a-tag v-else-if="isExternalLink(record.component)" color="orange">
              内链
            </a-tag>
            <span v-else-if="isDirectory(record)"></span>
            <a-tag v-else-if="record.type === 0">通用</a-tag>
            <a-tag v-else-if="record.type === 1" color="purple">页面</a-tag>
            <a-tag v-else-if="record.type === 2">列表</a-tag>
            <a-tag v-else-if="record.type === 3">文章</a-tag>
            <a-tag v-else-if="record.type === 4" color="cyan">表单</a-tag>
            <a-tag v-else-if="record.type === 5" color="green">文档</a-tag>
            <a-tag v-else-if="record.type === 9" color="orange">链接</a-tag>
          </template>
          <template v-else-if="column.key === 'title'">
            <a-avatar
              :size="22"
              shape="square"
              :src="`${record.image}`"
              style="margin-right: 10px"
              v-if="record.image"
            />
            <a v-if="!isDirectory(record)" @click="openPreview(record.path)">{{
              record.title
            }}</a>
            <a v-else>{{ record.title }}</a>
          </template>
          <template v-if="column.key === 'showIndex'">
            <a-tag v-if="record.showIndex === 1" color="green">显示</a-tag>
            <span v-else></span>
          </template>
          <template v-if="column.key === 'position'">
            <span v-if="record.position === 1" class="ele-text-placeholder"
              >顶部</span
            >
            <span v-if="record.position === 2" class="ele-text-placeholder"
              >底部</span
            >
            <span v-if="record.position === 0"></span>
          </template>
          <template v-if="column.key === 'hide'">
            <span v-if="record.hide === 0" class="ele-text-success">显示</span>
            <span v-if="record.hide === 1" class="ele-text-placeholder"
              >隐藏</span
            >
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a @click="openEdit(null, record.navigationId)">添加</a>
              <a-divider type="vertical" />
<!--              <a @click="moveUp(record)">上移<ArrowUpOutlined /></a>-->
<!--              <a-divider type="vertical" />-->
              <a @click="openEdit(record)">修改</a>
              <a-divider type="vertical" />
              <a-popconfirm
                placement="topRight"
                title="确定要删除此菜单吗？"
                @confirm="remove(record)"
              >
                <a class="ele-text-danger">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <navigation-edit
      v-model:visible="showEdit"
      :data="current"
      :parent-id="parentId"
      :navigation-list="navigationData"
      :position="position"
      @done="reload"
    />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message } from 'ant-design-vue/es';
  import { ArrowUpOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import type {
    DatasourceFunction,
    ColumnItem,
    EleProTableDone
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import {
    messageLoading,
    toDateString,
    isExternalLink,
    toTreeData,
    eachTreeData
  } from 'ele-admin-pro/es';
  import type { EleProTable } from 'ele-admin-pro/es';
  import NavigationEdit from './components/navigation-edit.vue';
  import {
    listNavigation,
    removeNavigation,
    updateNavigation
  } from '@/api/cms/navigation';
  import type { Navigation, NavigationParam } from '@/api/cms/navigation/model';
  import { openPreview } from '@/utils/common';
  import { getSiteInfo } from '@/api/layout';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'navigationId',
      width: 80
    },
    {
      title: '菜单名称',
      dataIndex: 'title',
      key: 'title',
      showSorterTooltip: false,
      ellipsis: true
    },
    {
      title: '路由地址',
      dataIndex: 'path',
      key: 'path'
    },
    {
      title: '组件路径',
      dataIndex: 'component',
      key: 'component'
    },
    {
      title: '模型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      width: 120
    },
    {
      title: '位置',
      dataIndex: 'position',
      key: 'position',
      align: 'center',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'hide',
      key: 'hide',
      align: 'center',
      width: 120,
      showSorterTooltip: false,
      customRender: ({ text }) => ['显示', '隐藏'][text]
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      align: 'center',
      width: 120,
      showSorterTooltip: false
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      showSorterTooltip: false,
      ellipsis: true,
      width: 180,
      customRender: ({ text }) => toDateString(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center'
    }
  ]);

  // 当前编辑数据
  const current = ref<Navigation | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 上级分类id
  const parentId = ref<number>();
  // 分类数据
  const navigationData = ref<Navigation[]>([]);
  // 表格展开的行
  const expandedRowKeys = ref<number[]>([]);
  const searchText = ref('');
  const position = ref(1);
  const tenantId = ref<number>();
  const domain = ref<string>();

  getSiteInfo().then((data) => {
    tenantId.value = data.tenantId;
    domain.value = data.domain;
  });

  // 表格数据源
  const datasource: DatasourceFunction = ({ where }) => {
    where = {};
    where.title = searchText.value;
    where.position = position.value;
    where.isMpWeixin = false;
    return listNavigation({ ...where });
  };

  // 上移
  const moveUp = (row?: Navigation) => {
    updateNavigation({
      navigationId: row?.navigationId,
      sortNumber: Number(row?.sortNumber) - 1
    }).then((msg) => {
      message.success(msg);
      reload();
    });
  };

  /* 数据转为树形结构 */
  const parseData = (data: Navigation[]) => {
    return toTreeData({
      data: data.map((d) => {
        return { ...d, key: d.navigationId, value: d.navigationId };
      }),
      idField: 'navigationId',
      parentIdField: 'parentId'
    });
  };

  /* 表格渲染完成回调 */
  const onDone: EleProTableDone<Navigation> = ({ data }) => {
    navigationData.value = data;
  };

  /* 刷新表格 */
  const reload = (where?: NavigationParam) => {
    tableRef?.value?.reload({ where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: Navigation | null, id?: number) => {
    current.value = row ?? null;
    parentId.value = id;
    showEdit.value = true;
  };

  /* 删除单个 */
  const remove = (row: Navigation) => {
    if (row.home == 1) {
      return;
    }
    if (row.children?.length) {
      message.error('请先删除子节点');
      return;
    }
    const hide = messageLoading('请求中..', 0);
    removeNavigation(row.navigationId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 展开全部 */
  const expandAll = () => {
    let keys: number[] = [];
    eachTreeData(navigationData.value, (d) => {
      if (d.children && d.children.length && d.navigationId) {
        keys.push(d.navigationId);
      }
    });
    expandedRowKeys.value = keys;
  };

  /* 折叠全部 */
  const foldAll = () => {
    expandedRowKeys.value = [];
  };

  /* 点击展开图标时触发 */
  const onExpand = (expanded: boolean, record: Navigation) => {
    if (expanded) {
      expandedRowKeys.value = [
        ...expandedRowKeys.value,
        record.navigationId as number
      ];
    } else {
      expandedRowKeys.value = expandedRowKeys.value.filter(
        (d) => d !== record.navigationId
      );
    }
  };

  /* 判断是否是目录 */
  const isDirectory = (d: Navigation) => {
    return !!d.children?.length;
  };

  /* 自定义行属性 */
  const customRow = (record: Navigation) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'Navigation'
  };
</script>
