<template>
  <q-splitter :model-value="70" class="w-full h-full">
    <template #before>
      <w-tree-grid ref="orgTreeGridRef" title="机构树" label-key="name" :actions="orgConfigure.actions" @update:selected="orgSelected" />
    </template>
    <template #after>
      <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0">
        <q-tab name="user" icon="bi-diagram-3" :label="$t('user')" />
        <q-tab name="menu" icon="bi-people" :label="$t('menu')" />
      </q-tabs>

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

        <q-tab-panel name="menu">
          <w-tree-grid
            ref="menuTreeGridRef"
            title="菜单树"
            label-key="titleI18nKey"
            label-i18n
            label-empty="--------------------"
            tick-strategy="leaf"
            :actions="menuConfigure.actions"
          />
        </q-tab-panel>
      </q-tab-panels>
    </template>
    <SelectUserDialog ref="selectUserDialog" title="可选用户列表" :maximized="false" width="50%" height="500px"></SelectUserDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Environment, axios } from 'platform-core';
import SelectUserDialog from './SelectUserDialog.vue';

const { t } = useI18n();

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

const selectUserDialog = ref();
const selectedTabRef = ref('user');
let selectedOrgId = '';

const userConfigure = {
  queryFormColsNumber: 4,
  queryFormColsAuto: false,
  queryFormFields: [],
  hideBottom: true,
  tableInitLoadData: false,
  tableLeftColumnStickyNumber: 0,
  tableTitle: t('system.user.gridTitle'),
  tableRowKey: 'id',
  tableDataUrl: '',
  tablePagination: {
    sortBy: 'lastModifyDate',
    descending: true,
    reqPageStart: 0,
    rowsPerPage: 0,
  },
  tableButtons: [
    'refresh',
    'inFullscreen',
    {
      name: 'addUser',
      label: t('system.user.action.addUser'),
      icon: '',
      enable: () => {},
      click: () => {
        selectUserDialog.value.show({ userGrid: userGridRef, orgTreeGridRef: orgTreeGridRef });
      },
    },
    {
      name: 'addAllUser',
      label: t('system.user.action.addAllUser'),
      icon: '',
      enable: () => {},
      click: () => {
        const orgId = orgTreeGridRef.value.getSelected()[0];
        axios
          .post(Environment.apiContextPath('/api/system/org/addAllUsers'), {
            one: orgId,
            many: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/user/queryUsersByOrg?orgId=') + orgId).then((response) => {
              userGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeUser',
      label: t('system.user.action.removeUser'),
      icon: '',
      enable: () => {},
      click: () => {
        const orgId = orgTreeGridRef.value.getSelected()[0];
        const userIds = [];
        for (const user of userGridRef.value.getSelectedRows()) {
          userIds.push(user.id);
        }
        axios
          .post(Environment.apiContextPath('/api/system/org/removeUsers'), {
            one: orgId,
            many: userIds,
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/user/queryUsersByOrg?orgId=') + orgId).then((response) => {
              userGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeAllUser',
      label: t('system.user.action.removeAllUser'),
      icon: '',
      enable: () => {},
      click: () => {
        const orgId = orgTreeGridRef.value.getSelected()[0];
        axios
          .post(Environment.apiContextPath('/api/system/org/removeAllUsers'), {
            one: orgId,
            many: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/user/queryUsersByOrg?orgId=') + orgId).then((response) => {
              userGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
  ],
  tableColumns: [
    { width: 100, name: 'loginName', label: t('loginName') },
    { width: 100, name: 'userName', label: t('userName') },
    { width: 80, name: 'enable', label: t('isEnable'), format: (value) => (value ? t('yes') : t('no')) },
  ],
};

const orgConfigure = {
  actions: [
    {
      name: 'refresh',
      label: t('refresh'),
      click: () => {},
    },
    {
      name: 'expandAll',
      label: t('expandAll'),
      click: () => {},
    },
    {
      name: 'selectAll',
      label: t('selectAll'),
      click: () => {},
    },
    {
      name: 'addRoot',
      label: t('addRoot'),
      click: () => {},
    },
    {
      name: 'addChild',
      label: t('addChild'),
      click: () => {},
    },
    {
      name: 'edit',
      label: t('edit'),
      click: () => {},
    },
    {
      name: 'delete',
      label: t('delete'),
      click: () => {},
    },
  ],
};

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

const orgSelected = (target) => {
  selectedOrgId = target;
  if (userGridRef.value) {
    axios.get(Environment.apiContextPath('/api/system/user/queryUsersByOrg?orgId=') + selectedOrgId).then((response) => {
      userGridRef.value.replaceRowsFun(response.data.content);
    });
  }
  if (menuTreeGridRef.value) {
    axios.get(Environment.apiContextPath('/api/system/menu/listAllMenusWithSelectedStatusByOrg?orgId=') + selectedOrgId).then((response) => {
      menuTreeGridRef.value.setNodes(response.data);
    });
  }
};

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