<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="tenantAdminDrawer"
    title="租户管理员"
    width="60%"
    @ok="handleSubmit"
  >
    <BasicTable @register="tenantAdminTable">
      <template #toolbar>
        <Authority value="api:yt:user:saveTenantAdmin:post">
          <a-button type="primary" @click="handleCreateTenantAdmin">新增租户管理员</a-button>
        </Authority>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '进入',
              icon: 'ant-design:login-outlined',
              tooltip: '以租户管理员身份登录',
              onClick: handleLoginTenantAdmin.bind(null, record),
            },
          ]"
          :drop-down-actions="[
            {
              label: '短信通知',
              icon: 'ant-design:send-outlined',
              tooltip: '发送通知短信',
              ifShow: record.phoneNumber != null && !record.hasPassword,
              popConfirm: {
                title: '是否需要发送通知短信',
                confirm: handleSendMsg.bind(null, record),
              },
            },
            {
              label: '清除密码',
              icon: 'ant-design:clear-outlined',
              tooltip: '清除密码',
              ifShow: record.hasPassword,
              popConfirm: {
                title: '是否需要清除密码',
                confirm: handleResetPassword.bind(null, record),
              },
            },
            {
              label: '编辑',
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              auth: 'api:yt:user:saveTenantAdmin:update',
              onClick: handleEdit.bind(null, record),
            },
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              tooltip: '删除',
              auth: 'api:yt:admin:user:deleteTenantAdmin:delete',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
      <template #status="{ record }">
        <Tag
          :color="
            record.userStatusEnum === 'NORMAL'
              ? 'green'
              : record.userStatusEnum === 'DISABLED'
              ? 'red'
              : 'orange'
          "
        >
          {{
            record.userStatusEnum === 'NORMAL'
              ? '正常'
              : record.userStatusEnum === 'DISABLED'
              ? '已禁用'
              : '已过期'
          }}
        </Tag>
      </template>
    </BasicTable>
    <TenantAdminFormDrawer @register="tenantAdminFormDrawer" @success="handleSuccess" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicDrawer, useDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicColumn, BasicTable, TableAction, useTable } from '/@/components/Table';
  import {
    deleteTenantAdmin,
    getTenantAdminPage,
    resetPassword,
    sendMessageOrEmail,
  } from '/@/api/tenant/tenantApi';
  import { Tag } from 'ant-design-vue';
  import TenantAdminFormDrawer from './TenantAdminFormDrawer.vue';
  import { MessageTypeEnum, SendResetPasswordEmailMsg } from '/@/api/tenant/tenantInfo';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Authority } from '/@/components/Authority';
  import { getMyInfo, getPermCode, getUserToken } from '/@/api/sys/user';
  import { useUserStore } from '/@/store/modules/user';
  import { usePermissionStore } from '/@/store/modules/permission';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { useGo } from '/@/hooks/web/usePage';
  import { PageEnum } from '/@/enums/pageEnum';
  import { router } from '/@/router';
  import { RouteRecordRaw } from 'vue-router';
  import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';

  export default defineComponent({
    name: 'TenantAdminDrawer',
    components: {
      BasicDrawer,
      BasicTable,
      TenantAdminFormDrawer,
      Tag,
      TableAction,
      Authority,
    },
    emits: ['register'],
    setup() {
      const { createMessage } = useMessage();
      const [tenantAdminFormDrawer, { openDrawer: openTenantAdminFormDrawer }] = useDrawer();

      const tenantId = ref('');
      async function handleCreateTenantAdmin() {
        const { items } = await getTenantAdminPage({
          page: 1,
          pageSize: 1000,
          tenantId: tenantId.value,
        });
        openTenantAdminFormDrawer(true, {
          isUpdate: false,
          tenantId: tenantId.value,
          judgeExistUserName: items,
        });
      }

      function handleEdit(record: Recordable) {
        openTenantAdminFormDrawer(true, {
          isUpdate: true,
          record,
          tenantId: tenantId.value,
        });
      }

      function handleDelete(record: Recordable) {
        deleteTenantAdmin([record.id]).then(() => {
          createMessage.success('删除成功');
          handleSuccess();
        });
      }

      function handleResetPassword(record: Recordable) {
        resetPassword(record.id).then(() => {
          createMessage.success('清空密码成功');
          handleSuccess();
        });
      }
      function handleSendMsg(record: Recordable) {
        const req = new SendResetPasswordEmailMsg(record.id, MessageTypeEnum.PHONE_MESSAGE);
        sendMessageOrEmail(req).then(() => {
          createMessage.success('短信发送成功');
          handleSuccess();
        });
      }

      const tenantAdminColumns: BasicColumn[] = [
        {
          title: '用户名',
          dataIndex: 'username',
          width: 50,
        },
        {
          title: '真实名字',
          dataIndex: 'realName',
          width: 50,
        },
        {
          title: '电话号码',
          dataIndex: 'phoneNumber',
          width: 50,
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          width: 70,
        },
        {
          title: '状态',
          dataIndex: 'userStatus',
          width: 30,
          slots: { customRender: 'status' },
        },
      ];
      const [tenantAdminTable, { reload }] = useTable({
        api: getTenantAdminPage,
        columns: tenantAdminColumns,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        searchInfo: {
          tenantId,
        },
        actionColumn: {
          width: 100,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });

      let firstEnterFlag = true;
      //默认传递页面数据
      const [tenantAdminDrawer, { closeDrawer }] = useDrawerInner(async (data) => {
        tenantId.value = data.record.tenantId;
        !firstEnterFlag && reload();
        if (firstEnterFlag) {
          firstEnterFlag = false;
        }
      });

      //提交按钮
      async function handleSubmit() {
        closeDrawer(); //关闭侧框
      }

      function handleSuccess() {
        reload();
      }

      const userStore = useUserStore();
      const permissionStore = usePermissionStore();
      const go = useGo();
      async function handleLoginTenantAdmin(record: { tbUser: string; id: string }) {
        try {
          const { token, refreshToken } = await getUserToken(record.id);
          userStore.storeToken(token, refreshToken);
          const userInfo = await getMyInfo();
          const permissionList = await getPermCode();
          permissionStore.setPermCodeList(permissionList);
          userStore.setUserInfo(userInfo);
          userStore.setRoleList(userInfo.roles as RoleEnum[]);
          const routes = await permissionStore.buildRoutesAction();
          routes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);
          go(PageEnum.BASE_HOME);
        } catch (error) {
        } finally {
        }
      }

      return {
        tenantAdminDrawer,
        handleCreateTenantAdmin,
        handleSubmit,
        tenantAdminTable,
        tenantId,
        tenantAdminFormDrawer,
        handleSuccess,
        handleEdit,
        handleDelete,
        handleResetPassword,
        handleSendMsg,
        handleLoginTenantAdmin,
      };
    },
  });
</script>
