<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <DeptTree @select="handleSelect" />
    </template>
    <template #resizeRight>
      <BasicTable @register="registerTable" isMenuTable>
        <template #toolbar>
          <a-button type="primary" v-auth="'user:add'" @click="handleCreate">{{
            t('新增用户')
          }}</a-button>
        </template>
        <template #action="{ record, index }">
          <TableAction
            :actions="[
              {
                label: record.enabledMark === 1 ? '锁定' : '解锁',
                auth: 'user:unlock',
                onClick: handleLock.bind(null, record),
              },
              {
                label: '重置密码',
                auth: 'user:resetPassword',
                onClick: handleReset.bind(null, record),
              },
              {
                label: '编辑',
                auth: 'user:edit',
                onClick: handleEdit.bind(null, record),
              },
              {
                label: '删除',
                auth: 'user:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  visible: popVisible(index),
                  onVisibleChange: handleVisibleChange.bind(null, index),
                  confirm: handleDelete.bind(null, record),
                  cancel: handleCancel,
                },
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </ResizePageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { getUserPageList, deleteUser, resetUserPassword, userEnabled } from '/@/api/system/user';
  import { ResizePageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { usePermission } from '/@/hooks/web/usePermission';

  import { useModal } from '/@/components/Modal';
  import AccountModal from './components/UserModal.vue';
  import DeptTree from './components/DeptTree.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { Tag } from 'ant-design-vue';
  const { t } = useI18n();
  export const searchFormSchema: FormSchema[] = [
    {
      field: 'userName',
      label: t('用户名'),
      component: 'Input',
      colProps: { lg: 8, md: 24 },
    },
    {
      field: 'name',
      label: t('姓名'),
      component: 'Input',
      colProps: { lg: 8, md: 24 },
    },
    {
      field: 'code',
      label: t('编号'),
      component: 'Input',
      colProps: { lg: 8, md: 24 },
    },
    {
      field: 'mobile',
      label: t('手机号码'),
      component: 'Input',
      colProps: { lg: 8, md: 24 },
    },
  ];

  export const columns: BasicColumn[] = [
    {
      title: t('用户名'),
      dataIndex: 'userName',
      width: 120,
      resizable: true,
    },
    {
      title: t('姓名'),
      dataIndex: 'name',
      width: 120,
      resizable: true,
    },
    {
      title: t('编号'),
      dataIndex: 'code',
      width: 120,
      resizable: true,
    },
    {
      title: '性别',
      dataIndex: 'gender',
      width: 80,
      resizable: true,
      customRender: ({ record }) => {
        return record.gender === 1 ? '男' : record.gender === 0 ? '女' : '';
      },
    },
    {
      title: t('手机号码'),
      dataIndex: 'mobile',
      width: 120,
      resizable: true,
    },

    {
      title: t('邮箱'),
      dataIndex: 'email',
      width: 180,
      resizable: true,
    },
    {
      title: t('登录状态'),
      dataIndex: 'enabledMark',
      width: 100,
      customRender: ({ record }) => {
        const enable = record.enabledMark;
        const color = enable === 1 ? 'blue' : 'red';
        const text = enable === 1 ? '正常' : '锁定';
        return h(Tag, { color: color }, () => text);
      },
      resizable: true,
    },
    {
      title: t('备注'),
      dataIndex: 'remark',
      resizable: true,
    },
  ];

  export default defineComponent({
    name: 'UserManagement',
    components: { BasicTable, ResizePageWrapper, DeptTree, AccountModal, TableAction },
    setup() {
      const { notification } = useMessage();
      const { hasPermission } = usePermission();

      const selectDeptId = ref('');
      const isVisible = ref<boolean>(false);
      const deleteIndex = ref();
      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload }] = useTable({
        title: t('用户列表'),
        api: getUserPageList,
        rowKey: 'id',
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          showResetButton: false,
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return { ...params, departmentId: selectDeptId.value };
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        actionColumn: {
          width: 210,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
        },
        customRow: (record) => {
          return {
            ondblclick: () => {
              if (hasPermission('user:edit')) {
                handleEdit(record);
              }
            },
          };
        },
      });

      function popVisible(index) {
        return isVisible.value && index === deleteIndex.value;
      }

      function handleCreate() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          id: record.id,
          isUpdate: true,
        });
      }

      function handleVisibleChange(index, bool) {
        if (!bool) {
          isVisible.value = false;
          return;
        }
        if (import.meta.env.VITE_GLOB_PRODUCTION === 'true') {
          notification.warning({
            message: '在线环境暂不允许该操作，请联系管理员。',
          });
          return;
        }
        isVisible.value = true;
        deleteIndex.value = index;
      }

      function handleDelete(record: Recordable) {
        isVisible.value = false;
        deleteUser([record.id]).then((_) => {
          reload();
          notification.success({
            message: t('删除'),
            description: t('成功'),
          }); //提示消息
        });
      }
      function handleCancel() {
        isVisible.value = false;
      }
      function handleReset(record) {
        if (import.meta.env.VITE_GLOB_PRODUCTION === 'true') {
          notification.warning({
            message: '在线环境暂不允许该操作，请联系管理员。',
          });
          return;
        }
        resetUserPassword(record.id).then(() => {
          notification.success({
            message: t('重置密码成功'),
            description: t('成功'),
          });
        });
      }
      async function handleLock(record) {
        await userEnabled(record.id);
        notification.success({
          message: record.enabledMark ? '锁定成功' : t('解锁成功'),
          description: t('成功'),
        });
        await reload();
      }
      function handleSuccess() {
        reload();
      }

      function handleSelect(deptId = '') {
        selectDeptId.value = deptId;
        reload();
      }

      return {
        registerTable,
        registerModal,
        popVisible,
        handleVisibleChange,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        handleReset,
        handleLock,
        handleCancel,
        t,
      };
    },
  });
</script>
