import Tables from '@/components/Tables';
import { useAjax } from '@/Hook/useAjax';
import { getChatGameListApi, getChatListApi, getServerListApi } from '@/services/gameData/player';
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Space } from 'antd';
import React, { useEffect, useState } from 'react';
import style from '../../components/TableData/index.less'
import moment from 'moment';
import { DefaultOptionType } from 'antd/lib/select';
import columnsPos from './tableConfig';

const ChatList: React.FC = () => {

    /*********************************/
    const [form] = Form.useForm()
    const supperGameId = Form.useWatch('supperGameId', form)
    const [queryFrom, setQueryFrom] = React.useState<{ supperGameId: number, pageNum: number, pageSize: number, roleId?: string, roleName?: string, chatStart?: string, chatEnd?: string }>({ supperGameId: 0, pageNum: 1, pageSize: 20 })
    const [gameList, setGameList] = useState<DefaultOptionType[]>([])
    const [serverList, setServerList] = useState<DefaultOptionType[]>([])

    const getChatGameList = useAjax(() => getChatGameListApi())
    const getChatList = useAjax((params) => getChatListApi(params))
    const getServerList = useAjax((params) => getServerListApi(params))
    /*********************************/

    useEffect(() => {
        getChatGameList.run().then(res => {
            if (res) {
                const arrayGame = Object.keys(res)
                setGameList(arrayGame.map(key => ({ label: res[key], value: key })))
                form.setFieldsValue({ supperGameId: arrayGame[0] })
                setQueryFrom({ ...queryFrom, supperGameId: arrayGame[0] as any })
            }
        })
    }, [])



    useEffect(() => {
        if (queryFrom.supperGameId) {
            getChatList.run(queryFrom)
        }
    }, [queryFrom])

    useEffect(() => {
        if (supperGameId) {
            getServerList.run({ supperGameId }).then(res => {
                if (res) {
                    setServerList(Object.keys(res).map(key => ({ label: res[key], value: key })))
                }
            })
        }
    }, [supperGameId])

    const onFinish = (data: any) => {
        const oldQueryFrom = JSON.parse(JSON.stringify(queryFrom))
        const { chatTime, ...params } = { ...oldQueryFrom, ...data, pageNum: 1 }
        if (chatTime?.length > 1) {
            params.chatStart = moment(chatTime[0]).format('YYYY-MM-DD')
            params.chatEnd = moment(chatTime[1]).format('YYYY-MM-DD')
        } else {
            delete params?.chatStart
            delete params?.chatEnd
        }
        setQueryFrom(params)
    }

    return <Card
        style={{ borderRadius: 8 }}
        headStyle={{ textAlign: 'left' }}
        bodyStyle={{ padding: '5px 10px' }}
    >
        <div style={{ textAlign: 'center', fontWeight: 'bold', padding: '4px 6px 6px', fontSize: 16, marginBottom: 4, position: 'relative' }}>
            聊天记录
        </div>

        <Space style={{ width: '100%' }} direction="vertical" size={10}>
            <Form
                layout="inline"
                className='queryForm'
                name="basicGameChat"
                form={form}
                onFinish={onFinish}
            >
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='supperGameId'>
                        <Select
                            showSearch
                            style={{ minWidth: 140 }}
                            placeholder={'请选择游戏'}
                            filterOption={(input, option) =>
                                (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={() => {
                                form.setFieldsValue({ codeType: undefined })
                            }}
                            options={gameList}
                        />
                    </Form.Item></Col>
                    {supperGameId && <Col><Form.Item name='serverId'>
                        <Select
                            showSearch
                            style={{ minWidth: 140 }}
                            placeholder={'请选择区服'}
                            filterOption={(input, option) =>
                                (option?.label as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={() => {
                                form.setFieldsValue({ codeType: undefined })
                            }}
                            loading={getServerList?.loading}
                            options={serverList}
                        />
                    </Form.Item></Col>}
                    <Col><Form.Item name='roleName'>
                        <Input placeholder="角色名称" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>
                    <Col><Form.Item name='roleId'>
                        <Input placeholder="角色ID" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>
                    <Col><Form.Item name='chatTime'>
                        <DatePicker.RangePicker placeholder={['聊天时间开始', '聊天时间结束']} />
                    </Form.Item></Col>
                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                        </Space>
                    </Col>
                </Row>
            </Form>

            <div className={`${style['small']}`}>
                <Tables
                    className={`all_table content_table_body`}
                    bordered
                    sortDirections={['ascend', 'descend', null]}
                    current={queryFrom.pageNum}
                    pageSize={queryFrom.pageSize}
                    columns={columnsPos()}
                    dataSource={getChatList?.data?.records}
                    scroll={{ x: 1000, y: 600 }}
                    onChange={(pagination: any, filters: any, sortData: any) => {
                        let { current, pageSize } = pagination
                        let newQueryForm = JSON.parse(JSON.stringify(queryFrom))
                        if (sortData && sortData?.order) {
                            newQueryForm['sortType'] = sortData?.order === 'ascend' ? 'asc' : 'desc'
                            newQueryForm['sortFiled'] = sortData?.field
                        } else {
                            delete newQueryForm['sortType']
                            delete newQueryForm['sortFiled']
                        }
                        newQueryForm.pageNum = current
                        newQueryForm.pageSize = pageSize
                        setQueryFrom({ ...newQueryForm })
                    }}
                    size="small"
                    total={getChatList?.data?.total}
                    loading={getChatList?.loading}
                    defaultPageSize={20}
                />
            </div>
        </Space>
    </Card>
};

export default ChatList;