<template>
  <div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'menuType'">
          <Tag :color="formatDictColor(sysMenuTypeOptions, record.menuType)">
            {{ formatDictValue(sysMenuTypeOptions, record.menuType) }}
          </Tag>
        </template>
        <template v-if="column.key === 'icon'">
          <Icon :icon="record.icon" />
        </template>
        <template v-if="column.key === 'keepalive'">
          <Tag :color="record.keepalive ? 'success' : 'error'">
            {{ commonDict(record.keepalive) }}
          </Tag>
        </template>
        <template v-if="column.key === 'linkExternal'">
          <Tag :color="record.linkExternal ? 'success' : 'error'">
            {{ commonDict(record.linkExternal) }}
          </Tag>
        </template>
        <template v-if="column.key === 'visible'">
          <Tag :color="record.visible ? 'success' : 'error'">
            {{ commonDict(record.visible, 2) }}
          </Tag>
        </template>
        <template v-if="column.key === 'frame'">
          <Tag :color="record.frame ? 'success' : 'error'">
            {{ commonDict(record.frame) }}
          </Tag>
        </template>
        <template v-if="column.key === 'disable'">
          <Tag :color="record.disable ? 'error' : 'success'">
            {{ commonDict(record.disable, 1) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: ['sys:menu:edit'],
                icon: 'icon-edit|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                auth: ['sys:menu:remove'],
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
      <template #toolbar>
        <a-button
          v-auth="['sys:menu:add']"
          type="primary"
          @click="handleCreate"
          preIcon="icon-plus|iconfont"
          >新增</a-button
        >
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Tag } from 'ant-design-vue';
  import { nextTick, onBeforeMount, ref, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import Icon from '/@/components/Icon/index';
  import FormModal from './FormModal.vue';
  import { columns, searchFormSchema } from './data';

  // import { fetchList, removeObj } from '/@/api/modules/system/sysMenuApi';
  import { sysMenuQueryPage, sysMenuRemove } from '/@/api/sys/sysMenuApi';
  import { listDictModel } from '/@/api/common';
  import { formatDictValue, commonDict, formatDictColor } from '/@/utils';

  const emit = defineEmits(['refresh-tree']);

  const props = defineProps({
    nodeId: { type: String },
  });

  const sysMenuTypeOptions = ref([]);
  const sysTenantMenuOptions = ref([]);
  onBeforeMount(async () => {
    sysMenuTypeOptions.value = await listDictModel({ dictCode: 'sys_menu_type' });
    sysTenantMenuOptions.value = await listDictModel({ dictCode: 'sys_tenant_menu' });
  });

  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: '菜单列表',
    api: sysMenuQueryPage,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      baseColProps: { span: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    showIndexColumn: false,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      auth: ['sys:menu:edit', 'sys:menu:remove'],
      width: 80,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    afterFetch: handleAfterFetch,
    sortFn: handleSortFn,
  });

  const tableSort = ref([
    {
      field: 'sort',
      direction: 'ASC',
    },
  ]) as any;

  // 新增按钮事件
  function handleCreate() {
    const record = {
      parentId: props.nodeId,
    };
    openModal(true, {
      record,
      isUpdate: false,
    });
  }

  // 编辑按钮事件
  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log(record);
    await sysMenuRemove([record.id]);
    createMessage.success('删除成功！');
    emit('refresh-tree', record.parentId === '0' ? undefined : record.parentId);
    // 表格刷新，在refresh-tree事件之后，执行
    // await reload();
  }

  // 弹窗回调事件
  function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    emit('refresh-tree', values.parentId);
    // 表格刷新，在refresh-tree事件之后，执行
    // reload();
  }

  // 表格请求之前，对参数进行处理, 添加默认 排序
  function handleBeforeFetch(params) {
    console.log('🚀 ~ file: index.vue:204 ~ handleBeforeFetch ~ params', params);
    return { ...params, parentId: !props.nodeId ? '0' : props.nodeId, orders: tableSort.value };
  }

  // 表格点击字段排序
  function handleSortFn(sortInfo) {
    console.log('🚀 ~ file: index.vue:209 ~ handleSortFn ~ sortInfo', sortInfo);
    if (sortInfo?.order && sortInfo?.columnKey) {
      // 默认单列排序
      tableSort.value = [
        {
          field: sortInfo.columnKey,
          direction: sortInfo.order.replace(/(\w+)(end)/g, '$1').toUpperCase(),
        },
      ];
    }
  }

  function handleAfterFetch(data) {
    console.log('🚀 ~ file: index.vue:204 ~ handleAfterFetch ~ data', data);
    const res = data.map(ele => {
      ele.children = null;
      return ele;
    });
    return res;
  }

  // 刷新表格
  function refresh() {
    reload();
  }

  watch(
    () => props.nodeId,
    () => {
      nextTick(() => {
        reload();
      });
    },
  );

  // 暴露内部方法
  defineExpose({ refresh });
</script>
