import { useAjax } from "@/Hook/useAjax"
import { Button, Col, Input, Modal, Row, Space, Table, Tag, Typography } from "antd"
import React, { useEffect, useState } from "react"
import { getBookListApi } from "../../API/global"

interface Props {
    platformKey?: string
    value?: string[],
    onChange?: (value?: string[]) => void
}

/**
 * 选择书籍
 * @returns 
 */
const SelectBook: React.FC<Props> = ({ platformKey, value, onChange }) => {

    /**************************************/
    const [queryForm, setQueryForm] = useState<{ pageNum: number, pageSize: number, bookName?: string }>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<{ pageNum: number, pageSize: number, bookName?: string }>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState<boolean>(false)
    const [selectedRow, setSelectedRow] = useState<any[]>([])//选择下发企微号

    const getBookList = useAjax((params) => getBookListApi(params))
    /**************************************/

    useEffect(() => {
        if (value && value?.length > 0) {
            setSelectedRow(value.map(item => ({ bookName: item })))
        } else {
            setSelectedRow([])
        }
    }, [value])

    useEffect(() => {
        if (platformKey) {
            getBookList.run({ ...queryForm, platformKey })
        }
    }, [queryForm, platformKey])

    const handleOk = () => {
        onChange?.(selectedRow?.length > 0 ? selectedRow.map(item => item.bookName) : undefined)
        setVisible(false)
    }

    return <div style={{ width: '100%', display: 'flex', alignItems: 'center' }}>
        {(value && value?.length > 0) && <div style={{ maxWidth: 'calc(100% - 72px)', marginRight: 8 }}><Typography.Text ellipsis={{ tooltip: true }}>{value?.toString()}</Typography.Text></div>}
        <Button type="primary" disabled={!platformKey} onClick={() => { setQueryForm({ ...queryForm, pageNum: 1 }); setVisible(true) }}>{(value && value?.length > 0) ? '修改书籍' : '选择书籍'}</Button>

        {visible && <Modal
            title="选择书籍"
            open={visible}
            onCancel={() => setVisible(false)}
            onOk={handleOk}
        >
            <Space direction="vertical" style={{ width: '100%' }}>
                <Space>
                    <Input placeholder="请输入书名" allowClear value={queryFormNew?.bookName} onChange={(e) => setQueryFormNew({ ...queryFormNew, bookName: e.target.value, pageNum: 1 })} />
                    <Button type="primary" onClick={() => setQueryForm({ ...queryFormNew })}>搜索</Button>
                </Space>
                <Row>
                    <Col span={17}>
                        <Table
                            style={{ marginBottom: 1 }}
                            dataSource={getBookList?.data?.data?.records?.map((item: any, index: number) => ({ bookName: item, id: item + '_' + index }))}
                            columns={[{
                                title: '书名',
                                dataIndex: 'bookName',
                                key: 'bookName',
                            }]}
                            scroll={{ y: 400 }}
                            rowKey={'bookName'}
                            size='small'
                            loading={getBookList.loading}
                            bordered
                            rowSelection={{
                                type: 'checkbox',
                                onSelect: (rocord, selected, rows) => {
                                    if (selected) {
                                        setSelectedRow([...selectedRow, rocord])
                                    } else {
                                        setSelectedRow(selectedRow?.filter(item => item.bookName !== rocord?.bookName))
                                    }
                                },
                                onSelectAll: (selected, _, changeRows) => {
                                    if (selected) {
                                        setSelectedRow([...selectedRow, ...changeRows])
                                    } else {
                                        let arr = selectedRow?.filter(item => changeRows?.every(i => i.bookName !== item.bookName))
                                        setSelectedRow(arr)
                                    }
                                },
                                selectedRowKeys: selectedRow?.map(item => item?.bookName),
                                getCheckboxProps: (record: any) => ({
                                    name: record?.bookName
                                }),
                            }}
                            pagination={{
                                total: getBookList?.data?.data?.total,
                                showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
                                showSizeChanger: true,
                                showLessItems: true,
                                defaultCurrent: 1,
                                defaultPageSize: 200,//默认初始的每页条数
                                current: getBookList?.data?.data?.current || 1,
                                pageSize: getBookList?.data?.data?.size || 20,
                                onChange: (page, pageSize) => {
                                    setQueryForm({ ...queryForm, pageNum: page, pageSize })
                                }
                            }}
                        />
                    </Col>
                    <Col span={7} style={{ paddingLeft: 6 }}>
                        <Space style={{ width: '100%' }} direction="vertical">
                            <div style={{ display: 'flex', justifyContent: 'space-between' }}><Typography.Text>已选：({selectedRow.length || 0})</Typography.Text><a onClick={() => { setSelectedRow([]) }}>清空选择</a></div>
                            <div style={{ maxHeight: 430, overflow: 'hidden', overflowY: 'auto' }}>
                                {selectedRow?.map(item => {
                                    return <div key={item?.bookName} style={{ marginBottom: 5 }}>
                                        <Tag closable onClose={(e) => {
                                            e.preventDefault();
                                            setSelectedRow([...selectedRow.filter(s => s?.bookName !== item?.bookName)])
                                        }} style={{ padding: 5 }}>
                                            <div style={{ maxWidth: 110, display: 'inline-block' }}><Typography.Text ellipsis={{ tooltip: true }}>{item?.bookName}</Typography.Text></div>
                                        </Tag>
                                    </div>
                                })}
                            </div>
                        </Space>
                    </Col>
                </Row>
            </Space>
        </Modal>}
    </div>
}

export default React.memo(SelectBook)