<template>
  <q-splitter :model-value="65" class="w-full h-full">
    <template #before>
      <div class="px-1">
        <w-grid
          ref="userGridRef"
          :title="$t('system.user.grid.title')"
          selection="multiple"
          :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() },
            { name: 'dataComeFrom', label: $t('dataComeFrom'), type: 'select', options: Options.enum(DataComeFromEnum) },
          ]"
          :toolbar-configure="{ noIcon: false }"
          :toolbar-actions="[
            'query',
            'refresh',
            'separator',
            'add',
            'clone',
            'edit',
            'remove',
            'separator',
            {
              name: 'setPassword',
              label: $t('system.user.action.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.action.setAllPassword'),
              icon: 'bi-shield',
              enableIf: function (selecteds) {
                return true;
              },
              click: function () {
                setPasswordDialogRef.open('setAllPassword');
              },
            },
            'separator',
            {
              name: 'resetPassword',
              label: $t('system.user.action.resetPassword'),
              icon: 'bi-shield-fill-check',
              enableIf: function (selecteds) {
                return selecteds.length > 0;
              },
              click: function (selecteds) {
                DialogManager.confirm(t('system.user.confirm.resetPassword'), () => {
                  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.action.resetAllPassword'),
              icon: 'bi-shield-fill',
              enableIf: function (selecteds) {
                return true;
              },
              click: function () {
                DialogManager.confirm($t('system.user.confirm.resetAllPassword'), () => {
                  axios.post(Environment.apiContextPath('/api/system/user/resetAllPassword')).then(() => {
                    setPasswordDialogRef.value.hide();
                    NotifyManager.info($t('operationSuccess'));
                  });
                });
              },
            },
            'separator',
            'view',
            'export',
          ]"
          :data-url="Environment.apiContextPath('/api/system/user')"
          row-key="id"
          :columns="[
            { name: 'loginName', label: $t('loginName') },
            { name: 'userName', label: $t('userName') },
            {
              name: 'status',
              label: $t('status'),
              format: (value, row) => {
                return {
                  componentType: UserStatusTag,
                  attrs: row,
                };
              },
            },
            { name: 'dataComeFrom', label: $t('dataComeFrom'), format: Formater.enum(DataComeFromEnum) },
            { name: 'lastModifier', label: $t('lastModifier') },
            { 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.getAddEditFormRef().value.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.yesNo() },
                { name: 'accountExpired', label: $t('accountExpired'), format: Formater.yesNo() },
                { name: 'accountLocked', label: $t('accountLocked'), format: Formater.yesNo() },
                { name: 'credentialsExpired', label: $t('credentialsExpired'), format: Formater.yesNo() },
                { 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: 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) => {
              console.log(row.id);
              currentSelectedUserId = row.id;
              roleGridRef?.refresh();
              orgTreeGridRef?.refresh();
            }
          "
        ></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" class="px-0">
            <w-grid
              ref="roleGridRef"
              :title="$t('system.role.grid.title')"
              :data-url="Environment.apiContextPath('/api/system/role/queryRolesByUser') + currentSelectedUserId"
              :auto-fetch-data="false"
              selection="multiple"
              :full-screen-button="false"
              :toolbar-configure="{ noIcon: true }"
              :toolbar-actions="[
                'refresh',
                'separator',
                {
                  name: 'addRole',
                  label: $t('system.role.action.addRole'),
                  enableIf: () => {
                    if (userGridRef) {
                      return userGridRef.getSelectedRows().length > 0;
                    }
                    return false;
                  },
                  click: () => {
                    selectRoleDialog.open({ userId: userGridRef.getSelectedRows()[0].id, userGrid: userGridRef, roleGrid: roleGridRef });
                  },
                },
                {
                  name: 'addAllRole',
                  label: $t('system.role.action.addAllRole'),
                  enableIf: () => {
                    if (userGridRef) {
                      return userGridRef.getSelectedRows().length > 0;
                    }
                    return false;
                  },
                  click: () => {
                    const selectedUser = userGridRef.getSelectedRows()[0];
                    DialogManager.confirm(
                      $t('system.role.action.addAllRole.confirm', { userLoginName: selectedUser.loginName, userName: selectedUser.userName }),
                      () => {
                        axios
                          .post(Environment.apiContextPath('/api/system/user/addAllRoles'), {
                            one: selectedUser.id,
                            many: [],
                          })
                          .then((response) => {
                            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + selectedUser.id).then((response) => {
                              roleGridRef.replaceRows(response.data.content);
                            });
                          });
                      },
                    );
                  },
                },
                'separator',
                {
                  name: 'removeRole',
                  label: $t('system.role.action.removeRole'),
                  enableIf: () => {
                    if (userGridRef && roleGridRef) {
                      return userGridRef.getSelectedRows().length > 0 && roleGridRef.getSelectedRows().length > 0;
                    }
                    return false;
                  },
                  click: (selecteds) => {
                    const selectedUser = userGridRef.getSelectedRows()[0];
                    const roleIds = Tools.extractProperties(selecteds, 'id');
                    const messageKey = roleIds.length > 1 ? 'system.role.action.removeRole.confirms' : 'system.role.action.removeRole.confirm';
                    DialogManager.confirm(
                      t(messageKey, {
                        userLoginName: selectedUser.loginName,
                        userName: selectedUser.userName,
                        roleCode: selecteds[0].code,
                        roleName: selecteds[0].name,
                        counter: selecteds.length,
                      }),
                      () => {
                        axios
                          .post(Environment.apiContextPath('/api/system/user/removeRoles'), {
                            one: selectedUser.id,
                            many: roleIds,
                          })
                          .then((response) => {
                            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + selectedUser.id).then((response) => {
                              roleGridRef.replaceRows(response.data.content);
                            });
                          });
                      },
                    );
                  },
                },
                {
                  name: 'removeAllRole',
                  label: $t('system.role.action.removeAllRole'),
                  enableIf: () => {
                    if (userGridRef && roleGridRef) {
                      return userGridRef.getSelectedRows().length > 0 && roleGridRef.getRows().length > 0;
                    }
                    return false;
                  },
                  click: () => {
                    const selectedUser = userGridRef.getSelectedRows()[0];
                    DialogManager.confirm(
                      t('system.role.action.removeAllRole.confirm', { userLoginName: selectedUser.loginName, userName: selectedUser.userName }),
                      () => {
                        axios
                          .post(Environment.apiContextPath('/api/system/user/removeAllRoles'), {
                            one: selectedUser.id,
                            many: [],
                          })
                          .then((response) => {
                            axios.get(Environment.apiContextPath('/api/system/role/queryRolesByUser?userId=') + selectedUser.id).then((response) => {
                              roleGridRef.replaceRows(response.data.content);
                            });
                          });
                      },
                    );
                  },
                },
                'separator',
                'view',
              ]"
              :columns="[
                { width: 100, name: 'code', label: $t('code') },
                { width: 100, name: 'name', label: $t('name') },
                {
                  width: 60,
                  name: 'status',
                  label: $t('status'),
                  format: (value, row) => {
                    return {
                      componentType: RoleStatusTag,
                      attrs: row,
                    };
                  },
                },
              ]"
              :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') },
                  ],
                },
              }"
            ></w-grid>
          </q-tab-panel>
          <q-tab-panel name="org" class="px-0">
            <w-grid
              ref="orgTreeGridRef"
              :tree="true"
              :title="$t('system.org.grid.title')"
              :data-url="Environment.apiContextPath('/api/system/org/listAllOrgsWithSelectedStatusByUser?userId=') + currentSelectedUserId"
              selection="multiple"
              :full-screen-button="false"
              :toolbar-configure="{ noIcon: true }"
              :toolbar-actions="[
                'refresh',
                'separator',
                {
                  name: 'save',
                  label: $t('save'),
                  click: () => {
                    axios
                      .post(Environment.apiContextPath('/api/system/user/updateOrgs'), {
                        one: currentSelectedUserId,
                        many: orgTreeGridRef.value.getTicked(),
                      })
                      .then((response) => {});
                  },
                },
                'view',
              ]"
              :pagination="{
                sortBy: 'name',
                descending: false,
                reqPageStart: 0,
                rowsPerPage: 0,
              }"
              :columns="[
                { width: 100, name: 'code', label: $t('code') },
                { width: 100, name: 'name', label: $t('name') },
                {
                  width: 60,
                  name: 'status',
                  label: $t('status'),
                  format: (value, row) => {
                    return {
                      componentType: RoleStatusTag,
                      attrs: row,
                    };
                  },
                },
              ]"
              :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') },
                  ],
                },
              }"
            ></w-grid>
          </q-tab-panel>
        </q-tab-panels>
      </div>
    </template>
    <SelectRoleDialog ref="selectRoleDialog"></SelectRoleDialog>
    <SetPasswordDialog ref="setPasswordDialogRef"></SetPasswordDialog>
  </q-splitter>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Environment, axios, EnumTools, NotifyManager, DialogManager, Formater, Options, Tools } from 'platform-core';
import SelectRoleDialog from './SelectRoleDialog.vue';
import SetPasswordDialog from './SetPasswordDialog.vue';
import UserStatusTag from './UserStatusTag.vue';
import RoleStatusTag from './RoleStatusTag.vue';

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

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

const DataComeFromEnum = await EnumTools.fetch('io.sc.platform.orm.api.enums.DataComeFrom');
const currentSelectedUserId = ref('');
</script>
