import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Form, Modal, Divider, Checkbox } from 'antd';

import styles from './incident.less';
import Sortable from 'sortablejs';
const CheckboxGroup = Checkbox.Group;
const AddModal = props => {
    const { callBackSubmit = () => { }, isType, pickItem, visible, filed, filed1, characterValue, newCheckedList, flag } = props;
    const [loading, setLoading] = useState(false);
    const [value, setValue] = useState('');
    const [checkValue, setCheckValue] = useState([]);
    const [form] = Form.useForm();
    const [title, setTitle] = useState([])
    const { Item } = Form;
    const [checkedList, setCheckedList] = useState([]);//选中的复选框内容
    const [indeterminate, setIndeterminate] = useState([]);
    const [checkAll, setCheckAll] = useState([]);
    const [selectData, setSelectData] = useState([])
    let objArr = []
    
    const onChangeList = (list, index, title) => {
        const checkedListArr = [...checkedList]
        checkedListArr[index] = list
        setCheckedList(checkedListArr);
        const indeterminateArr = [...indeterminate]
        const checkAllArr = [...checkAll]
        indeterminateArr[index] = !!list.length && list.length < filed[title].length
        checkAllArr[index] = list.length === filed[title].length
        setIndeterminate(indeterminateArr)
        setCheckAll(checkAllArr);
    };
    const onChangeList1 = (list, index, title) => {
        const checkedListArr = [...checkedList]
        checkedListArr[index] = list
        setCheckedList(checkedListArr);
        const indeterminateArr = [...indeterminate]
        const checkAllArr = [...checkAll]
        indeterminateArr[index] = !!list.length && list.length < filed1[title].length
        checkAllArr[index] = list.length === filed1[title].length
        setIndeterminate(indeterminateArr)
        setCheckAll(checkAllArr);
    };

    const onSubmit = () => {
        isType === 'rule' ? callBackSubmit(`${value === '无' || value === '' ? '' : value + ','}${checkValue.join(',')}`) : callBackSubmit({ checkedList, str: selectData.join(","), pickItem, stt: selectData, title: title, filed22: filed1, isType: isType });
    }
    const onCheckAllChange = e => {
        const indeterminateArr = [...indeterminate]
        const checkAllArr = [...checkAll]
        const checkedListArr = [...checkedList]
        checkAllArr[e.target.index] = e.target.checked
        indeterminateArr[e.target.index] = false
        e.target.checked ? checkedListArr[e.target.index] = e.target.checkvalue : checkedListArr[e.target.index] = []
        setCheckedList(checkedListArr);
        setIndeterminate(indeterminateArr);
        setCheckAll(checkAllArr);
    };
    useEffect(() => {
        console.log(filed1)
        selectAll()
    }, [checkedList]);

    const selectAll = () => {
        objArr = []
        checkedList.map(item => {
            objArr = objArr.concat(item)
        })
        setSelectData(objArr)
    }

    useEffect(() => {
        if (isType != '' && isType === 'add') {
            console.log(filed)
            let arr = Object.keys(filed)
            console.log(arr, 'arr')
            setTitle(arr)
            let checkArr = []
            let indeterminateArr = []
            let checkAllArr = []
            console.log(newCheckedList);
            // let b = []
            // let a = []
            arr.map((item, index) => {
                // filed[item].map((i, j) => {
                //     b.push(i)
                // })
                checkArr[index] = []
                newCheckedList.map(checkItem => {
                    if (filed[item].includes(checkItem)) {
                        checkArr[index].push(checkItem)
                    }
                })
                indeterminateArr.push(!!checkArr[index].length && checkArr[index].length < filed[item].length)
                checkAllArr.push(checkArr[index].length === filed[item].length)
            })
            // newCheckedList.map((item, index) => {
            //     if (b.includes(item) == false) {
            //         if(item == ''){
            //             a=[]
            //         }else{
            //             a.push(item)
            //         }
                    
            //     }
            // })
            // if(a.length >0){
            //     filed.外部字段 = a
            //     console.log(filed)
            //     arr.push('外部字段')
            // }
            // setTitle(arr) 
            // checkArr.push(a)
            setCheckedList(checkArr)
            setIndeterminate(indeterminateArr)
            setCheckAll(checkAllArr)
            console.log(characterValue)
            let newArr = characterValue.length ? characterValue.split(",") : []
            console.log(newArr)
            setSelectData(newArr)
            draftSort()
        } else if (isType === 'app') {
            console.log(filed1)
            let arr = Object.keys(filed1)
            console.log(arr, 'arr')
            setTitle(arr)
            let checkArr = []
            let indeterminateArr = []
            let checkAllArr = []
            console.log(newCheckedList);
            // let b = []
            // let a = []
            arr.map((item, index) => {
                // filed1[item].map((i, j) => {
                //     b.push(i)
                // })
                checkArr[index] = []
                newCheckedList.map(checkItem => {
                    if (filed1[item].includes(checkItem)) {
                        checkArr[index].push(checkItem)
                    }
                })
                indeterminateArr.push(!!checkArr[index].length && checkArr[index].length < filed1[item].length)
                checkAllArr.push(checkArr[index].length === filed1[item].length)
            })
            // newCheckedList.map((item, index) => {
            //     if (b.includes(item) == false) {
            //         if(item == ''){
            //             a=[]
            //         }else{
            //             a.push(item)
            //         }
                    
            //     }
            // })
            // if(a.length >0){
            //     filed1.外部字段 = a
            //     console.log(filed1)
            //     arr.push('外部字段')
            // }
            // setTitle(arr) 
            // checkArr.push(a)
            setCheckedList(checkArr)
            setIndeterminate(indeterminateArr)
            setCheckAll(checkAllArr)
            console.log(characterValue)
            let newArr = characterValue.length ? characterValue.split(",") : []
            console.log(newArr)
            setSelectData(newArr)
            draftSort()
        }

    }, [visible]);

    //拖拽初始化及逻辑
    const draftSort = () => {
        let el = document.getElementById('doctor-drag-items');
        if (el) {
            let sortable = Sortable.create(el, {
                animation: 100, //动画参数
                onEnd: function (evt) { //拖拽完毕之后发生，只需关注该事件
                    let arr = [];
                    let len = evt.from.children.length;
                    for (let i = 0; i < len; i++) {
                        arr.push(evt.from.children[i].getAttribute('drag-id'))
                    }
                    console.log(arr)
                    setSelectData(arr)
                }
            });
        }

    }
    if (isType != 'app') {
        return (
            <Modal
                title='字段集选择'
                bodyStyle={{ width: '100%', minHeight: '100px' }}
                width="700px"
                destroyOnClose
                centered={true}
                cancelText="取消"
                okText="确认"
                {...props}
                onOk={() => onSubmit()}
                forceRender={true}
                getContainer={false}
            >
                {visible && (
                    <div className={styles.listCard}>
                        <div className={styles.cardItem} style={{ borderRight: '1px solid #99bbe8' }}>
                            <Divider orientation="left" style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}>待选字段列表</Divider>

                            {flag === 0 ?
                                <>
                                    <div className={styles.cardContent}>
                                        <span style={{ color: 'red', fontSize: '1rem', marginLeft: '25px' }}>请先选择事件主表</span>
                                    </div>
                                </> :
                                <>
                                    {JSON.stringify(filed) == "{}" ?
                                        <>
                                            <div className={styles.cardContent}>
                                                <span style={{ color: 'red', fontSize: '1rem', marginLeft: '25px' }}>表字段缺失请先配置表/字段</span>
                                            </div>
                                        </>
                                        :
                                        <>
                                            <div className={styles.cardContent}>
                                                {title.map((item, index) => {
                                                    return <div className={styles.cardItemData} key={index}>
                                                        <Divider orientation="left" style={{ margin: '0 0 10px 0', color: '#15428b', borderTopColor: '#99bbe8' }}><Checkbox indeterminate={indeterminate[index]} onChange={onCheckAllChange} index={index} checkvalue={filed[item]} checked={checkAll[index]} style={{ marginRight: '7px' }}></Checkbox>{item}</Divider>
                                                        <CheckboxGroup options={filed[item]} value={checkedList[index]} onChange={(e) => onChangeList(e, index, item)} />
                                                    </div>
                                                })}
                                            </div>
                                        </>
                                    }

                                </>

                            }

                        </div>
                        <div className={styles.cardItem}>
                            <Divider orientation="left" style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}>已选字段列表</Divider>
                            <div className={styles.cardContent}>
                                <div className={styles.doctorTable}>
                                    <table>
                                        <thead>
                                            <tr>
                                                <td>字段名</td>
                                            </tr>
                                        </thead>
                                        <tbody id='doctor-drag-items'>
                                            {selectData && selectData.length > 0 ?
                                                selectData.map((item, index) => {
                                                    return <tr drag-id={item} key={index} style={{ cursor: 'move' }}>
                                                        <td><span title={item}>{item}</span></td>
                                                    </tr>
                                                })
                                                : <tr><td colSpan='10' style={{ textAlign: 'center' }}>暂无数据</td></tr>
                                            }
                                        </tbody>
                                    </table>
                                </div>

                            </div>
                        </div>
                    </div>
                )

                }
            </Modal>
        );
    } else if (isType === 'app') {
        return (
            <Modal
                title='部门或角色'
                bodyStyle={{ width: '100%', minHeight: '100px' }}
                width="700px"
                style={{ top: '10px' }}
                destroyOnClose
                centered={true}
                cancelText="取消"
                okText="确认"
                {...props}
                onOk={() => onSubmit()}
                forceRender={true}
                getContainer={false}
            >
                {visible && (
                    <div className={styles.listCard}>
                        <div className={styles.cardItem} style={{ borderRight: '1px solid #99bbe8' }}>
                            <Divider orientation="left" style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}>待选部门角色站点</Divider>
                            <div className={styles.cardContent}>
                                {title.map((item, index) => {
                                    return <div className={styles.cardItemData} key={index}>
                                        <Divider orientation="left" style={{ margin: '0 0 10px 0', color: '#15428b', borderTopColor: '#99bbe8' }}><Checkbox indeterminate={indeterminate[index]} onChange={onCheckAllChange} index={index} checkvalue={filed1[item]} checked={checkAll[index]} style={{ marginRight: '7px' }}></Checkbox>{item}</Divider>
                                        <CheckboxGroup options={filed1[item]} value={checkedList[index]} onChange={(e) => onChangeList1(e, index, item)} /></div>
                                })}
                            </div>
                        </div>
                        <div className={styles.cardItem}>
                            <Divider orientation="left" style={{ margin: '0 0 10px 0', backgroundColor: '#dfe8f6' }}>已选列表</Divider>
                            <div className={styles.cardContent}>
                                <div className={styles.doctorTable}>
                                    <table>
                                        <thead>
                                            <tr>
                                                <td>字段名</td>
                                            </tr>
                                        </thead>
                                        <tbody id='doctor-drag-items'>
                                            {selectData && selectData.length > 0 ?
                                                selectData.map((item, index) => {
                                                    return <tr drag-id={item} key={index} style={{ cursor: 'move' }}>
                                                        <td><span title={item}>{item}</span></td>
                                                    </tr>
                                                })
                                                : <tr><td colSpan='10' style={{ textAlign: 'center' }}>暂无数据</td></tr>
                                            }
                                        </tbody>
                                    </table>
                                </div>

                            </div>
                        </div>
                    </div>
                )

                }
            </Modal>
        );
    }
};
export default AddModal;