<template>
  <ResizePageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <template #resizeLeft>
      <BasicTree
        :title="t('菜单分类')"
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
        :selectedKeys="selectedKeys"
      />
    </template>
    <template #resizeRight>
      <BasicTable @register="registerTable">
        <template #toolbar>
          <a-button type="primary" v-auth="'appMenu:add'" @click="handleCreate">
            {{ t('新增菜单') }}
          </a-button>
        </template>
        <template #action="{ record, index }">
          <TableAction
            :actions="[
              {
                label: '编辑',
                auth: 'appMenu:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'appMenu:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  visible: popVisible(index),
                  onVisibleChange: handleVisibleChange.bind(null, index),
                  confirm: handleDelete.bind(null, record),
                  cancel: handleCancel,
                },
              },
            ]"
          />
        </template>
      </BasicTable>
      <MenuDrawer @register="registerModal" @success="handleSuccess" />
    </template>
  </ResizePageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, onMounted, ref } from 'vue';

  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';
  import { getAppMenuTree, deleteAppMenu } from '/@/api/system/menu';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useModal } from '/@/components/Modal';
  import MenuDrawer from './components/MenuDrawer.vue';
  // import Icon from '/@/components/Icon';
  import { Tag } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getDicDetailList } from '/@/api/system/dic';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  const { t } = useI18n();

  export const columns: BasicColumn[] = [
    // {
    //   title: t('菜单名称'),
    //   dataIndex: 'title',
    //   width: 200,
    //   align: 'left',
    // },
    {
      title: t('菜单名称'),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: t('编码'),
      dataIndex: 'code',
      align: 'center',
    },
    // {
    //   title: t('图标'),
    //   dataIndex: 'icon',
    //   align: 'left',
    //   width: 50,
    //   customRender: ({ record }) => {
    //     return h(Icon, { icon: record.icon });
    //   },
    // },
    // {
    //   title: t('组件'),
    //   dataIndex: 'component',
    //   align: 'left',
    // },

    {
      title: t('状态'),
      dataIndex: 'enabledMark',
      width: 80,
      align: 'center',
      customRender: ({ record }) => {
        const enabledMark = record.enabledMark;
        const enable = ~~enabledMark === 1;
        const color = enable ? 'green' : 'red';
        const text = enable ? t('启用') : t('停用');
        return h(Tag, { color: color }, () => text);
      },
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      align: 'center',
    },
  ];

  export const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('菜单名称'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'code',
      label: t('	编码'),
      component: 'Input',
      colProps: { lg: 8, md: 12, sm: 12 },
    },
    {
      field: 'enabledMark',
      label: t('状态'),
      component: 'Select',
      componentProps: {
        options: [
          { label: t('启用'), value: 1 },
          { label: t('停用'), value: 0 },
        ],
      },
      colProps: { lg: 8, md: 12, sm: 12 },
    },
  ];

  export default defineComponent({
    name: 'MenuManagement',
    components: { BasicTable, MenuDrawer, TableAction, ResizePageWrapper, BasicTree },
    setup() {
      const { notification } = useMessage();
      const { hasPermission } = usePermission();
      const selectedKeys = ref<string[]>(['']);
      const treeData = ref<TreeItem[]>([]);
      const selectParentId = ref('');
      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        title: t('菜单列表'),
        api: getAppMenuTree,
        columns,
        rowKey: 'id',
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          showResetButton: false,
        },
        pagination: {
          pageSize: 20,
        },
        striped: false,
        useSearchForm: true,
        showTableSetting: true,
        showIndexColumn: false,
        actionColumn: {
          width: 88,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
        tableSetting: {
          size: false,
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, detailId: selectParentId.value };
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('appMenu:edit')) {
                handleEdit(record);
              }
            },
          };
        },
      });
      const isVisible = ref<boolean>(false);
      const deleteIndex = ref();
      onMounted(async () => {
        await getTreeData();
      });
      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }
      function handleEdit(record: Recordable) {
        const childIds = [];
        openModal(true, {
          record,
          isUpdate: true,
          childIds,
        });
      }

      function handleDelete(record: Recordable) {
        isVisible.value = false;
        const permissionStore = usePermissionStore();
        deleteAppMenu([record.id]).then(async (_) => {
          await permissionStore.buildRoutesAction(false);
          reload();
          notification.success({
            message: t('提示'),
            description: t('删除成功'),
          }); //提示消息
        });
      }

      function handleSuccess() {
        reload();
      }

      function handleCancel() {
        isVisible.value = false;
      }

      function popVisible(index) {
        return isVisible.value && index === deleteIndex.value;
      }

      function handleVisibleChange(index, bool) {
        if (!bool) {
          isVisible.value = false;
          return;
        }
        if (import.meta.env.VITE_GLOB_PRODUCTION === 'true') {
          notification.warning({
            message: '在线环境暂不允许该操作，请联系管理员。',
          });
          return;
        }
        isVisible.value = true;
        deleteIndex.value = index;
      }

      function handleSelect(componentRow) {
        selectParentId.value = componentRow[0];
        reload();
      }
      async function getTreeData() {
        let res = (await getDicDetailList({
          itemId: '1673142942973763585',
        })) as unknown as TreeItem[];

        treeData.value = res;
        treeData.value.unshift({
          key: '',
          id: '',
          name: '全部',
        });
      }
      return {
        registerTable,
        registerModal,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleCancel,
        handleVisibleChange,
        popVisible,
        t,
        selectedKeys,
        handleSelect,
        treeData,
      };
    },
  });
</script>
