<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-tab name="authorization" icon="bi-diagram-3" label="权限" />
      </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-panel name="authorization">
          <q-splitter v-model="splitterModel">
            <template #before>
              <q-tabs v-model="authorizationModel" vertical>
                <q-tab name="统计报表-减值结果" label="统计报表-减值结果" />
                <q-tab name="统计报表-阶段迁徙分析" label="统计报表-阶段迁徙分析" />
                <q-tab name="统计报表-三分类汇总" label="统计报表-三分类汇总" />
                <q-tab name="统计报表-阶段汇总" label="统计报表-阶段汇总" />
                <q-tab name="用户管理" label="用户管理" />
                <q-tab name="公告管理" label="公告管理" />
                <q-tab name="消息管理" label="消息管理" />
                <q-tab name="参数管理" label="参数管理" />
                <q-tab name="数据字典" label="数据字典" />
                <q-tab name="国际化多语言" label="国际化多语言" />
                <q-tab name="流程管理" label="流程管理" />
              </q-tabs>
            </template>

            <template #after>
              <q-tab-panels v-model="authorizationModel" animated swipeable vertical transition-prev="jump-up" transition-next="jump-up">
                <q-tab-panel name="统计报表-减值结果">
                  <q-checkbox v-model="authorizationReactive.query" label="查询" />
                  <q-checkbox v-model="authorizationReactive.query" label="报表导出" />
                </q-tab-panel>

                <q-tab-panel name="用户管理">
                  <q-checkbox v-model="authorizationReactive.query" label="查询" />
                  <q-checkbox v-model="authorizationReactive.query" label="新增" />
                  <q-checkbox v-model="authorizationReactive.query" label="复制" />
                  <q-checkbox v-model="authorizationReactive.query" label="修改" />
                  <q-checkbox v-model="authorizationReactive.query" label="删除" />
                  <q-checkbox v-model="authorizationReactive.query" label="查看" />
                  <q-checkbox v-model="authorizationReactive.query" label="数据导入" />
                  <q-checkbox v-model="authorizationReactive.query" label="流程审批" />
                </q-tab-panel>
              </q-tab-panels>
              <div class="row justify-end items-start content-start">
                <q-btn label="保存" outline></q-btn>
              </div>
            </template>
          </q-splitter>
        </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, reactive } 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 authorizationReactive = reactive({
  query: true,
  add: true,
});
const splitterModel = ref(40);
const authorizationModel = ref('统计报表-减值结果');

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>
