<template>
  <q-splitter :model-value="60" class="w-full" style="height: 100%">
    <template #before>
      <div class="pr-1" style="height: 100%">
        <w-grid
          ref="roleGridRef"
          :title="$t('system.role.grid.title')"
          :config-button="true"
          selection="multiple"
          :checkbox-selection="true"
          :data-url="Environment.apiContextPath('/api/system/role')"
          :pagination="{
            sortBy: 'name',
            descending: false,
          }"
          :query-form-cols-num="3"
          :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() },
          ]"
          :toolbar-configure="{ noIcon: false }"
          :toolbar-actions="['query', 'refresh', 'separator', 'add', 'clone', 'edit', 'remove', 'separator', 'view', 'separator', 'export']"
          :columns="[
            { width: 150, name: 'code', label: $t('code') },
            { width: '100%', name: 'name', label: $t('name') },
            { width: 80, name: 'enable', label: $t('status'), format: Formater.enableTag() },
            { 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.none() },
                { name: 'dataComeFrom', label: $t('dataComeFrom') },
                { name: 'creator', label: $t('creator') },
                { name: 'createDate', label: $t('createDate') },
                { name: 'lastModifier', label: $t('lastModifier') },
                { name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.none() },
                { name: 'corporationCode', label: $t('corporationCode') },
              ],
            },
          }"
          @row-click="
            (evt, row, index) => {
              currentSelectedRoleId = row.id;
              menuTreeGridRef?.refresh();
              userGridRef?.refresh();
            }
          "
          @before-request-data="
            () => {
              currentSelectedRoleId = '';
              menuTreeGridRef?.refresh();
              userGridRef?.refresh();
            }
          "
        >
        </w-grid>
      </div>
    </template>
    <template #after>
      <div class="pl-1" style="height: 100%">
        <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0" no-caps>
          <q-tab name="menu" icon="bi-menu-app" :label="$t('menu')" />
          <q-tab name="user" icon="bi-person" :label="$t('user')" />
        </q-tabs>

        <q-tab-panels v-model="selectedTabRef" animated swipeable keep-alive style="height: calc(100% - 48px)">
          <q-tab-panel name="menu" class="px-0 pb-0" style="height: 100%; padding-left: 0px; padding-right: 0px; padding-bottom: 0px">
            <SelectMenuTreeGrid
              ref="menuTreeGridRef"
              :fetch-data-url="Environment.apiContextPath('/api/system/menu/listAllMenusWithSelectedStatusByRole')"
              foreign-key="roleId"
              :foreign-value="currentSelectedRoleId"
              @update="update"
            ></SelectMenuTreeGrid>
          </q-tab-panel>

          <q-tab-panel name="user" class="px-0 pb-0" style="height: 100%; padding-left: 0px; padding-right: 0px; padding-bottom: 0px">
            <SelectUserGrid
              ref="userGridRef"
              :fetch-data-url="Environment.apiContextPath('/api/system/user/queryUsersByRole')"
              :fetch-other-data-url="Environment.apiContextPath('/api/system/user/queryOtherUsersByRole')"
              foreign-key="roleId"
              :foreign-value="currentSelectedRoleId"
              @select-in="selectIn"
              @select-out="selectOut"
              @select-all-in="selectAllIn"
              @select-all-out="selectAllOut"
            >
            </SelectUserGrid>
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </template>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Environment, axios, EnumTools, Options, Formater } from 'platform-core';
import SelectUserGrid from '../shared/SelectUserGrid.vue';
import SelectMenuTreeGrid from '../shared/SelectMenuTreeGrid.vue';

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

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

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

const selectIn = (ids: string[], gridComponent, dialogComponent) => {
  axios
    .post(Environment.apiContextPath('/api/system/role/addUsers'), {
      one: roleGridRef.value.getSelectedRows()[0].id,
      many: ids,
    })
    .then(() => {
      gridComponent?.refresh();
      dialogComponent?.close();
    });
};

const selectOut = (ids, gridComponent) => {
  axios
    .post(Environment.apiContextPath('/api/system/role/removeUsers'), {
      one: roleGridRef.value.getSelectedRows()[0].id,
      many: ids,
    })
    .then(() => {
      gridComponent?.refresh();
    });
};

const selectAllIn = (gridComponent) => {
  axios
    .post(Environment.apiContextPath('/api/system/role/addAllUsers'), {
      one: roleGridRef.value.getSelectedRows()[0].id,
      many: [],
    })
    .then(() => {
      gridComponent?.refresh();
    });
};

const selectAllOut = (gridComponent) => {
  axios
    .post(Environment.apiContextPath('/api/system/role/removeAllUsers'), {
      one: roleGridRef.value.getSelectedRows()[0].id,
      many: [],
    })
    .then(() => {
      gridComponent?.refresh();
    });
};

const update = (ids, gridComponent) => {
  axios
    .post(Environment.apiContextPath('/api/system/role/updateMenus'), {
      one: roleGridRef.value.getSelectedRows()[0].id,
      many: ids,
    })
    .then(() => {
      gridComponent.refresh();
    });
};
</script>
