import { useAjax } from "@/Hook/useAjax";
import { delGameApi, getGameLibraryApi, getGameLibraryAppIdDetailApi, getGameLibraryDetailApi, getGameLibraryListApi } from "@/services/adqV3/global";
import { PlusOutlined, SearchOutlined } from "@ant-design/icons";
import { Button, Card, Divider, Input, message, Select, Spin, Table, Typography } from "antd";
import React, { useEffect, useState } from "react"
import '../../tencentAdPutIn/index.less'
import Modify from "./modify";
import columns from "./tableConfig";
const { Text, Paragraph } = Typography;

/**
 * 游戏库
 * @returns 
 */
const Game: React.FC = () => {

    /**********************************/
    const [queryForm, setQueryForm] = useState<{ pageNum: number, pageSize: number, gameName?: string, idList?: number[], gameType?: string }>({ pageNum: 1, pageSize: 20 })
    const [queryFormNew, setQueryFormNew] = useState<{ pageNum: number, pageSize: number, gameName?: string, idList?: number[], gameType?: string }>({ pageNum: 1, pageSize: 20 })
    const [visible, setVisible] = useState<boolean>(false)

    const getGameLibraryList = useAjax((params) => getGameLibraryListApi(params))
    const delGame = useAjax((params) => delGameApi(params))
    /**********************************/

    useEffect(() => {
        getGameLibraryList.run(queryFormNew)
    }, [queryFormNew])

    const del = (id: number) => {
        delGame.run(id).then(res => {
            if (res) {
                message.success('删除成功')
                getGameLibraryList.refresh()
            }
        })
    }

    return <Card
        className="cardResetCss"
        title={<div className="flexStart" style={{ gap: 8 }}>
            <Input style={{ width: 200 }} placeholder="请输入游戏名称" value={queryForm?.gameName} allowClear onChange={(e) => setQueryForm({ ...queryForm, gameName: e.target.value, pageNum: 1 })} />
            <Select
                showSearch
                placeholder="请选择游戏类型"
                onChange={(e) => setQueryForm({ ...queryForm, gameType: e, pageNum: 1 })}
                filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
                allowClear
                style={{ width: 150 }}
                options={[
                    {
                        value: 'WXGAME',
                        label: '微信小游戏',
                    }
                ]}
            />
            <Input.TextArea
                style={{ width: 300 }}
                placeholder="请输入游戏ID（多个逗号隔开）"
                allowClear
                rows={1}
                onChange={(e) => {
                    let value = e.target.value
                    let arr: any[] = []
                    if (value) {
                        value = value.replace(/[,，\s]/g, ',')
                        arr = value.split(',').filter((a: any) => a)
                    }
                    setQueryForm({ ...queryForm, idList: arr, pageNum: 1 })
                }}
            />
            <Button type="primary" icon={<SearchOutlined />} onClick={() => setQueryFormNew({ ...queryForm })}>搜索</Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => { setVisible(true) }}>新增游戏</Button>
        </div>}
    >

        <Table
            columns={columns(del)}
            dataSource={getGameLibraryList.data?.records}
            size="small"
            loading={getGameLibraryList?.loading}
            scroll={{ y: 600 }}
            bordered
            rowKey={'id'}
            pagination={{
                defaultPageSize: 20,
                current: getGameLibraryList.data?.current || 1,
                pageSize: getGameLibraryList.data?.size || 10,
                total: getGameLibraryList.data?.total || 0
            }}
            onChange={(pagination) => {
                const { current, pageSize } = pagination
                setQueryForm({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
                setQueryFormNew({ ...queryForm, pageNum: current || 1, pageSize: pageSize || 10 })
            }}
        />

        {/* 新增修改 */}
        {visible && <Modify
            visible={visible}
            onClose={() => {
                setVisible(false)
            }}
            onChange={() => {
                setVisible(false)
                getGameLibraryList.refresh()
            }}
        />}
    </Card>
}


/**
 * 选择游戏
 * @param param0 
 * @returns 
 */
export const SelectGame: React.FC<{ gameType: 'WXGAME', value?: string, onChange?: (value?: string, appId?: string) => void }> = ({ gameType, value, onChange }) => {

    /*******************************/
    const [visible, setVisible] = useState<boolean>(false)
    const getGameLibrary = useAjax((params) => getGameLibraryApi(params))
    /*******************************/

    // 获取列表
    useEffect(() => {
        getGameLibrary.run({ gameType })
    }, [gameType])

    return <>
        <Select
            showSearch
            allowClear
            placeholder="请选择企微"
            filterOption={(input: any, option: any) => {
                return option!.name?.toString().toLowerCase().includes(input.toLowerCase())
            }}
            style={{ width: 480 }}
            dropdownRender={menu => <>
                {menu}
                <Divider style={{ margin: '8px 0' }} />
                <div>
                    <Button type="link" onClick={() => {
                        window.location.href = '/#/launchSystemV3/tencenTasset/game'
                    }}>前往管理</Button>
                    <Button type="link" style={{ paddingLeft: 0, paddingRight: 0 }} onClick={() => {
                        setVisible(true)
                    }}>新增</Button>
                    {/* <Link href="/#/launchSystemV3/tencenTasset/miniProgramWechat" target="_blank">
                    前往管理
                </Link> */}
                </div>
            </>}
            value={value}
            onChange={(e, options) => onChange?.(e, options?.appId)}
        >
            {getGameLibrary?.data?.map((item: { id: number, appId: string, gameName: string }) => {
                return <Select.Option value={item.id} key={item.id} appId={item.appId} name={item.gameName + `(${item.appId})`}><Text strong>{item.gameName}</Text><Text type="secondary">{`(${item.appId})`}</Text></Select.Option>
            })}
        </Select>
        {/* 新增修改 */}
        {visible && <Modify
            visible={visible}
            onClose={() => {
                setVisible(false)
            }}
            onChange={() => {
                setVisible(false)
                getGameLibrary.refresh()
            }}
        />}
    </>
}

/**
 * 选择游戏
 * @param param0 
 * @returns 
 */
export const SelectGameAppId: React.FC<{ gameType: 'WXGAME', value?: string[], onChange?: (value?: string[]) => void }> = ({ gameType, value, onChange }) => {

    /*******************************/
    const [visible, setVisible] = useState<boolean>(false)
    const getGameLibrary = useAjax((params) => getGameLibraryApi(params))
    /*******************************/

    // 获取列表
    useEffect(() => {
        getGameLibrary.run({ gameType })
    }, [gameType])

    return <>
        <Select
            showSearch
            allowClear
            placeholder="请选择游戏"
            filterOption={(input: any, option: any) => {
                return option!.name?.toString().toLowerCase().includes(input.toLowerCase())
            }}
            style={{ width: 480 }}
            dropdownRender={menu => <>
                {menu}
                <Divider style={{ margin: '8px 0' }} />
                <div>
                    <Button type="link" onClick={() => {
                        window.location.href = '/#/launchSystemV3/tencenTasset/game'
                    }}>前往管理</Button>
                    <Button type="link" style={{ paddingLeft: 0, paddingRight: 0 }} onClick={() => {
                        setVisible(true)
                    }}>新增</Button>
                    {/* <Link href="/#/launchSystemV3/tencenTasset/miniProgramWechat" target="_blank">
                    前往管理
                </Link> */}
                </div>
            </>}
            value={value}
            onChange={(e) => onChange?.(e)}
        >
            {getGameLibrary?.data?.map((item: { id: number, appId: string, gameName: string }) => {
                return <Select.Option value={item.appId} key={item.id} name={item.gameName + `(${item.appId})`}><Text strong>{item.gameName}</Text><Text type="secondary">{`(${item.appId})`}</Text></Select.Option>
            })}
        </Select>
        {/* 新增修改 */}
        {visible && <Modify
            visible={visible}
            onClose={() => {
                setVisible(false)
            }}
            onChange={() => {
                setVisible(false)
                getGameLibrary.refresh()
            }}
        />}
    </>
}


/**
 * 展示游戏
 * @param param0 
 * @returns 
 */
export const ShowGameDetail: React.FC<{ id: number }> = ({ id }) => {

    /*******************************/
    const getGameLibraryDetail = useAjax((params) => getGameLibraryDetailApi(params))
    /*******************************/

    // 获取列表
    useEffect(() => {
        if (id) {
            getGameLibraryDetail.run(id)
        }
    }, [id])

    return <Spin spinning={getGameLibraryDetail.loading}>
        <Paragraph style={{ fontSize: 12, wordBreak: 'break-all', marginBottom: 0 }} ellipsis={{ rows: 2 }}>
            {getGameLibraryDetail.data ? <>
                <Text strong>游戏：{getGameLibraryDetail.data?.gameName}</Text><Text type="secondary">{`(${getGameLibraryDetail.data?.appId})`}</Text>
            </> : id}
        </Paragraph>
    </Spin>
}

export const ShowGameAppIdDetail: React.FC<{ appId: number }> = ({ appId }) => {

    /*******************************/
    const getGameLibraryAppIdDetail = useAjax((params) => getGameLibraryAppIdDetailApi(params))
    /*******************************/

    // 获取列表
    useEffect(() => {
        if (appId) {
            getGameLibraryAppIdDetail.run(appId)
        }
    }, [appId])

    return <Spin spinning={getGameLibraryAppIdDetail.loading}>
        <Paragraph style={{ fontSize: 12, wordBreak: 'break-all', marginBottom: 0 }} ellipsis={{ rows: 2 }}>
            {getGameLibraryAppIdDetail.data ? <>
                <Text strong>游戏：{getGameLibraryAppIdDetail.data?.gameName}</Text><Text type="secondary">{`(${getGameLibraryAppIdDetail.data?.appId})`}</Text>
            </> : appId}
        </Paragraph>
    </Spin>
}

export default Game