<template>
  <div>
    <q-splitter :model-value="60" class="w-full h-full">
      <template #before>
        <div class="pr-1">
          <w-grid
            ref="userGridRef"
            :title="$t('system.user.grid.title')"
            :config-button="true"
            selection="multiple"
            :checkbox-selection="true"
            :data-url="Environment.apiContextPath('/api/system/user')"
            :pagination="{
              sortBy: 'loginName',
              descending: false,
            }"
            :query-form-cols-num="3"
            :query-form-fields="[
              { name: 'loginName', label: $t('loginName'), type: 'text' },
              { name: 'userName', label: $t('userName'), type: 'text' },
              { name: 'enable', label: $t('isEnable'), type: 'select', options: Options.yesNo(), queryOperator: 'equals' },
            ]"
            :toolbar-configure="{ noIcon: false }"
            :toolbar-actions="[
              'query',
              'refresh',
              'separator',
              'add',
              'clone',
              'edit',
              'remove',
              'separator',
              {
                name: 'setPassword',
                label: $t('system.user.grid.toolbar.setPassword'),
                icon: 'bi-shield-check',
                enableIf: function (selecteds) {
                  return selecteds.length > 0;
                },
                click: function (selecteds) {
                  setPasswordDialogRef.open('setPassword', selecteds);
                },
              },
              {
                name: 'setAllPassword',
                label: $t('system.user.grid.toolbar.setAllPassword'),
                icon: 'bi-shield',
                enableIf: function (selecteds) {
                  return true;
                },
                click: function () {
                  setPasswordDialogRef.open('setAllPassword');
                },
              },
              'separator',
              {
                name: 'resetPassword',
                label: $t('system.user.grid.toolbar.resetPassword'),
                icon: 'bi-shield-fill-check',
                enableIf: function (selecteds) {
                  return selecteds.length > 0;
                },
                click: function (selecteds) {
                  DialogManager.confirm($t('system.user.grid.toolbar.resetPassword.tip'), () => {
                    const userIds = Tools.extractProperties(selecteds, 'id');
                    axios.post(Environment.apiContextPath('/api/system/user/resetPassword'), userIds).then(() => {
                      NotifyManager.info($t('operationSuccess'));
                    });
                  });
                },
              },
              {
                name: 'resetAllPassword',
                label: $t('system.user.grid.toolbar.resetAllPassword'),
                icon: 'bi-shield-fill',
                enableIf: function (selecteds) {
                  return true;
                },
                click: function () {
                  DialogManager.confirm($t('system.user.grid.toolbar.resetAllPassword.tip'), () => {
                    axios.post(Environment.apiContextPath('/api/system/user/resetAllPassword')).then(() => {
                      setPasswordDialogRef.value.hide();
                      NotifyManager.info($t('operationSuccess'));
                    });
                  });
                },
              },
              'separator',
              'view',
              'separator',
              'export',
            ]"
            :columns="[
              { width: 150, name: 'loginName', label: $t('loginName') },
              { width: '100%', name: 'userName', label: $t('userName') },
              {
                width: 150,
                name: 'enable',
                label: $t('status'),
                format: (value, row) => {
                  return {
                    componentType: UserStatusTag,
                    attrs: row,
                  };
                },
              },
              { width: 100, name: 'lastModifier', label: $t('lastModifier') },
              { width: 110, name: 'lastModifyDate', label: $t('lastModifyDate'), format: Formater.dateOnly() },
            ]"
            :editor="{
              dialog: {
                width: '600px',
                height: '610px',
              },
              form: {
                colsNum: 4,
                fields: [
                  { name: 'loginName', label: $t('loginName'), type: 'text', required: true, colspan: 4 },
                  { name: 'userName', label: $t('userName'), type: 'text', required: true, colspan: 4 },
                  { name: 'description', label: $t('description'), type: 'textarea', rows: 1, colspan: 4 },
                  { name: 'password', label: $t('password'), type: 'password', colspan: 4 },
                  {
                    name: 'confirmPassword',
                    label: $t('confirmPassword'),
                    type: 'password',
                    colspan: 4,
                    rules: [
                      (value) => {
                        return Tools.stringEquals(userGridRef.getEditorForm().getData().password, value) ? true : $t('passwordAndConfirmPasswordMustEqual');
                      },
                    ],
                  },
                  { name: 'mobile', label: $t('mobile'), type: 'text', colsFirst: true, colspan: 4 },
                  { name: 'phone', label: $t('phone'), type: 'text', colsFirst: true, colspan: 4 },
                  { name: 'email', label: $t('email'), type: 'text', colsFirst: true, colspan: 4 },
                  { name: 'weixin', label: $t('weixin'), type: 'text', colsFirst: true, colspan: 4 },
                  { name: 'qq', label: $t('qq'), type: 'text', colsFirst: true, colspan: 4 },

                  { name: 'enable', label: $t('enable'), type: 'checkbox', defaultValue: true },
                  { name: 'accountExpired', label: $t('accountExpired'), type: 'checkbox', defaultValue: false },
                  { name: 'accountLocked', label: $t('accountLocked'), type: 'checkbox', defaultValue: false },
                  { name: 'credentialsExpired', label: $t('credentialsExpired'), type: 'checkbox', defaultValue: false },
                ],
              },
            }"
            :viewer="{
              panel: {
                columnNum: 1,
                fields: [
                  { name: 'id', label: $t('id') },
                  { name: 'loginName', label: $t('loginName') },
                  { name: 'userName', label: $t('userName') },
                  { name: 'description', label: $t('description') },
                  { name: 'enable', label: $t('enable'), format: Formater.none() },
                  { name: 'accountExpired', label: $t('accountExpired') },
                  { name: 'accountLocked', label: $t('accountLocked') },
                  { name: 'credentialsExpired', label: $t('credentialsExpired') },
                  { name: 'email', label: $t('email') },
                  { name: 'phone', label: $t('phone') },
                  { name: 'mobile', label: $t('mobile') },
                  { name: 'weixin', label: $t('weixin') },
                  { name: 'qq', label: $t('qq') },
                  { 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) => {
                currentSelectedUserId = row.id;
                roleGridRef?.refresh();
                orgTreeGridRef?.refresh();
              }
            "
            @before-request-data="
              () => {
                currentSelectedUserId = '';
                roleGridRef?.refresh();
                orgTreeGridRef?.refresh();
              }
            "
          ></w-grid>
        </div>
      </template>
      <template #after>
        <div class="pl-1">
          <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0" no-caps>
            <q-tab name="role" icon="bi-people" :label="$t('role')" />
            <q-tab name="org" icon="bi-diagram-3" :label="$t('org')" />
          </q-tabs>

          <q-tab-panels v-model="selectedTabRef" animated swipeable keep-alive>
            <q-tab-panel name="role" class="px-0">
              <SelectRoleGrid
                ref="roleGridRef"
                :fetch-data-url="Environment.apiContextPath('/api/system/role/queryRolesByUser')"
                :fetch-other-data-url="Environment.apiContextPath('/api/system/role/queryOtherRolesByUser')"
                foreign-key="userId"
                :foreign-value="currentSelectedUserId"
                @select-in="selectIn"
                @select-out="selectOut"
                @select-all-in="selectAllIn"
                @select-all-out="selectAllOut"
              ></SelectRoleGrid>
            </q-tab-panel>
            <q-tab-panel name="org" class="px-0">
              <SelectOrgTreeGrid
                ref="orgTreeGridRef"
                :fetch-data-url="Environment.apiContextPath('/api/system/org/listAllOrgsWithSelectedStatusByUser')"
                foreign-key="userId"
                :foreign-value="currentSelectedUserId"
                @update="update"
              ></SelectOrgTreeGrid>
            </q-tab-panel>
          </q-tab-panels>
        </div>
      </template>
    </q-splitter>
    <SetPasswordDialog ref="setPasswordDialogRef"></SetPasswordDialog>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Environment, axios, NotifyManager, DialogManager, Formater, Options, Tools } from 'platform-core';
import SelectRoleGrid from '../shared/SelectRoleGrid.vue';
import SelectOrgTreeGrid from '../shared/SelectOrgTreeGrid.vue';
import UserStatusTag from '../shared/UserStatusTag.vue';
import SetPasswordDialog from './SetPasswordDialog.vue';

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

const selectedTabRef = ref('role');
const setPasswordDialogRef = ref();
const currentSelectedUserId = ref('');

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

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

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

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

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