<template>
  <q-splitter :model-value="70" class="w-full h-full">
    <template #before>
      <platform-grid
        ref="userGridRef"
        :table-props="{ borderded: false, flat: true }"
        :query-form-cols-number="userConfigure.queryFormColsNumber"
        :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"
        :add-form-props="userConfigure.addFormProps"
        :table-dense="false"
        @row-click="userConfigure.rowClickFun"
      >
      </platform-grid>
    </template>
    <template #after>
      <q-tabs v-model="selectedTabRef" inline-label align="left" :breakpoint="0">
        <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">
          <platform-grid
            ref="roleGridRef"
            :table-props="{ borderded: false, flat: true }"
            :query-form-cols-number="roleConfigure.queryFormColsNumber"
            :hide-bottom="roleConfigure.hideBottom"
            :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"
            table-selection="multiple"
            :table-dense="false"
          >
          </platform-grid>
        </q-tab-panel>
        <q-tab-panel name="org">
          <w-tree-grid ref="orgTreeGridRef" label-key="name" :actions="orgConfigure.actions" tick-strategy="leaf" />
        </q-tab-panel>
      </q-tab-panels>
    </template>
    <SelectRoleDialog ref="selectRoleDialog" title="可选角色列表" :maximized="false" width="50%" height="500px"></SelectRoleDialog>
    <ChangePasswordDialog ref="changePasswordDialog" title="修改密码" :maximized="false" width="450px" height="350px"></ChangePasswordDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Environment, axios } from 'platform-core';
import SelectRoleDialog from './SelectRoleDialog.vue';
import ChangePasswordDialog from './ChangePasswordDialog.vue';

const { t } = useI18n();

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

const selectRoleDialog = ref();
const changePasswordDialog = ref();

const selectedTabRef = ref('role');

const userConfigure = {
  queryFormColsNumber: 4,
  queryFormColsAuto: false,
  queryFormFields: [
    { label: t('loginName'), modelName: 'loginName', type: 'text' },
    { label: t('userName'), modelName: 'userName', 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.user.gridTitle'),
  tableRowKey: 'id',
  tableDataUrl: Environment.apiContextPath('/api/system/user'),
  tablePagination: {
    sortBy: 'lastModifyDate',
    descending: true,
    reqPageStart: 0,
    rowsPerPage: 10,
  },
  tableButtons: [
    'query',
    'reset',
    'separator',
    'refresh',
    'add',
    'edit',
    'delete',
    'separator',
    'view',
    'separator',
    {
      name: 'setPassword',
      label: t('system.user.action.setPassword'),
      icon: 'bi-shield-exclamation',
      enableIf: function () {},
      click: function () {
        changePasswordDialog.value.show();
      },
    },
    'inFullscreen',
  ],
  tableColumns: [
    { width: 100, name: 'loginName', label: t('loginName') },
    { width: 100, name: 'userName', label: t('userName') },
    { width: 100, name: 'enable', label: t('isEnable'), format: (value) => (value ? t('yes') : t('no')) },
    { width: 100, name: 'dataComeFrom', label: t('dataComeFrom') },
    { width: 100, name: 'accountExpired', label: t('accountExpired'), format: (value) => (value ? t('yes') : t('no')) },
    { width: 100, name: 'accountLocked', label: t('accountLocked'), format: (value) => (value ? t('yes') : t('no')) },
    { width: 120, name: 'credentialsExpired', label: t('credentialsExpired'), format: (value) => (value ? t('yes') : t('no')) },
    { 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: 'loginName', label: t('loginName'), type: 'text', required: true },
      { modelName: 'userName', label: t('userName'), type: 'text', required: true },
      { modelName: 'password', label: t('password'), type: 'text' },
      { modelName: 'confirmPassword', label: t('confirmPassword'), type: 'text' },
      { modelName: 'description', label: t('description'), type: 'textarea' },
      { modelName: 'email', label: t('email'), type: 'text' },
      { modelName: 'phone', label: t('phone'), type: 'text' },
      { modelName: 'mobile', label: t('mobile'), type: 'text' },
      { modelName: 'weixin', label: t('weixin'), type: 'text' },
      { modelName: 'qq', label: t('qq'), type: 'text' },
      { modelName: 'accountExpired', label: t('accountExpired'), type: 'checkbox' },
      { modelName: 'accountLocked', label: t('accountLocked'), type: 'checkbox' },
      { modelName: 'credentialsExpired', label: t('credentialsExpired'), type: 'checkbox' },
    ],
  },
  rowClickFun: (evt, row, index) => {
    // 设置单击表格行选中记录，当开启表格的选择模式为多选时，此处的清空当前已选择行代码注释，只保留push方法即可。
    userGridRef.value.getSelectedRows().splice(0, userGridRef.value.getSelectedRows().length);
    userGridRef.value.getSelectedRows().push(row);
    if (roleGridRef.value) {
      axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + row.id).then((response) => {
        roleGridRef.value.replaceRowsFun(response.data.content);
      });
    }
    if (orgTreeGridRef.value) {
      axios.get(Environment.apiContextPath('/api/system/org/listAllOrgsWithSelectedStatusByUser?userId=') + row.id).then((response) => {
        orgTreeGridRef.value.setNodes(response.data);
      });
    }
  },
};

const roleConfigure = {
  queryFormColsNumber: 4,
  queryFormColsAuto: false,
  queryFormFields: [],
  hideBottom: true,
  tableInitLoadData: false,
  tableLeftColumnStickyNumber: 0,
  tableTitle: t('system.role.gridTitle'),
  tableRowKey: 'id',
  tableDataUrl: '',
  tablePagination: {
    sortBy: 'lastModifyDate',
    descending: true,
    reqPageStart: 0,
    rowsPerPage: 0,
  },
  tableButtons: [
    'refresh',
    'inFullscreen',
    {
      name: 'addRole',
      label: t('system.role.action.addRole'),
      icon: '',
      enable: () => {
        if (userGridRef.value) {
          return userGridRef.value.getSelectedRows().length > 0;
        }
        return false;
      },
      click: () => {
        selectRoleDialog.value.show({ userGrid: userGridRef, roleGrid: roleGridRef });
      },
    },
    {
      name: 'addAllRole',
      label: t('system.role.action.addAllRole'),
      icon: '',
      enable: () => {
        if (userGridRef.value) {
          console.log(userGridRef.value.getSelectedRows());
          return userGridRef.value.getSelectedRows().length > 0;
        }
        return false;
      },
      click: () => {
        axios
          .post(Environment.apiContextPath('/api/system/user/addAllRoles'), {
            one: userGridRef.value.getSelectedRows()[0].id,
            many: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + userGridRef.value.getSelectedRows()[0].id).then((response) => {
              roleGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeRole',
      label: t('system.role.action.removeRole'),
      icon: '',
      enable: () => {
        if (userGridRef.value) {
          return userGridRef.value.getSelectedRows().length > 0;
        }
        return false;
      },
      click: () => {
        const roleIds = [];
        for (const role of roleGridRef.value.getSelectedRows()) {
          roleIds.push(role.id);
        }
        axios
          .post(Environment.apiContextPath('/api/system/user/removeRoles'), {
            one: userGridRef.value.getSelectedRows()[0].id,
            many: roleIds,
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + userGridRef.value.getSelectedRows()[0].id).then((response) => {
              roleGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
    {
      name: 'removeAllRole',
      label: t('system.role.action.removeAllRole'),
      icon: '',
      enable: () => {
        if (userGridRef.value) {
          return userGridRef.value.getSelectedRows().length > 0;
        }
        return false;
      },
      click: () => {
        axios
          .post(Environment.apiContextPath('/api/system/user/removeAllRoles'), {
            one: userGridRef.value.getSelectedRows()[0].id,
            many: [],
          })
          .then((response) => {
            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + userGridRef.value.getSelectedRows()[0].id).then((response) => {
              roleGridRef.value.replaceRowsFun(response.data.content);
            });
          });
      },
    },
  ],
  tableColumns: [
    { width: 100, name: 'code', label: t('code') },
    { width: 100, name: 'name', label: t('name') },
    { width: 80, name: 'enable', label: t('isEnable'), format: (value) => (value ? t('yes') : t('no')) },
  ],
};

const orgConfigure = {
  actions: [
    {
      name: 'save',
      label: '保存',
      click: () => {
        axios
          .post(Environment.apiContextPath('/api/system/user/updateOrgs'), {
            one: userGridRef.value.getSelectedRows()[0].id,
            many: orgTreeGridRef.value.getTicked(),
          })
          .then((response) => {});
      },
    },
  ],
};
</script>
