import { useLocalStorageState, useRequest } from "ahooks";
import { Input, Table, Spin, Typography, Flex, Space } from "antd";
import type { XCXFindUser, XCXFindUserResp } from "../types";
import User from "../components/User";
import { SEX } from "../utils";
import dayjs from "dayjs";

export function FindUserPage() {
  const [searchKey, setSearchKey] = useLocalStorageState<string>('findUser:searchKey');
  const findUserReq = useRequest(async (page: number = 1) => {
    const findOutUsers: XCXFindUserResp = await (await fetch(`/api/user/find?page=${page}&key=${searchKey}`)).json();
    return findOutUsers;
  }, { manual: true, refreshDeps: [searchKey], cacheKey: 'findUser:result' });
  return (
    <div className="app">
      <Typography.Title level={1}>查找用户</Typography.Title>
      <Spin spinning={findUserReq.loading}>
        <Flex vertical gap={48} align="center">
        <Input.Search
          allowClear
          size="large"
          placeholder="输入昵称或姓名查找"
          value={searchKey}
          onChange={e => setSearchKey(e.target.value)}
          onSearch={async () => findUserReq.runAsync()}
        />
        <Table
          size="small"
          style={{ width: '100%' }}
          rowKey={e => e.uid}
          dataSource={findUserReq.data?.data}
          pagination={{
            total: findUserReq.data?.total,
            current: findUserReq.data?.current_page,
            pageSize: findUserReq.data?.per_page,
            onChange(page) {
              findUserReq.run(page);
            },
          }}
        >
          <Table.Column
            align="center"
            title="昵称/姓名"
            dataIndex={'username2'}
            render={(username2, { realname, uid }: XCXFindUser) => (
              <User
                uid={uid}
                name={`${username2}${(realname && username2 !== realname) ? `（${realname}）` : ''}`}
              />
            )}
          />
          <Table.Column align="center" title="积分" dataIndex={'score'} />
          <Table.Column align="center" title="地区" dataIndex={'resideprovince'} />
          <Table.Column align="center" title="性别" dataIndex={'sex'} render={sex => SEX[sex]} />
          <Table.Column align="center" title="年龄" dataIndex={'birthyear'} render={year => year !== '0' ? dayjs().diff(dayjs(year), 'year') : '-'} />
        </Table>
        </Flex>
      </Spin>
    </div>
  );
}