<template>
  <q-splitter :model-value="70" class="w-full h-full">
    <template #before>
      <platform-grid
        ref="roleGridRef"
        :table-props="{ borderded: false, flat: true }"
        :query-form-cols-number="roleConfigure.queryFormColsNumber"
        :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"
        :add-form-props="roleConfigure.addFormProps"
        :table-dense="false"
        @row-click="roleConfigure.rowClickFun"
      >
      </platform-grid>
    </template>
    <template #after>
      <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0">
        <q-tab name="menu" icon="bi-people" :label="$t('menu')" />
        <q-tab name="user" icon="bi-diagram-3" :label="$t('user')" />
      </q-tabs>

      <q-tab-panels v-model="selectedTabRef" animated swipeable keep-alive>
        <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-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-panels>
    </template>
    <SelectUserDialog ref="selectUserDialog" title="可选用户列表" :maximized="false" width="50%" height="500px"></SelectUserDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Environment, axios } from 'platform-core';
import SelectUserDialog from './SelectUserDialog.vue';

const { t } = useI18n();

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

const selectUserDialog = ref();
const selectedTabRef = ref('menu');

const roleConfigure = {
  queryFormColsNumber: 4,
  queryFormColsAuto: false,
  queryFormFields: [
    { label: t('code'), modelName: 'code', type: 'text' },
    { label: t('name'), modelName: 'name', type: 'text' },
    {
      label: t('enable'),
      modelName: 'enable',
      type: 'select',
      options: [
        { value: true, label: '是' },
        { value: false, label: '否' },
      ],
    },
    {
      label: t('dataComeFrom'),
      modelName: 'dataComeFrom',
      type: 'select',
      options: [
        { value: 'MANUAL', label: t('io.sc.platform.orm.api.enums.DataComeFrom.MANUAL') },
        { value: 'AUTO', label: t('io.sc.platform.orm.api.enums.DataComeFrom.AUTO') },
      ],
    },
  ],
  hideBottom: false,
  tableInitLoadData: true,
  tableLeftColumnStickyNumber: 0,
  tableTitle: t('system.role.gridTitle'),
  tableRowKey: 'id',
  tableDataUrl: Environment.apiContextPath('/api/system/role'),
  tablePagination: {
    sortBy: 'lastModifyDate',
    descending: true,
    reqPageStart: 0,
    rowsPerPage: 10,
  },
  tableButtons: ['query', 'reset', 'separator', 'refresh', 'add', 'edit', 'delete', 'separator', 'view', 'separator', 'inFullscreen'],
  tableColumns: [
    { width: 100, name: 'code', label: t('code') },
    { width: 100, name: 'name', label: t('name') },
    { width: 100, name: 'enable', label: t('isEnable'), format: (value) => (value ? t('yes') : t('no')) },
    { width: 100, name: 'dataComeFrom', label: t('dataComeFrom') },
    { width: 110, name: 'lastModifier', label: t('lastModifier') },
    { width: 115, name: 'lastModifyDate', label: t('lastModifyDate') },
  ],
  addFormProps: {
    dialogInitWidth: '50%',
    dialogInitHeight: '90%',
    formColsNumber: 1,
    formColsAuto: false,
    formFields: [
      { modelName: 'code', label: t('code'), type: 'text', required: true },
      { modelName: 'name', label: t('name'), type: 'text', required: true },
      { modelName: 'description', label: t('description'), type: 'textarea' },
    ],
  },
  rowClickFun: (evt, row, index) => {
    // 设置单击表格行选中记录，当开启表格的选择模式为多选时，此处的清空当前已选择行代码注释，只保留push方法即可。
    roleGridRef.value.getSelectedRows().splice(0, roleGridRef.value.getSelectedRows().length);
    roleGridRef.value.getSelectedRows().push(row);
    if (menuTreeGridRef.value) {
      axios.get(Environment.apiContextPath('/api/system/menu/listAllMenusWithSelectedStatusByRole?roleId=') + row.id).then((response) => {
        menuTreeGridRef.value.setNodes(response.data);
      });
    }
    if (userGridRef.value) {
      axios.get(Environment.apiContextPath('/api/system/user/queryUsersByRole?roleId=') + row.id).then((response) => {
        userGridRef.value.replaceRowsFun(response.data.content);
      });
    }
  },
};

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: () => {
        if (roleGridRef.value) {
          return roleGridRef.value.getSelectedRows().length > 0;
        }
        return false;
      },
      click: () => {
        selectUserDialog.value.show({ userGrid: userGridRef, roleGrid: roleGridRef });
      },
    },
    {
      name: 'addAllUser',
      label: t('system.user.action.addAllUser'),
      icon: '',
      enable: () => {},
      click: () => {
        axios
          .post(Environment.apiContextPath('/api/system/role/addAllUsers'), {
            one: roleGridRef.value.getSelectedRows()[0].id,
            many: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/user/queryUsersByRole?roleId=') + roleGridRef.value.getSelectedRows()[0].id).then((response) => {
              userGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeUser',
      label: t('system.user.action.removeUser'),
      icon: '',
      enable: () => {},
      click: () => {
        const userIds = [];
        for (const user of userGridRef.value.getSelectedRows()) {
          userIds.push(user.id);
        }
        axios
          .post(Environment.apiContextPath('/api/system/role/removeUsers'), {
            one: roleGridRef.value.getSelectedRows()[0].id,
            many: userIds,
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/user/queryUsersByRole?roleId=') + roleGridRef.value.getSelectedRows()[0].id).then((response) => {
              userGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeAllUser',
      label: t('system.user.action.removeAllUser'),
      icon: '',
      enable: () => {},
      click: () => {
        axios
          .post(Environment.apiContextPath('/api/system/role/removeAllUsers'), {
            one: roleGridRef.value.getSelectedRows()[0].id,
            many: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/user/queryUsersByRole?roleId=') + roleGridRef.value.getSelectedRows()[0].id).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 menuConfigure = {
  actions: [
    {
      name: 'save',
      label: '保存',
      click: () => {
        axios
          .post(Environment.apiContextPath('/api/system/role/updateMenus'), {
            one: roleGridRef.value.getSelectedRows()[0].id,
            many: menuTreeGridRef.value.getTicked(),
          })
          .then((response) => {});
      },
    },
  ],
};
</script>
