import { useAjax } from '@/Hook/useAjax';
import { getGameListNewApi, getGameServerListApi } from '@/services/gameData';
import { getGameCountryDataListApi, GetGameCountryDataListProps, getGameCountryListApi } from '@/services/gsData';
import { groupBy } from '@/utils/utils';
import { Button, Card, Col, Form, Row, Select, Space, Spin, Table, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import CountryList from './countryList';

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

    /****************************************/
    const [form] = Form.useForm()
    const gameId = Form.useWatch('gameId', form)
    const serverId = Form.useWatch('serverId', form)
    const gameCountryList = Form.useWatch('gameCountryList', form)

    const [gameList, setGameList] = useState<any[]>([])
    const [parentGameList, setParentGameList] = useState<any[]>([])
    const [superGameList, setSuperGameList] = useState<any[]>([])
    const [countryList, setCountryList] = useState<any[]>([])

    const [queryForm, setQueryForm] = useState<GetGameCountryDataListProps>({})
    const [dataList, setDataList] = useState<{ [x: string]: any[] }>({})

    const getGameListNew = useAjax((params) => getGameListNewApi(params))
    const getGameServerList = useAjax((params) => getGameServerListApi(params))
    const getGameCountryList = useAjax((params) => getGameCountryListApi(params))
    const getGameCountryDataList = useAjax((params) => getGameCountryDataListApi(params))
    /****************************************/

    useEffect(() => {
        getGameCountryDataList.run({ ...queryForm, gameId: queryForm?.gameId ? [queryForm.gameId] : undefined }).then(res => {
            if (res) {
                setDataList(res)
            } else {
                setDataList({})
            }
        }).catch(() => {
            setDataList({})
        })
    }, [queryForm])

    /** 游戏列表 */
    useEffect(() => {
        getGameListNew.run({ sourceSystem: 'ZX_ONE' }).then((res: { gameList: any; parentGameList: any; superGameList: any }) => {
            if (res) {
                const { gameList, parentGameList, superGameList } = res
                setGameList(gameList?.map((item: { id: any; game_name: any }) => ({ id: item.id, name: item.game_name })) || [])
                setParentGameList(parentGameList)
                setSuperGameList(superGameList)
            }
        })
    }, [])

    useEffect(() => {
        getGameCountryList.run({ gameId: gameId ? [gameId] : undefined, serverId }).then(res => {
            if (res?.length) {
                const data = res.map((item: { country: string; serverId: string; }) => ({ ...item, id: item.country + ',' + item.serverId }))
                const countryData = groupBy(data, (item) => item.serverId, true)
                const countryList = Object.keys(countryData).map(key => {
                    return {
                        label: countryData[key]?.[0]?.gameName + '_' + countryData[key]?.[0]?.serverName,
                        value: JSON.parse(key),
                        options: countryData[key]?.map((item: { country: any; id: any; }) => ({
                            label: item.country,
                            value: item.id
                        }))
                    }
                })
                setCountryList(countryList)
            } else {
                setCountryList([])
            }
        })
    }, [serverId, gameId])

    useEffect(() => {
        setCountryList(data => data.map(i => {
            return { ...i, options: i.options.map((c: any) => ({ ...c, disabled: gameCountryList?.length >= 4 ? gameCountryList?.includes(c.value) ? false : true : false })) }
        }))
    }, [gameCountryList])

    const onFinish = (data: any) => {
        setQueryForm(data)
    }

    return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <Card bodyStyle={{ padding: 10 }}>
                <Form layout="inline" className='queryForm' initialValues={{}} name="basicGandRole" form={form} onFinish={onFinish}>
                    <Form.Item name='gameId'>
                        <Select
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择父游戏'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={(e, option: any) => {
                                if (option?.['data-super-id']) {
                                    getGameServerList.run({ gameId: option['data-super-id'] })
                                } else {
                                    getGameServerList?.data && getGameServerList.mutate([])
                                }
                                form.setFieldsValue({ gameCountryList: undefined })
                            }}
                        >
                            {parentGameList?.filter(item => [35, 36].includes(item.parent_game_id))?.map((item: any) => <Select.Option value={item.parent_game_id} key={item.parent_game_id} data-super-id={item.super_game_id}>{item.parent_game_name}</Select.Option>)}
                        </Select>
                    </Form.Item>
                    {gameId && <>
                        <Form.Item name='serverId'>
                            <Select
                                showSearch
                                maxTagCount={1}
                                mode='multiple'
                                style={{ minWidth: 140 }}
                                allowClear
                                placeholder={'请选择区服'}
                                filterOption={(input, option) =>
                                    (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                }
                                loading={getGameServerList.loading}
                                onChange={() => {
                                    form.setFieldsValue({ gameCountryList: undefined })
                                }}
                            >
                                {getGameServerList?.data?.map((item: any) => <Select.Option value={item.serverId} key={item.serverId}>{item.serverName}</Select.Option>)}
                            </Select>
                        </Form.Item>
                    </>}
                    <Form.Item name='gameCountryList'>
                        <Select
                            maxTagCount={1}
                            mode='multiple'
                            showSearch
                            style={{ minWidth: 160 }}
                            allowClear
                            placeholder={'请选择帮派'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            loading={getGameCountryList.loading}
                            options={countryList}
                        />
                    </Form.Item>
                    <Space>
                        <Button type="primary" htmlType="submit">搜索</Button>
                        <Button onClick={() => form.resetFields()}>重置</Button>
                    </Space>
                </Form>
            </Card>
            <Card bodyStyle={{ padding: 10 }}>
                <Spin spinning={getGameCountryDataList.loading}>
                    <Row gutter={[20, 20]}>
                        {Object.keys(dataList).map((d, index) => {
                            const [country] = d.split(',')
                            return <Col key={d + index} span={12}>
                                <Typography.Title level={3} style={{ textAlign: 'center' }}>{country}</Typography.Title>
                                <Table
                                    dataSource={dataList[d].map((item, index) => ({ ...item, id: index + 1 }))}
                                    size="small"
                                    bordered
                                    rowKey={'id'}
                                    scroll={{ x: 500 }}
                                    columns={[
                                        {
                                            title: '等级',
                                            dataIndex: 'countryLevel',
                                            key: 'countryLevel',
                                            render(value) {
                                                return ({ 0: '等级1-13级', 1: '等级13级以上(不包含13级)' } as any)[value]
                                            },
                                            width: 150
                                        },
                                        {
                                            title: '区服ID',
                                            dataIndex: 'serverId',
                                            key: 'serverId',
                                            width: 70,
                                            align: 'center'
                                        },
                                        {
                                            title: '帮派名称',
                                            dataIndex: 'country',
                                            key: 'country',
                                            width: 160,
                                            ellipsis: true
                                        },
                                        {
                                            title: '角色总数量',
                                            dataIndex: 'roleCount',
                                            key: 'roleCount',
                                            width: 70,
                                            align: 'center'
                                        },
                                        {
                                            title: '今日活跃角色数量',
                                            dataIndex: 'activeCount',
                                            key: 'activeCount',
                                            width: 80,
                                            align: 'center'
                                        },
                                        {
                                            title: '角色累计充值',
                                            dataIndex: 'roleTotalAmount',
                                            key: 'roleTotalAmount',
                                            width: 70,
                                            align: 'center'
                                        },
                                        {
                                            title: '操作',
                                            dataIndex: 'cz',
                                            key: 'cz',
                                            width: 70,
                                            align: 'center',
                                            render(_, record) {
                                                return <CountryList country={record.country} serverId={record.serverId} countryLevel={record.countryLevel}/>
                                            },
                                        }
                                    ]}
                                    pagination={false}
                                />
                            </Col>
                        })}
                    </Row>
                </Spin>
            </Card>
        </div>
    );
};

export default GandRole;