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";
import { getRoleUserListApi } from "@/services/gameData";

export 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 [operateList, setOperateList] = useState<any[]>([])
    const modalStrategy = useAjax((params) => modalStrategyApi(params))
    const getRoleUserList = useAjax((params) => getRoleUserListApi(params))
    /*****************************/

    useEffect(() => {
        const getList = async () => {
            let data = []
            // 运营
            let operate = await getRoleUserList.run({ authType: 'OPERATE' })
            data = operate ? Object.keys(operate)?.map(key => ({ userId: key, nickname: operate[key] })) : []
            // 客服
            let customer = await getRoleUserList.run({ authType: 'CUSTOMER' })
            let c = customer ? Object.keys(customer)?.map(key => ({ userId: key, nickname: customer[key] })) : []
            setOperateList(data.concat(c))
        }
        getList()
    }, [])

    useEffect(() => {
        if (type) {
            let timeTips: string = ''
            let amountTips: string = ''
            switch (type) {
                case 1:
                    // 单笔充值金额大于等于XX,并且注册时间在XX小时内的玩家
                    timeTips = time ? `注册时间${conditionEnum[timeCondition as keyof typeof conditionEnum]}${time}小时的玩家` : ''
                    amountTips = amount ? `单笔充值金额${conditionEnum[amountCondition as keyof typeof conditionEnum]}${amount}元` : ''
                    break
                case 2:
                    // 累计充值金额大于等于XX,并且最近游戏距今时间超过XX小时的玩家
                    amountTips = amount ? `累计充值金额${conditionEnum[amountCondition as keyof typeof conditionEnum]}${amount}元` : ''
                    timeTips = time ? `最近游戏距今时间${conditionEnum[timeCondition as keyof typeof conditionEnum]}${time}小时的玩家` : ''
                    break
                case 3:
                    // '新用户注册创角首日充值大于等于XX的用户'
                    amountTips = amount ? `新用户注册创角首日充值${conditionEnum[amountCondition as keyof typeof conditionEnum]}${amount}元的用户` : ''
                    break
                case 5:
                    amountTips = amount ? `新创建的角色在创角至今${conditionEnum[timeCondition as keyof typeof conditionEnum]}${time}小时内，首次充值（角色首充，单笔充值）${conditionEnum[amountCondition as keyof typeof conditionEnum]}${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: 5 }}
            wrapperCol={{ span: 19 }}
            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="策略类型" 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="告警人员" name='userIds' rules={[{ required: true, message: '请选择告警人员!' }]}>
                <Select
                    maxTagCount={4}
                    showSearch
                    mode="multiple"
                    style={{ minWidth: 140 }}
                    allowClear
                    loading={getRoleUserList.loading}
                    placeholder={'请选择告警人员'}
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                >
                    {operateList.map((item: any) => <Select.Option value={Number(item.userId)} key={item.userId}>{item.nickname}</Select.Option>)}
                </Select>
            </Form.Item>
            <Form.Item label="排除指标标签" name='tagIds'>
                <Select
                    maxTagCount={1}
                    showSearch
                    mode="multiple"
                    style={{ minWidth: 140 }}
                    allowClear
                    placeholder={'请选择排除指标标签'}
                    filterOption={(input, option) =>
                        (option?.children as any)?.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                >
                    <Select.Option value={1}>已退游</Select.Option>
                    <Select.Option value={2}>已添加企微</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小时内的用户，发送钉钉消息" /> */}
                <Input.TextArea placeholder="请输入备注" />
            </Form.Item>
            <Form.Item label="策略说明">
                <Input.TextArea value={help} disabled placeholder="策略说明" />
            </Form.Item>
        </Form>
    </Modal>
}

export default React.memo(StrategyModal)