import React, { useEffect, useState } from 'react';
import { Modal, Form, Input, notification, message, Row, Col, Select, Checkbox, Radio, Button } from 'antd';
import { GetCM_Event_LoadEventTypeTable, LoadEventFields, CM_Event_LoadDepartmentAndRoles, CM_Event_EditEventTable, GetCM_Event_QueryEventType, CM_Event_AddEventTable } from '@/services/standingBook/api'
import styles from './incident.less';
import ChangeAdd from './changeAdd'
import { PlusOutlined } from '@ant-design/icons'
import { set } from 'immutable';
import { getRoleGroup } from '@/services/userCenter/roleManage/api';

const { Option } = Select;
const AddModal = props => {
    const [inputValue, setInputValue] = useState({ SummaryFields: '', ReportFields: '', DisplayFields: '', EditableFields: '', TransitFields: '', Roles: '', RelatedEventFields: '', pictureFields: '' });
    const { callBackSubmit = () => { }, visible, type, formObj, treeData, maxLength } = props;

    const CheckboxGroup = Checkbox.Group;
    const defaultCheckedList = ['前端', '手持']
    // const plainOptions = ['前端', '手持']

    const [checkedList, setCheckedList] = useState(defaultCheckedList);
    const [checkedList1, setCheckedList1] = useState([])
    const [checkedList2, setCheckedList2] = useState([])
    const [checkedList3, setCheckedList3] = useState([])
    const [checkedList4, setCheckedList4] = useState([])

    const [editable, setEditable] = useState(false)
    const [ReportFromMobile, setReportFromMobile] = useState(false)
    const [ReportFromWeb, setReportFromWeb] = useState(false)

    const [indeterminate, setIndeterminate] = useState(true);
    const [checkAll, setCheckAll] = useState(true);
    const [pickItem, setPickItem] = useState('')
    const [prefixName, setPrefixName] = useState('')


    const [standingTable, setStandingTable] = useState([]);
    const [filed, setFiled] = useState({}); // 传给子组件列表数据
    const [filed1, setFiled1] = useState({}); // 传给子组件列表数据

    const [value, setValue] = useState(0);//单选
    const [types, setTypes] = useState(''); // 弹窗类型
    const [Order, setOrder] = useState(''); // 弹窗类型
    const [Type, setType] = useState('')

    const [isVisible, setIsVisible] = useState(false); // 弹窗
    const [characterValue, setCharacterValue] = useState('')
    const [form] = Form.useForm();
    const { Item } = Form;

    const onSubmit = () => {
        form.validateFields().then(validate => {
            if (validate) {
                // setLoading(true);
                let obj = form.getFieldsValue();
                // console.log(obj.Reportable)
                console.log(obj)
                console.log(obj.Editable)
                console.log(obj.CreateMode)
                console.log(obj.ReportFromWeb)
                console.log(inputValue)
                if (obj.CreateMode === 0 || 1) {
                    obj.CreateMode = obj.CreateMode.toString()
                }

                if (checkedList2 != true) {
                    obj.Editable = false
                } else {
                    obj.Editable = checkedList2
                }
                if (checkedList3 === true && checkedList4 === true) {
                    obj.Reportable = '均可'
                    obj.ReportFromMobile = '手持'
                    obj.ReportFromWeb = '前端'
                    // inputValue.Reportable = '均可'
                    // inputValue.ReportFromMobile = '手持'
                    // inputValue.ReportFromWeb = '前端'
                } else if (checkedList3 === true) {
                    obj.Reportable = '前端'
                    obj.ReportFromMobile = ''
                    obj.ReportFromWeb = '前端'
                    // inputValue.Reportable = '前端'
                    // inputValue.ReportFromMobile = ''
                    // inputValue.ReportFromWeb = '前端'
                } else if (checkedList4 === true) {
                    obj.Reportable = '手持'
                    obj.ReportFromMobile = '手持'
                    obj.ReportFromWeb = ''
                    // inputValue.Reportable = '手持'
                    // inputValue.ReportFromMobile = '手持'
                    // inputValue.ReportFromWeb = ''
                } else {
                    obj.Reportable = '否'
                    obj.ReportFromMobile = ''
                    obj.ReportFromWeb = ''
                    // inputValue.Reportable = ''
                    // inputValue.ReportFromMobile = ''
                    // inputValue.ReportFromWeb = ''
                }
                console.log(type)
                console.log(obj)
                console.log(inputValue)
                console.log({ ...inputValue })
                console.log({ ...obj })
                console.log(inputValue)
                if((obj.Reportable !== '否')&&(inputValue.Roles === '')){
                    notification.warning({
                        message: '提示',
                        description: '当允许客户端上报时需选择事件权限',
                    })
                }else{
                let data = type == 'add' ? { ...obj, ...inputValue, Order: maxLength } : { ...obj, Order, ID: formObj.ID }
                if (type == 'edit') {
                    CM_Event_EditEventTable(data)
                        .then(res => {
                            // setLoading(false);
                            if (res.msg === 'Ok') {
                                form.resetFields();
                                callBackSubmit();
                                notification.success({
                                    message: '提示',
                                    duration: 3,
                                    description: '编辑成功',
                                });
                            } else {
                                notification.error({
                                    message: '提示',
                                    duration: 3,
                                    description: res.msg,
                                });
                            }
                        })
                        .catch(error => {
                            notification.error({
                                message: '提示',
                                duration: 3,
                                description: '编辑失败',
                            });
                            setLoading(false);
                        });
                }
                if (type == 'add') {
                    CM_Event_AddEventTable(data)
                        .then(res => {
                            // setLoading(false);
                            if (res.msg === 'Ok') {
                                form.resetFields();
                                callBackSubmit();
                                notification.success({
                                    message: '提示',
                                    duration: 3,
                                    description: '新增成功',
                                });
                            } else {
                                notification.error({
                                    message: '提示',
                                    duration: 3,
                                    description: res.msg,
                                });
                            }
                        })
                        .catch(error => {
                            notification.error({
                                message: '提示',
                                duration: 3,
                                description: '新增失败',
                            });
                            setLoading(false);
                        });
                }

            }
            }
        });
    };

    useEffect(() => {
        getEventData()
        getRole()
        if (type === 'add') {
            setInputValue({ SummaryFields: '', ReportFields: '', DisplayFields: '', EditableFields: '', TransitFields: '', Roles: '', RelatedEventFields: '', pictureFields: '' })
            setFiled({})
            setFiled1({})
            form.resetFields();
            setEditable(false)
            setReportFromMobile(false)
            setReportFromWeb(false)
        } else if (type === 'edit') {
            GetCM_Event_QueryEventType({ eventTypeId: formObj.ID }).then(res => {
                res.data.root && form.setFieldsValue({ ...res.data.root });
                console.log(res.data.root)
                setEditable(res.data.root.Editable)
                setReportFromMobile(res.data.root.ReportFromMobile)
                setReportFromWeb(res.data.root.ReportFromWeb)
                setInputValue({ ...res.data.root })
                setOrder(res.data.root.Order)
                setType(res.data.root.BusinessType)
                changTable(res.data.root.TableName)
            })
        }
    }, [visible])

    const getRole = () => {
        CM_Event_LoadDepartmentAndRoles().then(res => {
            if (res.msg === 'Ok') {
                setFiled1(formateArrDataA1(res.data, 'groupType'))
                console.log(res.data)

            }
        })
    }

    const getEventData = () => {
        setType('')
        GetCM_Event_LoadEventTypeTable().then(res => {
            if (res.msg === 'Ok') {
                console.log(res.data)
                setStandingTable(res.data)
            }
        })
    }

    const changTable = (value) => {
        LoadEventFields({ eventTableName: value, distinctFields: '' }).then(res => {
            if (res.data.root && res.data.root.length) {
                setFiled(formateArrDataA(res.data.root, 'group'))
                console.log(res.data.root)
            }

        })

    }

    const formateArrDataA = (initialArr, name) => {
        // 判定传参是否符合规则
        if (!(initialArr instanceof Array)) {
            return '请传入正确格式的数组'
        }
        if (!name) {
            return '请传入对象属性'
        }
        //先获取一下这个数组中有多少个"name"
        let nameArr = []
        for (let i in initialArr) {
            if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
                nameArr.push(initialArr[i][`${name}`])
            }
        }
        console.log(nameArr)
        //新建一个包含多个list的结果对象
        let tempObj = {}
        // 根据不同的"name"生成多个数组
        for (let k in nameArr) {
            for (let j in initialArr) {
                if (initialArr[j][`${name}`] == nameArr[k]) {
                    // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
                    tempObj[nameArr[k]] = tempObj[nameArr[k]] || []
                    tempObj[nameArr[k]].push(initialArr[j])
                }
            }
        }
        console.log(tempObj)
        for (let key in tempObj) {
            let arr = []
            tempObj[key].map(item => {
                tempObj[key] = arr;
                arr.push(item.fieldName)
            })
        }
        return tempObj
    }
    const formateArrDataA1 = (initialArr, name) => {

        let aa = []
        let a1 = []
        let a2
        let a3 = []
        initialArr.map(i => {
            // console.log(i.groupType)
            a2 = i.groupType
            // console.log(a2)
            // console.log(i.root)
            a1 = i.root
            a1.map(j => {
                j.group = a2
                // console.log(j)

            })
            aa.push(i.root)
        })
        // console.log(aa)
        aa.map(p => {
            // console.log(p)
            p.map(o => {
                // console.log(o)
                a3.push(o)

            })
        })
        console.log(a3)

        // 判定传参是否符合规则
        if (!(a3 instanceof Array)) {
            return '请传入正确格式的数组'
        }
        if (!name) {
            return '请传入对象属性'
        }
        //先获取一下这个数组中有多少个"name"
        let nameArr = []
        a3.map(i => {
            if (nameArr.indexOf(i.group) === -1) {
                nameArr.push(i.group)
            }
        })
        console.log(nameArr)
        //新建一个包含多个list的结果对象
        let tempObj = {}
        // 根据不同的"name"生成多个数组
        for (let k in nameArr) {
            for (let j in a3) {
                if (a3[j].group == nameArr[k]) {
                    // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
                    tempObj[nameArr[k]] = tempObj[nameArr[k]] || []
                    tempObj[nameArr[k]].push(a3[j])
                }
            }
        }
        console.log(tempObj);
        for (let key in tempObj) {
            let arr = []
            tempObj[key].map(item => {
                tempObj[key] = arr;
                arr.push(item.Name)
            })
        }
        return tempObj
    }
    const onChange = list => {
        console.log(list)
        setCheckedList(list);
        setIndeterminate(!!list.length && list.length < ['前端', '手持'].length);
        setCheckAll(list.length === ['前端', '手持'].length);
    };

    const onCheckAllChange = e => {
        setCheckedList(e.target.checked ? ['前端', '手持'] : []);
        setIndeterminate(false);
        setCheckAll(e.target.checked);
    };

    const onChange1 = e => {
        console.log(e.target.checked)
        setEditable(e.target.checked)
        setCheckedList2(e.target.checked);//true
    }
    const onChange2 = e => {
        console.log(e.target.value)
        setValue(e.target.value);
    }
    const onChange3 = e => {
        console.log(e.target.checked)
        setReportFromWeb(e.target.checked)
        setCheckedList3(e.target.checked);//true
    }
    const onChange4 = e => {
        console.log(e.target.checked)
        setReportFromMobile(e.target.checked)
        setCheckedList4(e.target.checked);//true
    }
    const changeData = () => {

    }
    const onOK = prop => {
        setIsVisible(false)
        let inputText = { ...inputValue }
        inputText[prop.pickItem] = prop.str
        setCheckedList1(prop.checkedList)
        setInputValue(inputText)

    }
    const pickFiled = (fileds) => {
        setTypes('add')
        setCharacterValue(inputValue[fileds])
        setCheckedList1(inputValue[fileds].split(','))
        setPickItem(fileds)
        setIsVisible(true)
    }
    const pickFiled1 = (fileds) => {
        setTypes('app')
        setCharacterValue(inputValue[fileds])
        setCheckedList1(inputValue[fileds].split(','))
        setPickItem(fileds)
        setIsVisible(true)
    }
    const changeText = (e, type) => {
        let inputText = { ...inputValue }
        inputText[type] = e.target.value
        setInputValue(inputText)
    }
    const prefix = (e) => {
        setPrefixName(changPrefix(e.target.value))
        console.log(prefixName)
        form.setFieldsValue({ Code: prefixName })
    }
    const changPrefix = (item) => {
        let aa = item.slice(0, 2)
        return (aa)
    }
    return (
        <Modal
            title={type === 'add' ? '添加事件类型' : '编辑事件类型'}
            maskClosable={false}
            width="800px"
            destroyOnClose
            okText="确认"
            cancelText="取消"
            {...props}
            onOk={() => onSubmit()}
            // confirmLoading={loading}
            forceRender={true}
            getContainer={false}
        >
            <Form form={form} labelCol={{ span: 7 }} style={{ height: '38rem', overflowY: 'scroll' }}>
                <Row>
                    <Col span={13}>
                        <Item
                            label="事件名称"
                            name="Name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入事件名称',
                                },
                            ]}
                        >
                            <Input style={{ width: '17rem' }} onChange={prefix} placeholder="请输入事件名称" />
                        </Item>
                    </Col>
                    <Col span={11}>
                        <Item
                            label="编码前缀"
                            name="Code"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入编码前缀',
                                },
                            ]}
                        >
                            <Input style={{ width: '12rem' }} value={prefixName} placeholder="请输入编码前缀" />
                        </Item>
                    </Col>
                    <Col span={23}>
                        <Item
                            label="业务类型"
                            name="BusinessType"
                            labelCol={{ span: 4 }}
                            rules={[
                                {
                                    required: true,
                                    message: '请选择业务类型',
                                },
                            ]}
                        >
                            <Select
                                style={{ width: '580px' }}
                                placeholder="选择业务类型"

                            >
                                {treeData ? treeData.map((item, index) => { return <Option key={index} value={item}>{item}</Option> }) : ''}
                            </Select>
                        </Item>
                    </Col>
                    <Col span={23}>
                        <Item
                            label="事件主表"
                            name="TableName"
                            labelCol={{ span: 4 }}
                            rules={[
                                {
                                    required: true,
                                    message: '请选择事件主表',
                                },
                            ]}
                        >
                            <Select
                                style={{ width: '580px' }}
                                placeholder="选择事件主表"
                                onChange={changTable}
                            >
                                {standingTable ? standingTable.map((item, index) => { return <Option key={index} value={item.text}>{item.text}</Option> }) : ''}
                            </Select>
                        </Item>
                    </Col>
                    <Col span={4}>
                       <Item></Item>
                    </Col>
                    <Col span={20}>
                        <Item><span>客户端上报和配单(需配置事件权限、受理流程)</span></Item>
                    </Col>
                    <Col span={4}>
                        <Item>
                        </Item>
                    </Col>
                    <Col span={4}>
                        {/* <Item
                            name="Reportable"
                        >
                            <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
                                客户端上报和配单(需配置事件权限、受理流程)
                            </Checkbox>
                             <CheckboxGroup value={checkedList} onChange={onChange}/> 
                            <CheckboxGroup value={checkedList} onChange={onChange}>
                                <Checkbox value={'前端'}>前端</Checkbox>
                                <Checkbox value={'手持'}>手持</Checkbox>
                            </CheckboxGroup>
                        </Item> 
                        */}
                        {/* <Item
                            name="Reportable"
                        > */}
                        {/* <Checkbox indeterminate={indeterminate} onChange={onCheckAllChange} checked={checkAll}>
                                客户端上报和配单(需配置事件权限、受理流程)
                            </Checkbox> */}
                        <Item
                            name="ReportFromWeb"
                        >
                            <Checkbox onChange={onChange3} checked={ReportFromWeb} >前端</Checkbox>
                        </Item>
                        </Col>
                        <Col span={16}>
                        <Item
                            name="ReportFromMobile"
                        >
                            <Checkbox onChange={onChange4} checked={ReportFromMobile}>手持</Checkbox>
                        </Item>

                        {/* </Item> */}
                    </Col>
                    <Col span={4}>
                        <Item>
                        </Item>
                    </Col>
                    <Col span={20}>
                        <Item
                            name="Editable"
                        >
                            <Checkbox onChange={onChange1} checked={editable} >上报后可以编辑(需配置编辑字段)</Checkbox>
                        </Item>
                    </Col>
                    <Col span={23}>
                        <Item
                            label="上报方式"
                            name="CreateMode"
                            labelCol={{ span: 4 }}
                            rules={[
                                {
                                    required: true,
                                    message: '请选择上报方式',
                                },
                            ]}
                        >

                            <Radio.Group onChange={onChange2} value={value}>
                                <Radio value={0} style={{ marginLeft: '5px' }}>仅上报</Radio>
                                <Radio value={1} style={{ marginLeft: '185px' }}>工单分派</Radio>
                            </Radio.Group>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="摘要字段"
                            name="SummaryFields"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择摘要字段" onChange={(e) => changeText(e, 'SummaryFields')} value={inputValue.SummaryFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('SummaryFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>

                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="上报字段"
                            name="ReportFields"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择上报字段" onChange={(e) => changeText(e, 'ReportFields')} value={inputValue.ReportFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('ReportFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="显示字段"
                            name="DisplayFields"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择显示字段" onChange={(e) => changeText(e, 'DisplayFields')} value={inputValue.DisplayFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('DisplayFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="编辑字段"
                            name="EditableFields"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择编辑字段" onChange={(e) => changeText(e, 'EditableFields')} value={inputValue.EditableFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('EditableFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="转单字段"
                            name="TransitFields"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择转单字段" onChange={(e) => changeText(e, 'TransitFields')} value={inputValue.TransitFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('TransitFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="事件权限"
                            name="Roles"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择事件权限" onChange={(e) => changeText(e, 'Roles')} value={inputValue.Roles} allowClear />
                                <Button type="dashed" onClick={() => pickFiled1('Roles')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="置顶条件"
                            name="TopWhere"
                            labelCol={{ span: 4 }}
                        >
                            <Input style={{ width: '500px' }} placeholder="请输入置顶条件" allowClear />
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="上报视图"
                            name="ReportPage"
                            labelCol={{ span: 4 }}
                        >
                            <Input style={{ width: '500px' }} placeholder="请输入上报视图" allowClear />
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="处理视图"
                            name="DealPage"
                            labelCol={{ span: 4 }}
                        >
                            <Input style={{ width: '500px' }} placeholder="请输入处理视图" allowClear />
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="关联事件"
                            name="RelatedEvents"
                            labelCol={{ span: 4 }}
                        >
                            <Input style={{ width: '500px' }} placeholder="请输入关联事件" allowClear />
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="关联字段"
                            name="RelatedEventFields"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择关联字段" onChange={(e) => changeText(e, 'RelatedEventFields')} value={inputValue.RelatedEventFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('RelatedEventFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="接口配置"
                            name="InterfaceConfig"
                            labelCol={{ span: 4 }}
                        >
                            <Input style={{ width: '500px' }} placeholder="请输入接口配置" />
                        </Item>
                    </Col>
                    <Col span={24}>
                        <Item
                            label="图片表达"
                            name="ImageExpression"
                            labelCol={{ span: 4 }}
                        >
                            <div className={styles.filed_listItem} >
                                <Input style={{ width: '500px' }} placeholder="请选择图片表达" onChange={(e) => changeText(e, 'pictureFields')} value={inputValue.pictureFields} allowClear />
                                <Button type="dashed" onClick={() => pickFiled('pictureFields')} icon={<PlusOutlined />} style={{ marginLeft: '0.5rem', height: '100%', width: '3.5rem' }} />
                            </div>
                        </Item>
                    </Col>
                </Row>
            </Form>
            <ChangeAdd
                visible={isVisible}
                onCancel={() => setIsVisible(false)}
                callBackSubmit={onOK}
                newCheckedList={checkedList1}
                isType={types}
                filed={filed}
                filed1={filed1}
                pickItem={pickItem}
                characterValue={characterValue}
                formObj={formObj}
            />

        </Modal>
    );
};

export default AddModal;