import { Button } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { unstable_batchedUpdates as batch } from 'react-dom';
import { XForm } from '../packages/react/src/index';

const defaultValues = {
    id: 1,
    activityName: '2020-02-06test1',
    ranks: [
        {
            rankId: 1,
            liveType: 2,
            rankMemberType: 1,
            rankGiftType: 2,
            notScoreFreeGift: false,
            specifyGifts: [
                { giftId: 1, ratio: 2 },
                { giftId: 2, ratio: 4 },
                { giftId: 3, ratio: 3.5 }
            ],
            topLimit: 99,
            specifyUserType: 1,
            whiteUserIds: [70534, 49965, 78528]
        }
    ],
    timeRange: [moment(1582187791000), moment(1582274192000)]
};

const limitPositiveInts = (value: string | number) => {
    const reg = /^([1-9])(\d*).*$/;
    if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2') : '';
    } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2') : '';
    } else {
        return '';
    }
};

const limitDecimals = (value: string | number) => {
    const reg = /^(\-)*(\d+)\.(\d\d).*$/;
    if (typeof value === 'string') {
        return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : '';
    } else if (typeof value === 'number') {
        return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : '';
    } else {
        return '';
    }
};

const makeSchema = (values: any) => {
    return [
        ...(values
            ? [
                  {
                      key: 'id',
                      type: 'Input',
                      status: 'preview',
                      ui: {
                          label: '活动Id',
                          tooltip: '由后台自动生成'
                      }
                  }
              ]
            : []),
        {
            key: 'activityName',
            type: 'Input',
            ui: {
                label: '活动名称',
                tooltip: '不能超过30个字符，中英文都算作1个字符',
                required: true
            },
            props: {
                placeholder: '请输入活动名称，不能超过30个字符',
                maxLength: 30
            },
            rules: [
                {
                    required: true,
                    message: '请填写活动名称'
                }
            ]
        },
        {
            key: 'ranks',
            type: 'Array',
            value: [{}],
            ui: {
                label: '榜单配置',
                tooltip: '最少添加 1 个榜单，最多添加 10 个榜单',
                required: true
            },
            props: {
                type: 'Card',
                max: 10,
                min: 1,
                cardTitleKey: 'blackUserIds'
            },
            children: [
                ...(values
                    ? [
                          {
                              key: 'rankId',
                              type: 'Input',
                              status: 'preview',
                              ui: {
                                  label: '榜单Id',
                                  tooltip: '由后台自动生成'
                              }
                          }
                      ]
                    : []),
                {
                    key: 'liveType',
                    type: 'Radio',
                    value: 0,
                    ui: {
                        label: '榜单分区',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    options: [
                        { name: '全区', value: 0 },
                        { name: '视频', value: 1 },
                        { name: '音频', value: 2 }
                    ]
                },
                {
                    key: 'rankMemberType',
                    type: 'Radio',
                    value: 1,
                    ui: {
                        label: '榜单类型',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    options: [
                        { name: '主播榜', value: 1 },
                        { name: '用户榜', value: 2 }
                    ]
                },
                {
                    key: 'rankGiftType',
                    type: 'Radio',
                    value: 1,
                    ui: {
                        label: '统计内容',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    options: [
                        { name: '音符榜（统计所有礼物）', value: 1 },
                        { name: '道具榜（统计特定礼物）', value: 2 }
                    ]
                },
                {
                    key: 'giftIntegralRatio',
                    type: 'InputNumber',
                    value: 1,
                    ui: {
                        label: '积分计算',
                        tooltip: '1音符等于多少积分',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    props: {
                        placeholder: '>0两位小数',
                        min: 0.01,
                        step: 0.01,
                        formatter: limitDecimals,
                        parser: limitDecimals
                    },
                    listeners: [
                        {
                            watch: ['rankGiftType'],
                            condition: 'rankGiftType.value != 1',
                            set: {
                                status: 'hidden'
                            }
                        }
                    ],
                    rules: [
                        {
                            required: true,
                            message: '请填写积分计算'
                        }
                    ]
                },
                {
                    key: 'notScoreFreeGift',
                    type: 'Switch',
                    value: false,
                    ui: {
                        label: '免费礼物不计入积分',
                        tooltip: '不勾选此项，免费礼物会按照比例计入积分',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    listeners: [
                        {
                            watch: ['rankGiftType'],
                            condition: 'rankGiftType.value != 1',
                            set: {
                                status: 'hidden'
                            }
                        }
                    ]
                },
                {
                    key: 'specifyGifts',
                    type: 'Array',
                    ui: {
                        label: '积分计算',
                        tooltip: '最少添加 1 个礼物，最多添加 10 个礼物',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    props: {
                        type: 'Table',
                        max: 10,
                        min: 1
                    },
                    children: [
                        {
                            key: 'giftId',
                            type: 'InputNumber',
                            ui: {
                                label: '礼物Id',
                                required: true
                            },
                            props: {
                                placeholder: '礼物Id',
                                min: 1,
                                step: 1,
                                formatter: limitPositiveInts,
                                parser: limitPositiveInts
                            },
                            rules: [
                                {
                                    required: true,
                                    message: '请填写礼物Id'
                                }
                            ]
                        },
                        {
                            key: 'giftName',
                            type: 'Input',
                            status: 'preview',
                            ui: {
                                label: '礼物名称'
                            },
                            listeners: [
                                {
                                    watch: ['giftId'],
                                    set: (
                                        _valid: any,
                                        field: any,
                                        form: any
                                    ) => {
                                        const id = form.getValue('giftId');
                                        if (!id) {
                                            return;
                                        }
                                        field.setValue(id);
                                        // form.fieldMap['giftId'].setValid({
                                        //     valid: false,
                                        //     message: '查询不到该id对应的礼物',
                                        //     status: 'warning'
                                        // });
                                    }
                                }
                            ]
                        },
                        {
                            key: 'ratio',
                            type: 'InputNumber',
                            value: 1,
                            ui: {
                                label: '对应积分',
                                required: true
                            },
                            props: {
                                placeholder: '>=1整数',
                                min: 1,
                                step: 1,
                                formatter: limitPositiveInts,
                                parser: limitPositiveInts
                            },
                            rules: [
                                {
                                    required: true,
                                    message: '请填写对应积分'
                                }
                            ]
                        }
                    ],
                    listeners: [
                        {
                            watch: ['rankGiftType'],
                            condition: 'rankGiftType.value != 2',
                            set: {
                                status: 'hidden'
                            }
                        }
                    ],
                    rules: [
                        {
                            type: 'array',
                            required: true,
                            message: '请添加至少一个礼物'
                        }
                    ]
                },
                {
                    key: 'topLimit',
                    type: 'InputNumber',
                    value: 200,
                    ui: {
                        label: '榜单显示个数',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    props: {
                        placeholder: '>=1整数',
                        min: 1,
                        step: 1,
                        formatter: limitPositiveInts,
                        parser: limitPositiveInts
                    },
                    rules: [
                        {
                            required: true,
                            message: '请填写榜单显示个数'
                        }
                    ]
                },
                {
                    key: 'specifyUserType',
                    type: 'Radio',
                    value: 1,
                    ui: {
                        label: '参与活动UID',
                        required: true,
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    options: [
                        { name: '全区', value: 1 },
                        { name: '黑名单', value: 2 },
                        { name: '白名单', value: 3 }
                    ]
                },
                {
                    key: 'blackUserIds',
                    type: 'TextArea',
                    ui: {
                        label: '黑名单',
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    props: {
                        placeholder: '请输入UID，多个UID请用英文逗号或换行分隔',
                        autoSize: true
                    },
                    listeners: [
                        {
                            watch: ['specifyUserType'],
                            condition: 'specifyUserType.value != 2',
                            set: {
                                status: 'hidden'
                            }
                        }
                    ],
                    rules: [
                        {
                            required: true,
                            message: '请填写黑名单'
                        }
                    ]
                },
                {
                    key: 'whiteUserIds',
                    type: 'TextArea',
                    ui: {
                        label: '白名单',
                        labelCol: { span: 6 },
                        wrapperCol: { span: 18 }
                    },
                    props: {
                        placeholder: '请输入UID，多个UID请用英文逗号或换行分隔',
                        autoSize: true
                    },
                    listeners: [
                        {
                            watch: ['specifyUserType'],
                            condition: 'specifyUserType.value != 3',
                            set: {
                                status: 'hidden'
                            }
                        }
                    ],
                    rules: [
                        {
                            required: true,
                            message: '请填写白名单'
                        }
                    ]
                }
            ],
            rules: [
                {
                    type: 'array',
                    required: true,
                    message: '请添加至少一个榜单'
                }
            ]
        },
        {
            key: 'timeRange',
            type: 'RangePicker',
            ui: {
                label: '活动时间范围',
                tooltip: '活动开始时间距离上一个活动结束时间必须超过5分钟',
                required: true
            },
            props: {
                placeholder: ['请选择上线时间', '请选择下线时间'],
                showTime: { format: 'HH:mm:ss' },
                disabledDate: (current: any) =>
                    current && current < moment().subtract(1, 'days')
            },
            rules: [
                {
                    required: true,
                    message: '请选择活动时间范围'
                }
            ]
        }
    ];
};

export default function() {
    const formRef = useRef(null);
    const [schema, setSchema] = useState(makeSchema(null));
    const [status, setStatus] = useState('edit');
    const [values, setValues] = useState(null);

    const onSubmit = () => {
        formRef.current.submit().then((data: any) => {
            console.log(data);
        });
    };

    const onAdd = () => {
        batch(() => {
            // formRef.current.reset();
            setSchema(makeSchema(null));
            setStatus('edit');
            setValues(null);
        });
    };

    const onReset = () => {
        batch(() => {
            setSchema(makeSchema({...defaultValues}));
            setStatus('edit');
            setValues(defaultValues);
        });
    };

    const onView = () => {
        batch(() => {
            setSchema(makeSchema({...defaultValues}));
            setValues(defaultValues);
            setStatus('preview');
        });
    };

    return (
        <>
            <XForm
                className={'test'}
                ref={formRef}
                schema={schema}
                status={status}
                values={values}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 18 }}
            />
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'center',
                    marginBottom: '60px'
                }}
            >
                <Button type="primary" onClick={onSubmit}>
                    提交
                </Button>
                <Button style={{ marginLeft: '10px' }} onClick={onAdd}>
                    新建
                </Button>
                <Button style={{ marginLeft: '10px' }} onClick={onReset}>
                    编辑
                </Button>
                <Button style={{ marginLeft: '10px' }} onClick={onView}>
                    查看详情
                </Button>
            </div>
        </>
    );
}
