<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerSelectUserModal"
    title="选择用户"
    @ok="handleSubmit"
    width="1000px"
  >
    <BasicTable @register="registerTable" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getUserPageList } from '/@/api/system/user';
  import { useTable, FormSchema, BasicColumn, BasicTable } from '/@/components/FormTable';

  const searchFormSchema: FormSchema[] = [
    {
      field: 'name',
      label: '姓名',
      component: 'Input',
      colProps: { span: 8 },
    },
    {
      field: 'code',
      label: '编码',
      component: 'Input',
      colProps: { span: 8 },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 120,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: 120,
    },
    {
      title: '性别',
      dataIndex: 'code',
      width: 120,
    },
    {
      title: '手机号码',
      dataIndex: 'mobile',
      width: 120,
    },
    {
      title: '部门',
      dataIndex: 'departmentName',
      width: 180,
    },
  ];

  const emit = defineEmits(['success', 'register']);

  const [registerTable, { getSelectRows, setSelectedRowKeys }] = useTable({
    title: '账号列表',
    api: getUserPageList,
    canResize: false,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 50,
      schemas: searchFormSchema,
    },
    rowSelection: {
      type: 'checkbox',
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
  });

  const [registerSelectUserModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    if (data.selectIds && data.selectIds.length > 0) {
      setSelectedRowKeys(data.selectIds);
    } else {
      setSelectedRowKeys([]);
    }
  });

  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      const selectRows = getSelectRows();

      closeModal();
      emit('success', selectRows);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
