<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <DeptTree class="w-1/3 xl:w-1/4" @select="handleSelect" />
    <BasicTable @register="registerTable" class="w-2/3 xl:w-3/4">
      <template #toolbar>
        <a-button type="primary" v-auth="'user:add'" @click="handleCreate">{{
          t('新增用户')
        }}</a-button>
        <a-button type="default" v-auth="'user:resetPassword'" @click="handleReset">{{
          t('重置密码')
        }}</a-button>
          <a-button type="default" v-auth="'user:syncOrgAndUser'" @click="handleSync">{{
              t('同步组织人员')
          }}</a-button>
        <a-button type="default" v-auth="'user:unlock'" @click="handleLock">
          {{ lockText }}
        </a-button>
      </template>
      <template #action="{ record, index }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              auth: 'menu:edit',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              auth: 'menu:delete',
              color: 'error',
              popConfirm: {
                title: t('是否确认删除'),
                visible: popVisible(index),
                onVisibleChange: handleVisibleChange.bind(null, index),
                confirm: handleDelete.bind(null, record),
                cancel: handleCancel,
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, h, ref, computed } from 'vue';
  import { BasicTable, useTable, TableAction, FormSchema, BasicColumn } from '/@/components/Table';
  import { getUserPageList, deleteUser, resetUserPassword, userEnabled, syncOrgAndUser } from '/@/api/system/user';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';

  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: 'isSearchAll',
          label: t('全局搜索'),
          component: 'Checkbox',
          colProps: { style:'width:100px;' },
      },
    {
      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,
      sorter: true,
      align: 'left',
    },
    {
      title: t('姓名'),
      dataIndex: 'name',
      width: 120,
      sorter: true,
      align: 'left',
    },
    {
      title: t('编号'),
      dataIndex: 'code',
      width: 120,
      sorter: true,
      align: 'left',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      width: 80,
      sorter: true,
      align: 'left',
      customRender: ({ record }) => {
        return record.gender === 1 ? '男' : record.gender === 0 ? '女' : '';
      },
    },
    {
      title: t('手机号码'),
      dataIndex: 'mobile',
      width: 120,
      align: 'left',
      sorter: true,
    },

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

  export default defineComponent({
    name: 'UserManagement',
    components: { BasicTable, PageWrapper, DeptTree, AccountModal, TableAction },
    setup() {
      const { notification } = useMessage();
      const selectDeptId = ref('');
      const isVisible = ref<boolean>(false);
      const deleteIndex = ref();
      const [registerModal, { openModal }] = useModal();
      const [registerTable, { reload, getSelectRows, setSelectedRowKeys }] = useTable({
        title: t('用户列表'),
        api: getUserPageList,
        rowKey: 'id',
        columns,
        formConfig: {
          rowProps: {
            gutter: 16,
          },
          schemas: searchFormSchema,
          showResetButton: false,
        },
        rowSelection: {
          type: 'radio',
        },
        beforeFetch: (params) => {
          //发送请求默认新增  左边树结构所选机构id
          return params.isSearchAll?{...params}:{ ...params, departmentId: selectDeptId.value };
        },
        useSearchForm: true,
        showTableSetting: true,
        striped: false,
        actionColumn: {
          width: 80,
          title: t('操作'),
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        tableSetting: {
          size: false,
          setting: false,
        },
      });

      const lockText = computed(() => {
        return getSelectRows()?.length && !getSelectRows()[0].enabledMark ? '解锁' : '锁定';
      });

      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 (process.env.NODE_ENV === 'production') {
          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 handleSync(){
          syncOrgAndUser("fromDataCenter");
          notification.success({
              message: t('开始同步组织和人员，请稍后刷新页面查看结果'),
              description: t('成功'),
          });
      }
      function handleReset() {
        if (process.env.NODE_ENV === 'production') {
          notification.warning({
            message: '在线环境暂不允许该操作，请联系管理员。',
          });
          return;
        }
        let rows = warning();
        if (!rows) {
          return;
        }
        resetUserPassword(rows.id).then(() => {
          notification.success({
            message: t('重置密码成功'),
            description: t('成功'),
          });
        });
      }
      async function handleLock() {
        let rows = warning();
        if (!rows) {
          return;
        }
        await userEnabled(rows.id);
        notification.success({
          message: getSelectRows()[0].enabledMark ? '锁定成功' : t('解锁成功'),
          description: t('成功'),
        });
        await reload();
        setSelectedRowKeys([rows.id]);
      }
      function warning() {
        const selectRows = getSelectRows();
        if (selectRows.length === 0) {
          notification.warning({
            message: t('警告'),
            description: t('必须选中一行！'),
          }); //提示消息
          return false;
        } else {
          return selectRows[0];
        }
      }
      function handleSuccess() {
        reload();
      }

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

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