import { Button, Card, Col, DatePicker, Form, Input, message, Row, Select, Space } from "antd"
import React, { useEffect, useState } from "react"
import style from '../../components/TableData/index.less'
import { PlusOutlined } from "@ant-design/icons"
import Tables from "@/components/Tables"
import { delPackLinkApi, getPackConfigListApi, getPackLinkListApi, GetPackLinkListProps } from "@/services/gameData/roleOperate"
import { useAjax } from "@/Hook/useAjax"
import moment from "moment"
import ModifyLink from "./modifyLink"
import columnsPos from "./tableConfig"
import LinkCode from "./linkCode"
import LinkLog from "./linkLog"
import LinkLqLog from "./linkLqLog"

export type ConfigDataProps = { label: string, value: number, packList: { label: string, value: string }[] }

/**
 * 游戏发码器
 * @returns 
 */
const CodeSender: React.FC = () => {

    /*************************************/
    const [form] = Form.useForm()
    const gameId = Form.useWatch('gameId', form)
    const [queryFrom, setQueryForm] = useState<GetPackLinkListProps>({ pageNum: 1, pageSize: 20 })
    const [configData, setConfigData] = useState<ConfigDataProps[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [initialValues, setInitialValues] = useState<any>()
    const [toCodeData, setToCodeData] = useState<{ data: any, visible: boolean }>({ data: undefined, visible: false })
    const [toLogData, setToLogData] = useState<{ data: any, visible: boolean }>({ data: undefined, visible: false })
    const [toLqData, setToLqData] = useState<{ data: any, visible: boolean }>({ data: undefined, visible: false })

    const getPackConfigList = useAjax(() => getPackConfigListApi())
    const getPackLinkList = useAjax((params) => getPackLinkListApi(params))
    const delPackLink = useAjax((params) => delPackLinkApi(params))
    /*************************************/

    useEffect(() => {
        getPackConfigList.run().then(res => {
            if (res) {
                setConfigData(res?.map((item: { t1: any, t2: any }) => {
                    const gameId = Object.keys(item.t1)[0]
                    const ganemName = item.t1[gameId]
                    return { label: ganemName, value: Number(gameId), packList: Object.keys(item.t2).map(key => ({ label: item.t2[key], value: key })) }
                }))
            }
        })
    }, [])

    useEffect(() => {
        getPackLinkList.run(queryFrom)
    }, [queryFrom])

    const onFinish = (data: any) => {
        let oldQueryFrom = JSON.parse(JSON.stringify(queryFrom))
        let params = { ...oldQueryFrom, ...data, pageNum: 1 }
        if (params?.createTime?.length > 1) {
            params.createBeginTime = moment(params.createTime[0]).format('YYYY-MM-DD')
            params.createEndTime = moment(params.createTime[1]).format('YYYY-MM-DD')
        } else {
            delete params?.createBeginTime
            delete params?.createEndTime
        }
        if (params?.updateTime?.length > 1) {
            params.updateBeginTime = moment(params.updateTime[0]).format('YYYY-MM-DD')
            params.updateEndTime = moment(params.updateTime[1]).format('YYYY-MM-DD')
        } else {
            delete params?.updateBeginTime
            delete params?.updateEndTime
        }
        setQueryForm(params)
    }

    const toCode = (data: any) => {
        setToCodeData({ data, visible: true })
    }

    const editPack = (data: any) => {
        setInitialValues(data)
        setVisible(true)
    }

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

    const handle = (data: any, type: string) => {
        switch (type) {
            case 'log':
                setToLogData({ data, visible: true })
                break
            case 'lq':
                setToLqData({ data, visible: true })
                break
        }
    }

    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="basicGameServer" form={form} onFinish={onFinish}>
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='codeLink'>
                        <Input placeholder="礼包链接" allowClear style={{ width: 140 }} />
                    </Form.Item></Col>
                    <Col><Form.Item name='gameId'>
                        <Select
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择游戏'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            onChange={() => {
                                form.setFieldsValue({ codeType: undefined })
                            }}
                        >
                            {configData?.map((item: any) => <Select.Option value={item.value} key={item.value}>{item.label}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    {gameId && <Col><Form.Item name='codeType'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择礼包码类型'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {configData?.find(item => item.value === gameId)?.packList?.map((item: any) => <Select.Option value={item.value} key={item.value}>{item.label}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>}
                    <Col><Form.Item name='createTime'>
                        <DatePicker.RangePicker placeholder={['创建时间开始', '创建时间结束']} />
                    </Form.Item></Col>
                    <Col><Form.Item name='updateTime'>
                        <DatePicker.RangePicker placeholder={['更新时间开始', '更新时间结束']} />
                    </Form.Item></Col>
                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                            <Button icon={<PlusOutlined />} type="primary" onClick={() => { setVisible(true); }}>新增礼包码链接</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(toCode, editPack, del, handle)}
                    dataSource={getPackLinkList?.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
                        setQueryForm({ ...newQueryForm })
                    }}
                    size="small"
                    total={getPackLinkList?.data?.total}
                    loading={getPackLinkList?.loading}
                    defaultPageSize={20}
                />
            </div>
        </Space>

        {/* 新增链接 */}
        {visible && <ModifyLink
            configData={configData}
            visible={visible}
            initialValues={initialValues}
            onClose={() => {
                setVisible(false)
                setInitialValues(undefined)
            }}
            onChange={() => {
                setVisible(false)
                setInitialValues(undefined)
                getPackLinkList.refresh()
            }}
        />}

        {/* 礼包码 */}
        {toCodeData?.visible && <LinkCode
            {...toCodeData}
            onClose={() => {
                setToCodeData({ data: undefined, visible: false })
            }}
        />}

        {/* 访问记录 */}
        {toLogData?.visible && <LinkLog
            {...toLogData}
            onClose={() => {
                setToLogData({ data: undefined, visible: false })
            }}
        />}


        {/* 访问记录 */}
        {toLqData?.visible && <LinkLqLog
            {...toLqData}
            onClose={() => {
                setToLqData({ data: undefined, visible: false })
            }}
        />}
    </Card>
}

export default CodeSender