<template>
  <q-splitter :model-value="70" class="w-full h-full">
    <template #before>
      <w-tree-grid
        ref="menuTreeGridRef"
        title="菜单树"
        label-key="titleI18nKey"
        label-i18n
        label-empty="--------------------"
        :actions="menuConfigure.actions"
        tick-strategy="none"
        @update:selected="menuSelected"
      />
    </template>
    <template #after>
      <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0">
        <q-tab name="role" icon="bi-diagram-3" :label="$t('role')" />
        <q-tab name="org" icon="bi-people" :label="$t('org')" />
      </q-tabs>

      <q-tab-panels v-model="selectedTabRef" animated swipeable keep-alive>
        <q-tab-panel name="user">
          <platform-grid
            ref="roleGridRef"
            :table-props="{ borderded: false, flat: true }"
            :query-form-cols-number="roleConfigure.queryFormColsNumber"
            :hide-bottom="roleConfigure.hideBottom"
            :query-form-cols-auto="roleConfigure.queryFormColsAuto"
            :table-title="roleConfigure.tableTitle"
            :table-row-key="roleConfigure.tableRowKey"
            :table-init-load-data="roleConfigure.tableInitLoadData"
            :table-data-url="roleConfigure.tableDataUrl"
            :table-show-sort-no="false"
            :table-columns="roleConfigure.tableColumns"
            :table-left-column-sticky-number="roleConfigure.tableLeftColumnStickyNumber"
            :table-buttons="roleConfigure.tableButtons"
            :query-form-fields="roleConfigure.queryFormFields"
            :table-pagination="roleConfigure.tablePagination"
            table-selection="multiple"
            :table-dense="false"
          >
          </platform-grid>
        </q-tab-panel>

        <q-tab-panel name="org">
          <w-tree-grid
            ref="orgTreeGridRef"
            title="机构树"
            label-key="titleI18nKey"
            label-i18n
            label-empty="--------------------"
            :actions="orgConfigure.actions"
          />
        </q-tab-panel>
      </q-tab-panels>
    </template>
    <SelectRoleDialog ref="selectRoleDialog" title="可选角色列表" :maximized="false" width="50%" height="500px"></SelectRoleDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Environment, axios } from 'platform-core';
import SelectRoleDialog from './SelectRoleDialog.vue';

const { t } = useI18n();

const menuTreeGridRef = ref();
const roleGridRef = ref();
const orgTreeGridRef = ref();

const selectRoleDialog = ref();
const selectedTabRef = ref('user');
let selectedMenuId = '';

const roleConfigure = {
  queryFormColsNumber: 4,
  queryFormColsAuto: false,
  queryFormFields: [],
  hideBottom: true,
  tableInitLoadData: false,
  tableLeftColumnStickyNumber: 0,
  tableTitle: t('system.role.gridTitle'),
  tableRowKey: 'id',
  tableDataUrl: '',
  tablePagination: {
    sortBy: 'lastModifyDate',
    descending: true,
    reqPageStart: 0,
    rowsPerPage: 0,
  },
  tableButtons: [
    'refresh',
    'inFullscreen',
    {
      name: 'addRole',
      label: t('system.role.action.addRole'),
      icon: '',
      enable: () => {},
      click: () => {
        selectRoleDialog.value.show({ roleGridRef: roleGridRef, menuTreeGridRef: menuTreeGridRef });
      },
    },
    {
      name: 'addAllRole',
      label: t('system.role.action.addAllRole'),
      icon: '',
      enable: () => {},
      click: () => {
        const menuId = menuTreeGridRef.value.getSelected();
        axios
          .post(Environment.apiContextPath('/api/system/menu/addAllRoles'), {
            source: menuId,
            sourceParents: menuTreeGridRef.value.getCascadeParentIds(menuId),
            sourceChildren: menuTreeGridRef.value.getCascadeChildrenIds(menuId),
            targets: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByMenu?menuId=') + menuId).then((response) => {
              roleGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeRole',
      label: t('system.role.action.removeRole'),
      icon: '',
      enable: () => {},
      click: () => {
        const menuId = menuTreeGridRef.value.getSelected();
        const roleIds = [];
        for (const role of roleGridRef.value.getSelectedRows()) {
          roleIds.push(role.id);
        }
        axios
          .post(Environment.apiContextPath('/api/system/menu/removeRoles'), {
            source: menuId,
            sourceParents: menuTreeGridRef.value.getCascadeParentIds(menuId),
            sourceChildren: menuTreeGridRef.value.getCascadeChildrenIds(menuId),
            targets: roleIds,
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByMenu?menuId=') + menuId).then((response) => {
              roleGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeAllRole',
      label: t('system.role.action.removeAllRole'),
      icon: '',
      enable: () => {},
      click: () => {
        const menuId = menuTreeGridRef.value.getSelected();
        axios
          .post(Environment.apiContextPath('/api/system/menu/removeAllRoles'), {
            source: menuId,
            sourceParents: menuTreeGridRef.value.getCascadeParentIds(menuId),
            sourceChildren: menuTreeGridRef.value.getCascadeChildrenIds(menuId),
            targets: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByMenu?menuId=') + menuId).then((response) => {
              roleGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
  ],
  tableColumns: [
    { width: 100, name: 'code', label: t('code') },
    { width: 100, name: 'name', label: t('name') },
    { width: 80, name: 'enable', label: t('isEnable'), format: (value) => (value ? t('yes') : t('no')) },
  ],
};

const menuConfigure = {
  actions: [
    {
      name: 'refresh',
      label: t('refresh'),
      click: () => {},
    },

    {
      name: 'addRoot',
      label: t('system.menu.action.addTop'),
      click: () => {},
    },
    {
      name: 'addChild',
      label: t('system.menu.action.addChild'),
      click: () => {},
    },
    {
      name: 'edit',
      label: t('edit'),
      click: () => {},
    },
    {
      name: 'delete',
      label: t('delete'),
      click: () => {},
    },
  ],
};

const orgConfigure = {
  actions: [
    {
      name: 'save',
      label: '保存',
      click: () => {
        const orgId = menuTreeGridRef.value.getSelected()[0];
        axios
          .post(Environment.apiContextPath('/api/system/menu/updateOrgs'), {
            one: orgId,
            many: menuTreeGridRef.value.getTicked(),
          })
          .then((response) => {});
      },
    },
  ],
};

const menuSelected = (target) => {
  selectedMenuId = target;
  if (roleGridRef.value) {
    axios.get(Environment.apiContextPath('/api/system/role/queryRolesByMenu?menuId=') + selectedMenuId).then((response) => {
      roleGridRef.value.replaceRowsFun(response.data.content);
    });
  }

  // if (orgTreeGridRef.value) {
  //   axios.get(Environment.apiContextPath('/api/system/org/listAllOrgsWithSelectedStatusByMenu?menuId=') + selectedMenuId).then((response) => {
  //     orgTreeGridRef.value.setNodes(response.data);
  //   });
  // }
};

onMounted(() => {
  axios.get(Environment.apiContextPath('/api/system/menu?pageable=false&sortBy=order')).then((response) => {
    menuTreeGridRef.value.setNodes(response.data.content);
  });
});
</script>
