import React, { useState, useEffect } from 'react';
import { Form, Modal, Input, Select, Checkbox, notification, Card } from 'antd';

import {
    loadTableFields, addTables, addFields
} from '@/services/platform/bs'
import styles from './index.less'
const CheckboxGroup = Checkbox.Group;
import qs from 'qs';
const { Option } = Select;
const AddModal = props => {
    const { callBackSubmit = () => { }, type, visible, tableList, formObj } = props;
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const { Item } = Form;
    const [plainOptions, setPlainOptions] = useState([]);//复选框所有内容
    const [checkedList, setCheckedList] = useState([]);//选中的复选框内容
    const [indeterminate, setIndeterminate] = useState(true);
    const [checkAll, setCheckAll] = useState(false);


    const onChange = list => {
        setCheckedList(list);
        setIndeterminate(!!list.length && list.length < plainOptions.length);
        setCheckAll(list.length === plainOptions.length);
    };

    const onCheckAllChange = e => {
        setCheckedList(e.target.checked ? plainOptions : []);
        setIndeterminate(false);
        setCheckAll(e.target.checked);
    };
    // 提交
    const onSubmit = () => {
        let fieldNames = [];
        (checkedList || []).map(item => {
            fieldNames.push({ fieldNames: item })
        })
        form.validateFields().then(validate => {
            if (validate) {
                let obj = form.getFieldsValue();
                setLoading(true);
                let data = {}, url = JSON.stringify(formObj) == '{}' ? addTables : addFields
                if (JSON.stringify(formObj) == '{}') {
                    data = { tableName: obj.tableName, alias: obj.tableAlias || '', fieldNames: checkedList.join(',') }
                }
                else {
                    data = { tableName: formObj.tableName, fieldNames: checkedList.join(',') }
                }
                url(data).then(res => {
                    setLoading(false);
                    if (res.msg === "Ok" || res.msg === "") {
                        form.resetFields();
                        callBackSubmit();
                        notification.success({
                            message: '提示',
                            duration: 3,
                            description: JSON.stringify(formObj) == '{}' ? '新增成功' : '表字段新增成功',
                        });

                    } else {
                        notification.error({
                            message: '提示',
                            duration: 3,
                            description: res.msg,
                        });
                    }
                })
                    .catch(err => {
                        notification.error({
                            message: '提示',
                            duration: 3,
                            description: '新增失败',
                        });
                        setLoading(false);
                    });

            }
        });
    };



    useEffect(() => {
        if (type != '' && JSON.stringify(formObj) == '{}') {
            renderField(tableList[0].text)
            form.setFieldsValue({
                tableName: tableList[0].text
            })
        } else if (type != '' && JSON.stringify(formObj) != '{}') {
            renderField(formObj.tableName)
        }

    }, [visible]);

    const renderField = (name) => {
        loadTableFields({ tableName: name }).then(response => {
            if (response.data.root.length) {
                let arr = [], newArr = []
                response.data.root.map(item => {
                    newArr.push(item.fieldName)
                    if (item.isCheck) {
                        arr.push(item.fieldName)
                    }
                })
                setCheckAll(false)
                setPlainOptions(newArr)
                setCheckedList(arr)
            }
        })
    }
    const layout = {
        layout: 'horizontal',
        labelCol: {
            span: 4,
        },
        wrapperCol: {
            span: 18,
        },
    };

    const handleChange = (value) => {
        renderField(value)
    }

    return (
        <Modal
            title={JSON.stringify(formObj) == '{}' ? '附加表' : '附加字段'}
            bodyStyle={{ width: '100%', minHeight: '200px' }}
            style={{ top: '150px' }}
            width="700px"
            destroyOnClose
            maskClosable={false}
            cancelText="取消"
            okText="确认"
            {...props}
            onOk={() => onSubmit()}
            confirmLoading={loading}
            forceRender={true}
            getContainer={false}
        >
            {visible && (
                <Form form={form} {...layout} >
                    {JSON.stringify(formObj) == '{}' ? <><Item
                        label="表名"
                        name="tableName"
                        rules={[{ required: true, message: '请选择表名' }]}
                    >
                        <Select onChange={handleChange}>
                            {tableList.length ? tableList.map((item, index) => { return <Select.Option key={index} value={item.text}>{item.text}</Select.Option>; }) : ''}
                        </Select>
                    </Item>
                        <Item
                            label="别名"
                            name="tableAlias"
                        >
                            <Input allowClear />
                        </Item></> : <div className={styles.paneTitle}>{formObj.tableName}</div>}
                    <div className={styles.field}>
                        <Card title="字段名" extra={<Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}> </Checkbox>} >
                            {
                                plainOptions.length ? <CheckboxGroup options={plainOptions} value={checkedList} onChange={onChange} /> : ''
                            }

                        </Card>
                    </div>

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