import { useAjax } from "@/Hook/useAjax"
import { getGameListNewApi } from "@/services/gameData"
import { StrategyListProps, delStrategyApi, getStrategyListApi } from "@/services/gameData/roleOperate"
import { PlusOutlined } from "@ant-design/icons"
import { Button, Card, Col, Form, Row, Select, Space, message } from "antd"
import React, { useEffect, useState } from "react"
import style from '../../components/TableData/index.less'
import StrategyModal from "./strategyModal"
import Tables from "@/components/Tables"
import columnsPos from "./tableConfig"

export const strategyType = [
    { label: '追踪玩家', value: 1, tips: '单笔充值金额大于XX,并且注册时间在XX小时内的玩家' },
    { label: '玩家流失', value: 2, tips: '累计充值金额大于XX,并且最近游戏距今时间超过XX小时的玩家' },
    { label: '新用户追踪', value: 3, tips: '新用户注册创角首日充值大于XX的用户' },
    { label: '累充追踪', value: 4, tips: '' },
    { label: '新增角色追踪', value: 5, tips: '新创建的角色在创角至今【XX】小时内，首次充值（角色首充，单笔充值）【XX】金额，触发报警一次' }
]
/**
 * 游戏策略配置
 * @returns 
 */
const Strategy: React.FC = () => {

    /****************************/
    const [form] = Form.useForm()
    const [queryFrom, setQueryForm] = useState<StrategyListProps>({ pageNum: 1, pageSize: 20 })
    const [superGameList, setSuperGameList] = useState<any[]>([])
    const [initialValues, setInitialValues] = useState<any>({})
    const [visible, setVisible] = useState<boolean>(false)
    const getStrategyList = useAjax((params) => getStrategyListApi(params))
    const delStrategy = useAjax((params) => delStrategyApi(params))
    const getGameList = useAjax((params) => getGameListNewApi(params))
    /****************************/

    const onFinish = (data: any) => {
        let oldQueryFrom = JSON.parse(JSON.stringify(queryFrom))
        setQueryForm({ ...oldQueryFrom, ...data, pageNum: 1 })
    }

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

    useEffect(() => {
        getGameList.run({ sourceSystem: 'ZX_ONE' }).then(res => {
            if (res) {
                const { superGameList } = res
                setSuperGameList(superGameList)
            }
        })
    }, [])

    const editVip = (data: any) => {
        setInitialValues({ ...data, userIds: data.userNameIds || [], tagIds: data.tagsNameIds || [] })
        setVisible(true)
    }

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

    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' initialValues={initialValues} name="basicGameVip" form={form} onFinish={onFinish}>
                <Row gutter={[0, 6]}>
                    <Col><Form.Item name='superGameId'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ minWidth: 140 }}
                            allowClear
                            placeholder={'请选择超父游戏'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {superGameList?.map((item: any) => <Select.Option value={item.super_game_id} key={item.super_game_id}>{item.super_game_name}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    <Col><Form.Item name='type'>
                        <Select
                            maxTagCount={1}
                            showSearch
                            style={{ width: 140 }}
                            allowClear
                            placeholder={'请选择策略类型'}
                            filterOption={(input, option) =>
                                (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            dropdownMatchSelectWidth={false}
                        >
                            {strategyType?.map((item: any) => <Select.Option value={item.value} key={item.value}>{item.label}_{item.tips}</Select.Option>)}
                        </Select>
                    </Form.Item></Col>
                    <Col>
                        <Space>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button onClick={() => form.resetFields()}>重置</Button>
                            <Button icon={<PlusOutlined />} type="primary" onClick={() => { setVisible(true); setInitialValues({}) }}>新增游戏策略配置</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(editVip, del)}
                    dataSource={getStrategyList?.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={getStrategyList?.data?.total}
                    loading={getStrategyList?.loading}
                    defaultPageSize={20}
                />
            </div>
        </Space>

        {visible && <StrategyModal
            superGameList={superGameList}
            visible={visible}
            initialValues={initialValues}
            onChange={() => {
                setInitialValues({});
                getStrategyList.refresh()
                setVisible(false)
            }}
            onClose={() => {
                setInitialValues({})
                setVisible(false)
            }}
        />}
    </Card>
}

export default Strategy