/** @format */

import * as React from 'react';
import { RcFile } from 'antd/es/upload';
import message from "../../../../components/message"
import { Form, Upload, Input, Icon, Row, Col, Switch, Spin, notification } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { GetFieldDecoratorOptions } from 'antd/es/form/Form';
import { phonePattern, adminPasswordPattern } from "../../../../const/regular"
import Modal from '../../../../components/modalForm';
import { ReciveMerchantProps } from '../../../../service/merchant';
import { validatorIp } from '../../../../utils/validator';
import { useOss } from '../../../../service/oss';
const { Password } = Input
const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
};

interface MerchantFormProps {
    title: string;
    visible?: boolean;
    values?: ReciveMerchantProps;
    loading?: boolean;
    onCancel?: () => void;
    onSubmit?: (values: any) => void;
    type?: "insert" | "update"
}
interface FormLableItem extends GetFieldDecoratorOptions {
    label?: string;
    Component: React.ReactNode;
    key: string;
}
const merchantForm: React.FC<FormComponentProps & MerchantFormProps> = props => {
    const { form, title, loading = false, type = "update", visible = false, values, children, onCancel, onSubmit } = props;
    const { getFieldDecorator, validateFieldsAndScroll, setFieldsValue, resetFields } = form;
    const [uploadState, requestUpload] = useOss();
    const handleSubmit = () => {
        if (uploadState.loading) {
            return message.error("图片上传中,请稍后")
        }
        validateFieldsAndScroll((error, values) => {
            if (error) return;
            onSubmit && onSubmit(values)
        })
    }
    const beforeUpload: (file: RcFile, FilseList: RcFile[]) => boolean = (file, FileList) => {
        validateFieldsAndScroll(['merchant_name'], (errors, values) => {
            if (!errors) {
                const { name } = file;
                const filename = values.merchant_name + name.slice(name.lastIndexOf('.'));
                requestUpload(filename, file)
                    .then((result: any) => {
                        const { url } = result;
                        setFieldsValue({
                            merchant_license: url
                        })
                    })
                    .catch(error => {
                        notification.error({
                            message: "文件上传失败",
                            description: error,
                        })
                    });
            }
        });
        return false;
    };
    const Dragger = React.forwardRef((props: any, ref) => {
        const { value, onChange, ...rest } = props
        const fileList = value ? [{ name: value, uid: "merchant_license" }] : []
        return (
            <Spin spinning={uploadState.loading}>
                <Upload.Dragger
                    ref={ref}
                    accept='image/*'
                    beforeUpload={beforeUpload}
                    fileList={fileList}
                    {...rest}
                >
                    {value ?
                        <img style={{ width: 200 }} src={value} alt="" />
                        : <>
                            <p className='ant-upload-drag-icon'>
                                <Icon type='inbox' />
                            </p>
                            <p className='ant-upload-text'>点击选择上传文件</p>
                            <p className='ant-upload-hint'>仅支持选择图片</p>
                        </>}
                </Upload.Dragger>
            </Spin>
        )
    })
    const formItems: { title: string; child: FormLableItem[] }[] = [
        {
            title: '基本信息',
            child: [
                {
                    label: '用户名',
                    key: 'name',
                    initialValue: values?.name || "",
                    rules: [
                        {
                            required: true,
                            message: '请输入用户名',
                        },
                        {
                            whitespace: true,
                            message: '请输入用户名',

                        }
                    ],
                    Component: <Input autoComplete='off' placeholder='请输入用户名' />,
                },
                {
                    label: '手机号',
                    initialValue: values?.phone || '',
                    key: 'phone',
                    rules: [{
                        pattern: phonePattern,
                        message: "请输入正确的手机号!"
                    }, {
                        required: true,
                        message: "请输入正确的手机号!"
                    }],
                    Component: <Input autoComplete='off' placeholder='请输入手机号' />,
                },
                {
                    label: '密码',
                    key: 'password',
                    initialValue: values?.password || '',
                    Component: <Password autoComplete='off' placeholder='请输入密码' />,
                    rules: type === "insert" ? [
                        {
                            required: true,
                            message: '请设置密码',
                        },
                        {
                            pattern: adminPasswordPattern,
                            message: "字母和数字的组合，不少于8个，不超过12个字符",
                        }
                    ] : [
                        {
                            pattern: adminPasswordPattern,
                            message: "字母和数字的组合，不少于8个，不超过12个字符",
                        }],
                },
                {
                    label: '邮箱',
                    key: 'email',
                    initialValue: values?.email || '',
                    Component: <Input autoComplete='off' placeholder='请输入邮箱地址' />,
                    rules: [
                        {
                            type: 'email',
                            message: '请输入正确的邮箱地址',
                        },
                    ],
                },
            ],
        },
        {
            title: '认证信息',
            child: [
                {
                    label: '商户',
                    Component: <Input autoComplete='off' placeholder='请输入商户名' />,
                    key: 'merchant_name',
                    initialValue: values?.merchant_name || '',
                    rules: [
                        {
                            required: true,
                            message: '请输入商户名',
                        },
                        {
                            whitespace: true,
                            message: '请输入商户名',
                        }
                    ],
                },
                {
                    label: '信用码',
                    Component: <Input autoComplete='off' placeholder='请输入商户信用码' />,
                    key: 'social_code',
                    initialValue: values?.social_code || '',
                    rules: [
                        {
                            required: true,
                            message: '请输入商户信用码',
                        },
                    ],
                },
                {
                    label: '密码',
                    key: 'merchant_parssword',
                    initialValue: values?.merchant_parssword || '',
                    Component: <Password autoComplete='off' placeholder='请输入商户密码' />,
                    rules: type === "insert" ? [
                        {
                            required: true,
                            message: '请设置密码',
                        },
                        {
                            pattern: adminPasswordPattern,
                            message: "字母和数字的组合，不少于8个，不超过12个字符",
                        }
                    ] : [
                        {
                            pattern: adminPasswordPattern,
                            message: "字母和数字的组合，不少于8个，不超过12个字符",
                        }],
                },
                {
                    label: '邮箱',
                    key: 'memail',
                    initialValue: values?.memail || '',
                    Component: <Input autoComplete='off' placeholder='请输入商户邮箱地址' />,
                    rules: [
                        {
                            type: 'email',
                            message: '请输入正确的商户邮箱',
                        },
                    ],
                },
                {
                    label: '公司',
                    initialValue: values?.company_name || '',
                    key: 'company_name',
                    Component: <Input autoComplete='off' placeholder='请输入商户公司名' />,
                },
                {
                    label: '住址',
                    initialValue: values?.address || '',
                    key: 'address',
                    Component: <Input autoComplete='off' placeholder='请输入商户联系地址' />,
                },
                {
                    label: '联系人',
                    initialValue: values?.contact_name || '',
                    key: 'contact_name',
                    Component: <Input autoComplete='off' placeholder='请输入商户联系人' />,
                },
                {
                    label: '联系电话',
                    key: 'contact_number',
                    initialValue: values?.contact_number || '',
                    rules: [{
                        pattern: phonePattern,
                        message: "请输入正确的商户联系电话!"
                    }],
                    Component: <Input autoComplete='off' placeholder='请输入商户联系电话' />,
                },
                {
                    label: '营业执照',
                    key: 'merchant_license',
                    initialValue: values?.merchant_license,
                    Component: <Dragger></Dragger>,
                },
            ],
        },
        {
            title: '安全信息',
            child: [
                {
                    label: '是否预警',
                    key: 'warning_enable',
                    valuePropName: 'checked',
                    initialValue: values?.warning_enable || false,
                    Component: <Switch />,
                },
                {
                    label: '是否修改HTTP状态码',
                    key: 'is_http_code',
                    valuePropName: 'checked',
                    normalize: (value) => { if (value) { return 1 } else return 0 },
                    initialValue: values?.is_http_code || false,
                    Component: <Switch />,
                },
                {
                    label: 'IP白名单',
                    key: 'ip_whitelist',
                    initialValue: values?.ip_whitelist || '',
                    rules: [
                        {
                            validator: validatorIp,
                        },
                    ],
                    Component: (
                        <Input.TextArea
                            autoComplete='off'
                            rows={4}
                            placeholder='请输入IP白名单，格式：IP段以“*.*.*.*-*.*.*.*”形式，多个ip逗号分隔'
                        />
                    ),
                },
            ],
        },
    ];

    return (
        <>
            {children}
            <Modal loading={loading} onOk={handleSubmit} onCancel={() => {
                resetFields()
                onCancel && onCancel()
            }} title={title} destroyOnClose width={1000} style={{ top: 20 }} visible={visible}>
                <Form {...formItemLayout}>
                    {formItems.map((element, index) => {
                        return (
                            <Row key={index}>
                                <h3>{element.title}</h3>
                                {element.child.map(item => {
                                    const { label, key, rules, Component, ...rest } = item;
                                    return (
                                        <Col span={12} key={key}>
                                            <Form.Item label={label}>
                                                {getFieldDecorator(key, {
                                                    rules,
                                                    ...rest,
                                                })(Component)}
                                            </Form.Item>
                                        </Col>
                                    );
                                })}
                            </Row>
                        );
                    })}
                </Form>
            </Modal>
        </>
    );
};
export default Form.create<FormComponentProps & MerchantFormProps>({ name: 'merchantForm' })(merchantForm);
