import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Form, Select, DatePicker, Button, Input, Drawer, message } from 'kts-xui';
import { Row, Divider, TreeSelect } from 'kts-components-antd-x4';
import debounce from 'lodash/debounce';
import agent from '../Server';
import moment from 'moment';
const { RangePicker } = DatePicker;
const AddTemplate = (props: any) => {
    const [form] = Form.useForm();
    const [template, setTemplate] = useState<any>();
    const [rules, setRules] = useState<any>([]);
    const [groupUuid, setUuid] = useState();
    const [templateUuid, setTemplateId] = useState();
    const [goods, setGoods] = useState<any>([]);
    const [goodsName, setGoodsName] = useState();
    const formItemLayout = {
        labelCol: { span: 24 },
        wrapperCol: { span: 24 },
    };
    useEffect(() => {
        onSearch('');
        let cloneData = JSON.parse(JSON.stringify(props.data));
        setUuid(props.data.groupUuid);
        setTemplateId(props.data.templateUuid);
        form.setFieldsValue({ time: [moment(props.data.youxiao['effectiveStart']), moment(props.data.youxiao['effectiveEnd'])] })
        delete cloneData.updateTime;
        delete cloneData.youxiao;
        delete cloneData.groupUuid;
        delete cloneData.templateUuid;
        setRules(cloneData);
        setTemplate(cloneData);
    }, []);
    const onFinish = useCallback(async (values) => {
        const keys = Object.keys(values);
        let d: any = [];
        for (var i in rules) {
            if (keys.includes(rules[i].field)) {
                d.push({
                    ...rules[i],
                    fieldExpectValue: values[rules[i].field]
                });
            }
        }
        const dd = {
            ...values,
            effectiveStart: moment(values['time'][0]).format('YYYY-MM-DD'),
            effectiveEnd: moment(values['time'][1]).format('YYYY-MM-DD'),
            data: d,
            groupUuid,
            templateUuid
        };
        const res: any = await agent.post('/web/verifier/rule/update', dd, this);
        if (res.res) {
            message.success('操作成功');
            onSuccess();
        }
    }, [template, rules]);
    const onSuccess = () => {
        props.onSuccess();
    }
    const onClose = () => {
        props.onClose();
    };
    const onSubmit = () => {
        form.submit();
    };
    const labels = template && Object.keys(template);
    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);
            })
            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
        }
    }
    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>
            }
        >
            {template && <Form  {...formItemLayout} layout="vertical" form={form} onFinish={onFinish}>
                <Form.Item label="规则有效性设置" name='time' rules={[{ required: true, message: '请输入必填项' }]}>
                    <RangePicker style={{ width: '100%' }} />
                </Form.Item>
                <Divider />
                {
                    labels.length > 0 && labels.map((item, index) => {
                        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 initialValue={template[item].fieldExpectValue} 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 = JSON.parse(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 initialValue={template[item].fieldExpectValue} rules={[{ required: true, message: '请输入必填项' }]} key={index} name={template[item].field} label={'内容（支持输入多个内容，用“,”间隔）'} >
                                        {/* <Select 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;