import { App, Button, Form, InputNumber, Modal, Popconfirm, Radio, Select, Table } from 'antd';
import React, { useState } from 'react';
import { RECHARGETYPE } from '../../const';

interface valueProps {
    hongbao: number;
    price: number;
    rechargeFrequency: 0 | 1;
    rechargeTimes: number;
    rechargeType: number;
    vipConfigId: string
}

interface SetConfigProps {
    value?: valueProps[]
    onChange?: (value: valueProps[]) => void
}

const SetConfig: React.FC<SetConfigProps> = ({ value = [], onChange }) => {

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

    return <div>
        <Button type="primary" onClick={() => setVisible(true)}>添加充值项</Button>
        {value?.length > 0 && <Table
            style={{ marginTop: 10 }}
            dataSource={value.map((item, index) => ({ ...item, id: index + 1 }))}
            columns={[
                {
                    title: '充值类型',
                    dataIndex: 'rechargeType',
                    key: 'rechargeType',
                    align: 'center',
                    render(value) {
                        return RECHARGETYPE[value]
                    },
                },
                {
                    title: '充值金额',
                    dataIndex: 'price',
                    key: 'price',
                    render(value) {
                        return (value || value === 0) ? value + '元' : '--'
                    },
                },
                {
                    title: '赠送金额',
                    dataIndex: 'hongbao',
                    key: 'hongbao',
                    render(value) {
                        return (value || value === 0) ? value + '元' : '--'
                    },
                },
                {
                    title: '限购次数',
                    dataIndex: 'rechargeFrequency',
                    key: 'rechargeFrequency',
                    render(value, record) {
                        return value === 0 ? record.rechargeTimes === -1 ? '不限' : (record.rechargeTimes + '次') : record.rechargeTimes === -1 ? '不限' : ('每天' + record.rechargeTimes + '次')
                    },
                },
                {
                    title: '操作',
                    dataIndex: 'cz',
                    key: 'cz',
                    align: 'center',
                    render(_, record) {
                        return <Popconfirm
                            title="确定删除该项?"
                            onConfirm={() => {
                                onChange?.(value?.filter((_, index) => record.id !== (index + 1)))
                            }}
                        >
                            <a>删除</a>
                        </Popconfirm>
                    },
                },
            ]}
            rowKey={'id'}
            size='small'
            bordered
            pagination={false}
        />}
        {visible && <SetConfigModal
            visible={visible}
            onClose={() => setVisible(false)}
            onChange={(newValue) => {
                setVisible(false)
                const oldValue = JSON.parse(JSON.stringify(value || []))
                oldValue.push(newValue)
                onChange?.(oldValue)
            }}
        />}
    </div>
};

interface SetConfigModalProps {
    onChange?: (value: valueProps) => void
    visible?: boolean;
    onClose?: () => void;
}
const SetConfigModal: React.FC<SetConfigModalProps> = ({ visible, onChange, onClose }) => {

    /***********************************/
    const { message } = App.useApp()
    const [form] = Form.useForm();
    const rechargeType = Form.useWatch('rechargeType', form)
    const price = Form.useWatch('price', form)
    /***********************************/

    const handleOk = () => {
        form.validateFields().then((values) => {
            console.log(values)
            onChange?.(values)
        })
    }

    return <Modal
        title={<strong>添加充值项</strong>}
        open={visible}
        onCancel={onClose}
        width={600}
        onOk={handleOk}
    >
        <Form
            form={form}
            name="newConfig"
            labelAlign='left'
            labelCol={{ span: 5 }}
            colon={false}
            scrollToFirstError={{
                behavior: 'smooth',
                block: 'center'
            }}
            onFinishFailed={({ errorFields }) => {
                message.error(errorFields?.[0]?.errors?.[0])
            }}
            onFinish={handleOk}
            initialValues={{ rechargeType: 0, rechargeFrequency: 0 }}
        >
            <Form.Item label={<strong>充值类型</strong>} name="rechargeType" rules={[{ required: true, message: '请选择充值类型!' }]}>
                <Select
                    showSearch
                    allowClear
                    placeholder="请选择充值类型"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    options={Object.keys(RECHARGETYPE).map(key => ({ label: RECHARGETYPE[key], value: Number(key) }))}
                />
            </Form.Item>
            {rechargeType === 0 ? <>
                <Form.Item
                    label={<strong>充值金额</strong>}
                    name="price"
                    rules={[
                        { required: true, message: '请输入充值金额!' },
                        {
                            validator: (_: any, value: number) => {
                                if (value && value.toString().split('.')[1]?.length > 2) {
                                    return Promise.reject('最多输入两位小数');
                                }
                                return Promise.resolve();
                            }
                        }
                    ]}
                >
                    <InputNumber suffix="元" placeholder="请输入" min={1} max={300} precision={2} style={{ width: '100%' }} />
                </Form.Item>
                <Form.Item
                    label={<strong>赠送金额</strong>}
                    name="hongbao"
                    rules={[
                        { required: true, message: '请输入赠送金额!' },
                        {
                            validator: (_: any, value: number) => {
                                if (!value) return Promise.resolve();
                                // 小数位数校验
                                if (value.toString().split('.')[1]?.length > 2) {
                                    return Promise.reject('最多输入两位小数');
                                }
                                // 动态倍数校验
                                const maxRatio = price <= 9 ? 2.5 : 1.5;
                                const maxAmount = Math.min(price * maxRatio, 20);
                                if (value > maxAmount) {
                                    return Promise.reject(
                                        price <= 9
                                            ? `不能超过${maxRatio}倍(最大20元)`
                                            : `不能超过${maxRatio}倍`
                                    );
                                }
                                return Promise.resolve();
                            }
                        }
                    ]}
                >
                    <InputNumber suffix="元" placeholder="请输入" precision={2} style={{ width: '100%' }} />
                </Form.Item>
            </> : <>
                <Form.Item label={<strong>充值项</strong>} name="vipConfigId" rules={[{ required: true, message: '请选择充值项!' }]}>
                    <Select
                        showSearch
                        allowClear
                        placeholder="请选择充值项"
                        filterOption={(input, option) =>
                            ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                        }
                        options={[
                            { label: '365元包一年', value: '365元包一年' },
                            { label: '399元包一年', value: '399元包一年' },
                            { label: '666元包一年', value: '666元包一年' },
                            { label: '499元包一年', value: '499元包一年' },
                            { label: '499元买一年送一年', value: '499元买一年送一年' },
                            { label: '666买一年送一年', value: '666买一年送一年' },
                            { label: '888元包一年', value: '888元包一年' },
                            { label: '288元包一年', value: '288元包一年' },
                            { label: '199元包一个月', value: '199元包一个月' }
                        ]}
                    />
                </Form.Item>
            </>}
            <Form.Item label={<strong>限购频次</strong>} name="rechargeFrequency" rules={[{ required: true, message: '请选择限购频次!' }]}>
                <Radio.Group
                    buttonStyle="solid"
                    options={[
                        { value: 0, label: '按次数' },
                        { value: 1, label: '每天' },
                    ]}
                />
            </Form.Item>
            <Form.Item label={<strong>限购次数</strong>} name="rechargeTimes" rules={[{ required: true, message: '请选择限购次数!' }]}>
                <Select
                    showSearch
                    allowClear
                    placeholder="请选择限购次数"
                    filterOption={(input, option) =>
                        ((option?.label ?? '') as string).toLowerCase().includes(input.toLowerCase())
                    }
                    options={[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(item => ({ label: item === -1 ? '不限' : item + '次', value: item }))}
                />
            </Form.Item>
        </Form>
    </Modal>
};

export default React.memo(SetConfig);