<template>
  <q-splitter :model-value="60" class="w-full h-full">
    <template #before>
      <div class="px-1">
        <w-grid
          ref="roleGridRef"
          :title="$t('system.role.grid.title')"
          :data-url="Environment.apiContextPath('/api/system/role')"
          selection="multiple"
          :query-form-fields="[
            { name: 'code', label: $t('code'), type: 'text' },
            { name: 'name', label: $t('name'), type: 'text' },
            { name: 'enable', label: $t('isEnable'), type: 'select', options: Options.yesNo() },
            { name: 'dataComeFrom', label: $t('dataComeFrom'), type: 'select', options: Options.enum(DataComeFromEnum) },
          ]"
          :toolbar-configure="{ noIcon: false }"
          :toolbar-actions="['query', 'refresh', 'separator', 'add', 'clone', 'edit', 'remove', 'separator', 'view', 'export']"
          :columns="[
            { name: 'code', label: $t('code') },
            { name: 'name', label: $t('name') },
            { width: 80, name: 'status', label: $t('status'), format: Formater.enableTag() },
            { width: 100, name: 'dataComeFrom', label: $t('dataComeFrom'), format: Formater.enum(DataComeFromEnum) },
            { width: 120, name: 'lastModifier', label: $t('lastModifier') },
            { width: 120, name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.dateOnly() },
          ]"
          :editor="{
            dialog: {
              width: '600px',
              height: '300px',
            },
            form: {
              colsNum: 1,
              fields: [
                { name: 'code', label: $t('code'), type: 'text', required: true },
                { name: 'name', label: $t('name'), type: 'text', required: true },
                { name: 'description', label: $t('description'), type: 'textarea', rows: 1 },
                { name: 'enable', label: $t('enable'), type: 'checkbox', defaultValue: true },
              ],
            },
          }"
          :viewer="{
            panel: {
              columnNum: 1,
              fields: [
                { name: 'id', label: $t('id') },
                { name: 'code', label: $t('code') },
                { name: 'name', label: $t('name') },
                { name: 'description', label: $t('description') },
                { name: 'enable', label: $t('enable'), format: Formater.yesNo() },
                { name: 'dataComeFrom', label: $t('dataComeFrom'), format: Formater.enum(DataComeFromEnum) },
                { name: 'creator', label: $t('creator') },
                { name: 'createDate', label: $t('createDate') },
                { name: 'lastModifier', label: $t('lastModifier') },
                { name: 'lastModifyDate', label: $t('lastModifyDate') },
                { name: 'corporationCode', label: $t('corporationCode') },
              ],
            },
          }"
          @row-click="
            (evt, row, index) => {
              currentSelectedRoleId = row.id;
              userGridRef?.refresh();
              menuTreeGridRef?.refresh();
            }
          "
        >
        </w-grid>
      </div>
    </template>
    <template #after>
      <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0" no-caps>
        <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" class="px-0">
          <w-grid
            ref="menuTreeGridRef"
            :tree="true"
            :title="$t('system.org.grid.title')"
            :data-url="Environment.apiContextPath('/api/system/menu/listAllMenusWithSelectedStatusByRole?roleId=') + currentSelectedRoleId"
            selection="multiple"
            :pageable="false"
            :full-screen-button="false"
            :toolbar-configure="{ noIcon: true }"
            :toolbar-actions="[
              'refresh',
              'separator',
              {
                name: 'save',
                label: $t('save'),
                click: () => {
                  axios
                    .post(Environment.apiContextPath('/api/system/role/updateMenus'), {
                      one: userGridRef.getSelectedRows()[0].id,
                      many: menuTreeGridRef.getTicked(),
                    })
                    .then((response) => {});
                },
              },
              'view',
            ]"
            :columns="[
              {
                width: 100,
                name: 'titleI18nKey',
                label: $t('name'),
                format: (value, row) => {
                  return $t(value);
                },
              },
              { width: 60, name: 'enable', label: $t('status'), format: Formater.enableTag() },
            ]"
            :viewer="{
              panel: {
                columnNum: 1,
                fields: [
                  { name: 'id', label: $t('id') },
                  { name: 'code', label: $t('code') },
                  { name: 'name', label: $t('name') },
                  { name: 'description', label: $t('description') },
                  { name: 'enable', label: $t('enable'), format: Formater.yesNo() },
                  { name: 'dataComeFrom', label: $t('dataComeFrom'), format: Formater.enum(DataComeFromEnum) },
                  { name: 'creator', label: $t('creator') },
                  { name: 'createDate', label: $t('createDate') },
                  { name: 'lastModifier', label: $t('lastModifier') },
                  { name: 'lastModifyDate', label: $t('lastModifyDate') },
                  { name: 'corporationCode', label: $t('corporationCode') },
                ],
              },
            }"
          ></w-grid>
        </q-tab-panel>

        <q-tab-panel name="user" class="px-0">
          <w-grid
            ref="userGridRef"
            :title="$t('system.role.selectUser.grid.title')"
            :fetch-data-url="Environment.apiContextPath('/api/system/user/queryUsersByRole?roleId=') + currentSelectedRoleId"
            :auto-fetch-data="false"
            selection="multiple"
            :full-screen-button="false"
            :toolbar-configure="{ noIcon: true }"
            :toolbar-actions="[
              'refresh',
              'separator',
              {
                name: 'addUser',
                label: $t('system.role.selectUser.grid.toolbar.addUser'),
                enableIf: () => {
                  if (roleGridRef) {
                    return roleGridRef.getSelectedRows().length > 0;
                  }
                  return false;
                },
                click: () => {
                  selectUserDialog.open({ roleId: roleGridRef.getSelectedRows()[0].id, userGrid: userGridRef });
                },
              },
              {
                name: 'addAllUser',
                label: $t('system.role.selectUser.grid.toolbar.addAllUser'),
                enableIf: () => {
                  if (roleGridRef) {
                    return roleGridRef.getSelectedRows().length > 0;
                  }
                  return false;
                },
                click: () => {
                  const selectedRole = roleGridRef.getSelectedRows()[0];
                  DialogManager.confirm($t('system.role.selectUser.grid.toolbar.addAllUser.tip'), () => {
                    axios
                      .post(Environment.apiContextPath('/api/system/role/addAllUsers'), {
                        one: selectedRole.id,
                        many: [],
                      })
                      .then((response) => {
                        userGridRef?.refresh();
                      });
                  });
                },
              },
              'separator',
              {
                name: 'removeUser',
                label: $t('system.role.selectUser.grid.toolbar.removeUser'),
                enableIf: () => {
                  if (roleGridRef && userGridRef) {
                    return roleGridRef.getSelectedRows().length > 0 && userGridRef.getSelectedRows().length > 0;
                  }
                  return false;
                },
                click: (selecteds) => {
                  const selectedRole = roleGridRef.getSelectedRows()[0];
                  const userIds = Tools.extractProperties(selecteds, 'id');
                  DialogManager.confirm($t('system.role.selectUser.grid.toolbar.removeUser.tip'), () => {
                    axios
                      .post(Environment.apiContextPath('/api/system/role/removeUsers'), {
                        one: selectedRole.id,
                        many: userIds,
                      })
                      .then((response) => {
                        userGridRef?.refresh();
                      });
                  });
                },
              },
              {
                name: 'removeAllUser',
                label: $t('system.role.selectUser.grid.toolbar.removeAllUser'),
                enableIf: () => {
                  if (roleGridRef) {
                    return roleGridRef.getSelectedRows().length > 0;
                  }
                  return false;
                },
                click: () => {
                  const selectedRole = roleGridRef.getSelectedRows()[0];
                  DialogManager.confirm($t('system.role.selectUser.grid.toolbar.removeAllUser.tip'), () => {
                    axios
                      .post(Environment.apiContextPath('/api/system/role/removeAllUsers'), {
                        one: selectedRole.id,
                        many: [],
                      })
                      .then((response) => {
                        userGridRef?.refresh();
                      });
                  });
                },
              },
              'separator',
              'view',
            ]"
            :columns="[
              { width: 100, name: 'loginName', label: t('loginName') },
              { width: 100, name: 'userName', label: t('userName') },
              {
                name: 'status',
                label: $t('status'),
                format: (value, row) => {
                  return {
                    componentType: UserStatusTag,
                    attrs: row,
                  };
                },
              },
            ]"
          >
          </w-grid>
        </q-tab-panel>
      </q-tab-panels>
    </template>
    <SelectUserDialog ref="selectUserDialog"></SelectUserDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Environment, axios, DialogManager, Tools, EnumTools, Options, Formater } from 'platform-core';
import SelectUserDialog from './SelectUserDialog.vue';
import UserStatusTag from '../user/UserStatusTag.vue';

const { t } = useI18n();

const DataComeFromEnum = await EnumTools.fetch('io.sc.platform.orm.api.enums.DataComeFrom');

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

const selectUserDialog = ref();
const selectedTabRef = ref('user');
const currentSelectedRoleId = ref('');

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>
