import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Form, AutoComplete, DatePicker, Button, Input, Drawer, message } from 'kts-xui';
import { Row, Divider,  TreeSelect } from 'kts-components-antd-x4';
import agent from '../Server';
import moment from 'moment';
const { RangePicker } = DatePicker;
const AddTemplate = (props: any) => {
    const [form] = Form.useForm();
    const uuid=React.useMemo(()=>props.uuid,[]);
    const [template, setTemplate] = useState<any>({});
    const [rules, setRules] = useState<any>([]);
    // const [templateUuid, setUuid] = useState();
    const [goods, setGoods] = useState<any>([]);
    const [goodsName, setGoodsName] = useState();


    const formItemLayout = {
        labelCol: { span: 24 },
        wrapperCol: { span: 24 },
    };
    useEffect(() => {
        onSearch('');
        (async () => {
            const res: any = await agent.post('/web/verifier/rule/get-template', {templateUuid:uuid}, this);

            if (res.res) {
                const data = res.res.reduce((acc, obj) => {
                    const key = obj.field;
                    acc[key] = obj;
                    return acc;
                }, {});
                // setUuid(res.res[0].templateUuid);
                setTemplate(data);
                setRules(res.res);
            }
        })()
    }, []);
    const onFinish = useCallback(async (values) => {
        const keys = Object.keys(values);
        const d = rules.reduce((item, b) => {
            if (keys.includes(b.field)) {
                item.push({
                    ...b,
                    fieldExpectValue: values[b.field]
                });
                return item;
            } else {
                return item
            }
        }, [])
        const dd = {
            ...values,
            effectiveStart: moment(values['time'][0]).format('YYYY-MM-DD'),
            effectiveEnd: moment(values['time'][1]).format('YYYY-MM-DD'),
            data: d,
            templateUuid:uuid
        };
        const res: any = await agent.post('/web/verifier/rule/insert', dd, this);
        if (res.res) {
            message.success('操作成功');
            onSuccess();
        }
    }, [template, rules]);
    const onSuccess = () => {
        props.onSuccess();
    }
    const onClose = () => {
        props.onClose();
    };
    const onSubmit = () => {
        form.submit();
    };
    const onSearch = async (value) => {
        const params = {
            categoryName: value
        }
        const res: any = await agent.post('/product/platform/productCategory', params, this);
        if (res.res) {
            res.res = res.res.map(item => {
                return loopChildData(item);
            })
            console.log(res.res);
            setGoods(res.res);
        }

    }

    const loopChildData = (item) => {
        if (item.children && item.children.length > 0) {
            item = {
                ...item,
                label: item.categoryName,
                value: item.categoryName,
            }
            item.children = item.children.map(ele => {
                return loopChildData(ele);
            })
            return item;
        } else {
            return {
                ...item,
                label: item.categoryName,
                value: item.categoryName,
            }
        }
    }
    const onSelect = (value) => {
        const found = goods.find(item => item.id === value);
        if (found) {
            setGoodsName(found.categoryName);
        }
    }
    const setLength = (field: string) => {
        if (field === 'buyerName' || field === 'salerName') {
            return 100
        } else if (field === 'goodsName') {
            return 200
        } else if (field === 'specificationModel') {
            return 400
        }
    }
    const labels = template && Object.keys(template);
    return (
        <Drawer
            title='新增有效性规则'
            visible={true}
            onClose={onClose}
            footer={
                <div
                    style={{
                        textAlign: 'right',
                    }}
                >
                    <Button onClick={onClose} style={{ marginRight: 8 }}>
                        取消
                    </Button>
                    <Button onClick={onSubmit} type="primary">
                        提交
                    </Button>
                </div>
            }
        >
            <Form {...formItemLayout} layout="vertical" form={form} onFinish={onFinish}>
                <Form.Item initialValue={[moment().month(0).date(1), moment().month(11).date(31)]} label="规则有效时间" name='time' rules={[{ required: true, message: '请输入必填项' }]}>
                    <RangePicker style={{ width: '100%' }} />
                </Form.Item>
                <Divider />
                {
                    labels.length > 0 && labels.map((item, index) => {
                        if (template[item].active === true) {
                            if (template[item].field !== 'classify') {
                                return (
                                    <   >
                                        <Row justify='space-between'>
                                            <p style={{ fontWeight: 'bold' }}>校验字段:<span style={{ color: '#0074FF', fontWeight: 'normal' }}>{template[item].fieldDesc}</span></p>
                                            <p style={{ fontWeight: 'bold' }}>校验规则:{template[item].operatorDesc}</p>
                                        </Row>
                                        <Form.Item rules={[{ required: true, message: '请输入必填项', }]} key={index} name={template[item].field} label={'内容（支持输入多个内容，用“,”间隔）'} >
                                            <Input maxLength={setLength(template[item].field)} />
                                        </Form.Item>
                                        <Divider />
                                    </>
                                );
                            } else {
                                const { config } = template[item];
                                const fieldDescs = config.filter(ele => ele.active);
                                const titles = fieldDescs.reduce((acc, obj) => {
                                    acc.push(obj.fieldDesc);
                                    return acc;
                                }, []);
                                const title = '分类下' + titles.join('和')
                                return (
                                    <>
                                        <p style={{ fontWeight: 'bold' }}>校验字段:<span style={{ color: '#0074FF', fontWeight: 'normal' }}>{template[item].fieldDesc} </span>({title})</p>
                                        <p style={{ fontWeight: 'bold' }}>校验规则:{template[item].operatorDesc}</p>
                                        <Form.Item rules={[{ required: true, message: '请输入必填项' }]} key={index} name={template[item].field} label={'内容（支持输入多个内容，用“,”间隔）'} >
                                            {/* <Select showSearch={true} placeholder='请输入要查询的内容' style={{ width: '100%', }} onSelect={onSelect} onSearch={debounce(onSearch, 800)} >
                                                {goods.map((item) => (
                                                    <Select.Option key={item.id} value={item.categoryName}>
                                                        {item.categoryName}
                                                    </Select.Option>
                                                ))}
                                            </Select> */}
                                            <TreeSelect
                                                showSearch={true}
                                                treeNodeFilterProp='categoryName'
                                                style={{ width: '100%' }}
                                                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                                                treeData={goods}
                                                treeDefaultExpandAll
                                                onChange={onSelect}
                                            />
                                        </Form.Item>
                                    </>
                                );
                            }

                        }
                    })
                }

            </Form>

        </Drawer>
    );

}
export default AddTemplate;