import { useAjax } from '@/Hook/useAjax';
import { App, Button, Flex, Input, InputProps, Modal, Space, Table, Tag } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { getAutoLinkBookListApi, GetAutoLinkBookListProps } from '../../API/bookLink';
import { SearchOutlined } from '@ant-design/icons';

interface SelectBookProps extends InputProps {
    platformKey: string,
    hanldeSearchChapter?: () => void;
    searchChapterLoading?: boolean;
    searchChapterDisabled?: boolean;
    isSearchChapter?: boolean;
}

/**
 * 书籍选择
 * @param param0 
 * @returns 
 */
const SelectBook: React.FC<SelectBookProps> = ({ platformKey, value, onChange, hanldeSearchChapter, searchChapterLoading, searchChapterDisabled, isSearchChapter = true, ...rest }) => {

    /*******************************************/
    const { message } = App.useApp()
    const [visible, setVisible] = useState<boolean>(false)
    const [queryForm, setQueryForm] = useState<GetAutoLinkBookListProps>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<GetAutoLinkBookListProps>({ pageNum: 1, pageSize: 20 })
    const [selectedRows, setSelectedRows] = useState<any[]>([])

    const getAutoLinkBookList = useAjax((params) => getAutoLinkBookListApi(params))
    /*******************************************/

    useEffect(() => {
        if (visible && platformKey) {
            getAutoLinkBookList.run({ ...queryFormNew, platformKey })
        }
    }, [visible, queryFormNew, platformKey])

    const handleOk = useCallback(() => {
        if (selectedRows.length) {
            onChange?.(selectedRows[0])
            setVisible(false)
            setSelectedRows([])
        } else {
            message.warning('请选择书籍')
        }
    }, [selectedRows])

    return <>
        <Flex gap={10}>
            <Space.Compact style={{ width: '100%' }}>
                <Input
                    placeholder="请输入作品(书籍)ID"
                    style={{ width: '100%' }}
                    {...rest}
                    value={value}
                    onChange={onChange}
                />
                <Button type="primary" disabled={!platformKey} onClick={() => setVisible(true)}>选择书</Button>
            </Space.Compact>
            {isSearchChapter && <Button type="primary" loading={searchChapterLoading} disabled={searchChapterDisabled} onClick={() => hanldeSearchChapter?.()}>查询章节列表</Button>}
        </Flex>
        {visible && <Modal
            title={<strong>选择书籍</strong>}
            open={visible}
            onCancel={() => {
                setVisible(false)
                setSelectedRows([]);
            }}
            onOk={handleOk}
            width={600}
        >
            <Flex gap={6} style={{ marginBottom: 10 }}>
                <Input placeholder='书籍名称' allowClear value={queryForm.bookName} onChange={(e) => setQueryForm({ ...queryForm, bookName: e.target.value, pageNum: 1 })} />
                <Input placeholder='书籍ID' allowClear value={queryForm.bookId} onChange={(e) => setQueryForm({ ...queryForm, bookId: e.target.value, pageNum: 1 })} />
                <Button type="primary" onClick={() => {
                    setQueryFormNew({ ...queryForm })
                }} loading={getAutoLinkBookList.loading} icon={<SearchOutlined />}>搜索</Button>
            </Flex>
            <Table
                dataSource={getAutoLinkBookList?.data?.data?.records}
                columns={[
                    {
                        title: '书籍',
                        dataIndex: 'bookName',
                        key: 'bookName',
                        render: (value, records: any) => {
                            return <span style={{ fontSize: 12 }}>{value}（{records.bookId}）</span>
                        }
                    },
                ]}
                bordered
                pagination={{
                    total: getAutoLinkBookList.data?.data?.total,
                    showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                    showSizeChanger: true,
                    showLessItems: true,
                    defaultCurrent: 1,
                    defaultPageSize: 20,//默认初始的每页条数
                    current: getAutoLinkBookList?.data?.data?.current || 1,
                    pageSize: getAutoLinkBookList?.data?.data?.size || 20,
                    onChange: (page, pageSize) => {
                        setQueryForm({ ...queryForm, pageNum: page, pageSize })
                        setQueryFormNew({ ...queryFormNew, pageNum: page, pageSize })
                    }
                }}
                rowKey={'bookId'}
                size='small'
                loading={getAutoLinkBookList?.loading}
                scroll={{ y: 400 }}
                rowSelection={{
                    selectedRowKeys: selectedRows,
                    type: 'radio',
                    onChange(selectedRowKeys) {
                        setSelectedRows(selectedRowKeys)
                    },
                }}
            />
        </Modal>}
    </>
};

export default React.memo(SelectBook);