import { Form, Input, InputNumber, Modal, Select, Space, message } from "antd";
import React, { useEffect, useState } from "react"
import { strategyType } from ".";
import { FieldTimeOutlined } from "@ant-design/icons";
import { useAjax } from "@/Hook/useAjax";
import { StrategyProps, modalStrategyApi } from "@/services/gameData/roleOperate";

enum conditionEnum {
    gt = '大于',
    ge = '大于等于',
    lt = '小于',
    le = '小于等于',
    eq = '等于',
}

interface Props {
    superGameList: any[]
    initialValues?: any
    visible?: boolean
    onClose?: () => void
    onChange?: () => void
}
const StrategyModal: React.FC<Props> = ({ superGameList, initialValues, visible, onClose, onChange }) => {

    /*****************************/
    const [form] = Form.useForm<StrategyProps>()
    const type = Form.useWatch('type', form)
    const time = Form.useWatch('time', form)
    const timeCondition = Form.useWatch('timeCondition', form)
    const amount = Form.useWatch('amount', form)
    const amountCondition = Form.useWatch('amountCondition', form)
    const [help, setHelp] = useState<string>()
    const modalStrategy = useAjax((params) => modalStrategyApi(params))
    /*****************************/

    useEffect(() => {
        if (type) {
            let timeTips: string = ''
            let amountTips: string = ''
            switch (type) {
                case 1:
                    // 单笔充值金额大于等于XX,并且注册时间在XX小时内的玩家
                    timeTips = time ? `注册时间${conditionEnum[timeCondition]}${time}小时的玩家` : ''
                    amountTips = amount ? `单笔充值金额${conditionEnum[amountCondition]}${amount}元` : ''
                    break
                case 2:
                    // 累计充值金额大于等于XX,并且最近游戏距今时间超过XX小时的玩家
                    amountTips = amount ? `累计充值金额${conditionEnum[amountCondition]}${amount}元` : ''
                    timeTips = time ? `最近游戏距今时间${conditionEnum[timeCondition]}${time}小时的玩家` : ''
                    break
                case 3:
                    // '新用户注册创角首日充值大于等于XX的用户'
                    amountTips = amount ? `新用户注册创角首日充值${conditionEnum[amountCondition]}${amount}元的用户` : ''
                    break
            }
            let helpTips = ''
            if (timeTips && amountTips) {
                helpTips = amountTips + '，并且' + timeTips + '，发送钉钉消息'
            } else if (timeTips) {
                helpTips = timeTips + '，发送钉钉消息'
            } else if (amountTips) {
                helpTips = amountTips + '，发送钉钉消息'
            }
            setHelp(helpTips)
            form.setFieldsValue({ configExplain: helpTips })
        } else {
            setHelp(undefined)
            form.setFieldsValue({ configExplain: undefined })
        }
    }, [type, time, amount, timeCondition, amountCondition])

    const handleOk = async () => {
        form.submit()
        let data = await form.validateFields()
        console.log('===========>', data)
        if (!data?.amount && !data?.time) {
            message.error('时间和金额最少填一项')
            return
        }
        if (initialValues?.id) {
            data.id = initialValues?.id
        }
        modalStrategy.run(data).then(res => {
            if (res) {
                if (initialValues?.id) {
                    message.success('修改成功')
                } else {
                    message.success('新增成功')
                }
                onChange?.()
            }
        })
    }


    // 配置 formatter 和 parser
    const integerFormatter = (value: any) => {
        // 去除非数字字符
        if (value && value !== 0) {
            const intValue = parseInt(value, 10);
            return isNaN(intValue) ? 0 : intValue as any;
        }
        return value
    };

    const integerParser = (value: any) => {
        // 去除非数字字符
        if (value && value !== 0) {
            const intValue = parseInt(value, 10);
            return isNaN(intValue) ? '' : String(intValue);
        }
        return value
    };

    return <Modal
        title={`${initialValues?.id ? '修改' : '新增'}游戏策略`}
        visible={visible}
        onCancel={onClose}
        onOk={handleOk}
        confirmLoading={modalStrategy.loading}
    >
        <Form
            name="basicStrategy"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
            form={form}
            autoComplete="off"
            labelAlign="left"
            colon={false}
            initialValues={Object.keys(initialValues).length > 0 ? { ...initialValues } : { amountCondition: 'gt', timeCondition: 'gt' }}
        >
            <Form.Item label="超父游戏" name='superGameId' rules={[{ required: true, message: '请选择超父游戏!' }]}>
                <Select
                    showSearch
                    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>
            <Form.Item label="策略类型" help={help} name='type' rules={[{ required: true, message: '请选择策略类型!' }]}>
                <Select
                    showSearch
                    style={{ minWidth: 140 }}
                    allowClear
                    placeholder={'请选择策略类型'}
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                >
                    {strategyType?.map((item: any) => <Select.Option value={item.value} key={item.value}>{item.label}</Select.Option>)}
                </Select>
            </Form.Item>
            <Form.Item
                label="金额(元)"
            >
                <Space style={{ width: '100%' }}>
                    <Form.Item
                        name='amount'
                        noStyle
                    >
                        <InputNumber
                            style={{ width: '100%' }}
                            prefix="￥"
                            min={0}
                            placeholder="请输入金额"
                            formatter={integerFormatter}
                            parser={integerParser}
                        />
                    </Form.Item>
                    {(amount || amount === 0) && <Form.Item
                        name='amountCondition'
                        noStyle
                        rules={[{ required: true, message: '请选择条件' }]}
                    >
                        <Select
                            style={{ width: 100 }}
                            placeholder="条件"
                        >
                            <Select.Option value="gt">大于</Select.Option>
                            <Select.Option value="ge">大于等于</Select.Option>
                            <Select.Option value="lt">小于</Select.Option>
                            <Select.Option value="le">小于等于</Select.Option>
                            <Select.Option value="eq">等于</Select.Option>
                        </Select>
                    </Form.Item>}
                </Space>
            </Form.Item>

            {type !== 3 && <Form.Item
                label="时间(小时)"
            >
                <Space>
                    <Form.Item
                        name='time'
                        noStyle
                    >
                        <InputNumber
                            style={{ width: '100%' }}
                            prefix={<FieldTimeOutlined />}
                            min={0}
                            placeholder="请输入时间"
                            formatter={integerFormatter}
                            parser={integerParser}
                        />
                    </Form.Item>
                    {(time || time === 0) && <Form.Item
                        name='timeCondition'
                        noStyle
                        rules={[{ required: true, message: '请选择条件' }]}
                    >
                        <Select
                            style={{ width: 100 }}
                            placeholder="条件"
                        >
                            <Select.Option value="gt">大于</Select.Option>
                            <Select.Option value="ge">大于等于</Select.Option>
                            <Select.Option value="lt">小于</Select.Option>
                            <Select.Option value="le">小于等于</Select.Option>
                            <Select.Option value="eq">等于</Select.Option>
                        </Select>
                    </Form.Item>}
                </Space>
            </Form.Item>}
            <Form.Item label="策略说明" name='configExplain' rules={[{ required: true, message: '请选择配置说明!' }]}>
                <Input.TextArea placeholder="配置说明：请写出具体的配置细节。如：首次充值金额大于等于500并且注册时间24小时内的用户，发送钉钉消息" />
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(StrategyModal)