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(() => { 
    //     (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 formatDate = (dateString) => {
        const [year, month, day] = dateString.match(/\d+/g);
        return `${year}${month.padStart(2, '0')}${day.padStart(2, '0')}`;
    };
    
    const [ranges, setRanges] = useState(props.timeList.map(item=>{
        let _times = item.split('-');
        return `${formatDate(_times[0])}-${formatDate(_times[1])}` ; // `${moment(_times[0]).format('YYYYMMDD')}-${moment(_times[0]).format('YYYYMMDD')}`;
    })||[]);

    // 定义一个函数来检查新日期范围是否可以添加到现有的日期范围数组
    const canAddDateRange = (existingRanges, newRange) => {
        const [newStart, newEnd] = newRange.map(date => moment(date, 'YYYYMMDD'));

        for (const range of existingRanges) {
            const [start, end] = range.split('-').map(date => moment(date, 'YYYYMMDD'));

            // 检查是否重叠
            const overlap = newStart.isBefore(end) && newEnd.isAfter(start);
            // 检查新日期范围的开始时间是否与任何现有范围的结束时间相同
            const startEqualsEnd = newStart.isSame(end);

            if (overlap || startEqualsEnd) {
                return false;
            }
        }

        return true;
    };
    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 newRangeTime = values.time;
        // console.log('23333',ranges, newRangeTime);;
        const isOverlapping = ranges.some(rangeStr => {
            let range = rangeStr.split('-');
            // console.log('dasdasdas', range, newRangeTime[0].isBefore(moment(range[1])) && newRangeTime[1].isAfter(moment(range[0])))
            return newRangeTime[0].isBefore(moment(range[1])) && newRangeTime[1].isAfter(moment(range[0]));
        } 
        ); 
        if (isOverlapping) {
            message.error('时间段不能重叠');
            return;
        } 
            // if (canAddDateRange(ranges, newRangeTime)) {
            //     // ranges.push(newRangeTime);
               
            // } else {
            //     message.error("新日期范围与现有范围重叠或起始时间与现有范围的结束时间相同，无法添加。");
            //     return;
            // }

            const dd = [...ranges, `${moment(newRangeTime[0]).format('YYYYMMDD')}-${moment(newRangeTime[1]).format('YYYYMMDD')}`];
            setRanges([...ranges, newRangeTime] as any);
            const res: any = await agent.post('/web/verifier/submitRange/saveOrUpdateSubmitRange', {submitRangeData: dd}, this);
            if (res.res) {
                message.success('新增成功');
                onSuccess();
            } 
            // message.success('时间段添加成功');
        // } 
       
    }, []);
    const onSuccess = () => {
        props.onSuccess();
    }
    const onClose = () => {
        props.onClose();
    };
    const onSubmit = () => {
        form.submit();
    }; 

    // 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,
    //         }
    //     }
    // }  
    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 />  
            </Form>

        </Drawer>
    );

}
export default AddTemplate;