<template>
  <Ok @wsp="wsp"></Ok>
  <q-splitter :model-value="70" class="w-full h-full">
    <template #before>
      <div class="px-1">
        <w-grid
          ref="userGridRef"
          :title="userGrid.title"
          selection="multiple"
          :query-form-fields="userGrid.queryFormFields"
          :toolbar-actions="userGrid.toolbarActions"
          :toolbar-configure="userGrid.toolbarConfigure"
          :data-url="userGrid.dataUrl"
          :columns="userGrid.columns"
          :row-key="userGrid.rowKey"
          :editor="userGrid.editor"
          :viewer="userGrid.viewer"
          @row-click="userGrid.rowClick"
        ></w-grid>
      </div>
    </template>
    <template #after>
      <div class="px-1">
        <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>
      </div>
    </template>
    <SelectRoleDialog ref="selectRoleDialog" title="可选角色列表" :maximized="false" width="50%" height="500px"></SelectRoleDialog>
    <w-dialog
      ref="changePasswordDialogRef"
      title="修改密码"
      width="500px"
      height="250px"
      :buttons="[
        {
          label: $t('submit'),
          click: () => {
            console.log(changePasswordFormRef.getData());
            axios.post(Environment.apiContextPath('/api/system/user/changePassword'), changePasswordFormRef.getData()).then(() => {
              changePasswordDialogRef.hide();
            });
          },
        },
      ]"
    >
      <w-form
        ref="changePasswordFormRef"
        :cols-num="1"
        :fields="[
          { name: 'rawPassword', label: $t('rawPassword'), type: 'password' },
          { name: 'newPassword', label: $t('newPassword'), type: 'password' },
          { name: 'confirmNewPassword', label: $t('confirmNewPassword'), type: 'password' },
        ]"
        class="p-2"
      ></w-form>
    </w-dialog>
    <ChangePasswordDialog ref="changePasswordDialog2" title="修改密码" :maximized="false" width="450px" height="350px"></ChangePasswordDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref, toRaw } from 'vue';
import { useI18n } from 'vue-i18n';
import { QBtn } from 'quasar';
import { Environment, axios, EnumTools } from 'platform-core';
import SelectRoleDialog from './SelectRoleDialog.vue';
import ChangePasswordDialog from './ChangePasswordDialog.vue';
import UserStatusTag from './UserStatusTag.vue';
import Ok from './Ok.vue';

const { t } = useI18n();

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

const selectRoleDialog = ref();
const changePasswordDialogRef = ref();
const changePasswordFormRef = ref();

const selectedTabRef = ref('role');

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

const wsp = (v1, ss) => {
  console.log(v1.ok(), v1.hello, ss);
};

const userGrid = {
  title: t('system.user.gridTitle'),
  queryFormFields: [
    { name: 'loginName', label: t('loginName'), type: 'text' },
    { name: 'userName', label: t('userName'), type: 'text' },
    { name: 'enable', label: t('isEnable'), type: 'select', options: YesNoEnum.list },
    { name: 'dataComeFrom', label: t('dataComeFrom'), type: 'select', options: DataComeFromEnum.list },
  ],
  toolbarConfigure: { noIcon: false },
  toolbarActions: [
    'query',
    'refresh',
    'separator',
    'add',
    'edit',
    'remove',
    'separator',
    {
      name: 'setPassword',
      label: t('system.user.action.setPassword'),
      icon: 'bi-shield-exclamation',
      enableIf: function (selected) {
        return selected.length > 0;
      },
      click: function () {
        changePasswordDialogRef.value.show();
      },
    },
    'view',
    'export',
  ],
  dataUrl: Environment.apiContextPath('/api/system/user'),
  rowKey: 'id',
  columns: [
    { name: 'loginName', label: t('loginName') },
    { name: 'userName', label: t('userName') },
    //{ width: 100, name: 'enable', label: t('isEnable'), align: 'center', format: (value) => YesNoEnum.map[value] },
    //{ width: 100, name: 'accountExpired', label: t('accountExpired'), format: (value) => YesNoEnum.map[value] },
    //{ width: 100, name: 'accountLocked', label: t('accountLocked'), format: (value) => YesNoEnum.map[value] },
    //{ width: 160, name: 'credentialsExpired', label: t('credentialsExpired'), format: (value) => YesNoEnum.map[value] },
    {
      name: 'status',
      label: t('status'),
      format: (value, row) => {
        return {
          componentType: UserStatusTag,
          attrs: row,
        };
      },
    },
    { name: 'dataComeFrom', label: t('dataComeFrom'), format: (value) => DataComeFromEnum.map[value] },
    { name: 'lastModifier', label: t('lastModifier') },
    { name: 'lastModifyDate', label: t('lastModifyDate') },
  ],
  editor: {
    dialog: {},
    form: {
      colsNum: 2,
      fields: [
        { name: 'loginName', label: t('loginName'), type: 'text', required: true },
        { name: 'userName', label: t('userName'), type: 'text', required: true },
        { name: 'description', label: t('description'), type: 'textarea', colspan: 2, rows: 1 },
        { name: 'password', label: t('password'), type: 'password' },
        { name: 'confirmPassword', label: t('confirmPassword'), type: 'password' },
        { name: 'mobile', label: t('mobile'), type: 'text' },
        { name: 'phone', label: t('phone'), type: 'text' },
        { name: 'email', label: t('email'), type: 'text' },
        { name: 'weixin', label: t('weixin'), type: 'text' },
        { name: 'qq', label: t('qq'), type: 'text' },
        { name: 'enable', label: t('enable'), type: 'checkbox', defaultValue: true, colsFirst: true },
        { name: 'accountExpired', label: t('accountExpired'), type: 'checkbox', defaultValue: false, colsFirst: true },
        { name: 'accountLocked', label: t('accountLocked'), type: 'checkbox', defaultValue: false, colsFirst: true },
        { name: 'credentialsExpired', label: t('credentialsExpired'), type: 'checkbox', defaultValue: false, colsFirst: true },
      ],
    },
  },
  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') },
        { 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'), format: (value) => DataComeFromEnum.map[value] },
        { 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') },
      ],
    },
  },
  rowClick: (evt, row, index) => {
    if (roleGridRef.value) {
      axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + row.id).then((response) => {
        //roleGridRef.value.replaceRows(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>
