<template>
  <q-splitter :model-value="60" class="w-full h-full">
    <template #before>
      <div class="pr-1">
        <w-grid
          ref="orgTreeGridRef"
          :tree="true"
          :title="$t('system.org.grid.title')"
          dense-body
          :data-url="Environment.apiContextPath('/api/system/org')"
          selection="multiple"
          :checkbox-selection="false"
          :pageable="false"
          :tree-icon="
            (row) => {
              return { name: 'folder', color: 'amber' };
            }
          "
          :toolbar-configure="{ noIcon: false }"
          :toolbar-actions="['refresh', 'separator', ['addTop', 'addChild'], 'edit', 'remove', 'separator', 'view', 'export']"
          :columns="[
            { width: '100%', name: 'name', label: $t('name') },
            { width: 200, name: 'code', label: $t('code') },
            { width: 100, name: 'enable', label: $t('status'), sortable: false, format: Formater.enableTag() },
          ]"
          :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) => {
              currentSelectedOrgId = row.id;
              userGridRef?.refresh();
              menuTreeGridRef?.refresh();
            }
          "
        ></w-grid>
      </div>
    </template>
    <template #after>
      <div class="pl-1">
        <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" class="px-0">
            <SelectUserGrid
              ref="userGridRef"
              :fetch-data-url="Environment.apiContextPath('/api/system/user/queryUsersByOrg')"
              :fetch-other-data-url="Environment.apiContextPath('/api/system/user/queryOtherUsersByOrg')"
              foreign-key="orgId"
              :foreign-value="currentSelectedOrgId"
              @add="add"
              @remove="remove"
              @add-all="addAll"
              @remove-all="removeAll"
            >
            </SelectUserGrid>
          </q-tab-panel>
          <q-tab-panel name="menu" class="px-0">
            <SelectMenuTreeGrid
              ref="menuTreeGridRef"
              :fetch-data-url="Environment.apiContextPath('/api/system/menu/listAllMenusWithSelectedStatusByOrg')"
              foreign-key="orgId"
              :foreign-value="currentSelectedOrgId"
              @update="update"
            ></SelectMenuTreeGrid>
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </template>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Environment, axios, EnumTools, 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 orgTreeGridRef = ref();
const userGridRef = ref();
const menuTreeGridRef = ref();

const selectedTabRef = ref('user');
const currentSelectedOrgId = ref('');

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

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

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

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

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