/** @format */

import React from 'react';
import {Popconfirm, Row, Form, Col, notification, message} from 'antd';
import {FormComponentProps} from 'antd/es/form';
import {ColumnProps} from 'antd/es/table';
import Table from '../../../components/table';
import Button from '../../../components/button';
import Input from '../../../components/input';
import CheckGroup from './components/checkGroup';
import {useGroupList, useNodeList, useGroupDelete, useGroupAdd, useGroupEdit} from '../../../service/accountList';
import styles from './styles/accountList.module.scss';
import AddGroup from './components/addGroup';
import pubPush from '../../../utils/eventProxy';

interface childrenProps {
    id: number;
    name: string;
    pid: number;
}
export interface eleProps {
    id: number;
    name: string;
    pid: number;
    children: childrenProps[];
}
interface groupTableProps {
    index: number;
    label: string;
}
const GroupEdit: React.FC<FormComponentProps> = props => {
    const {form} = props;
    const {getFieldDecorator, validateFieldsAndScroll, setFieldsValue} = form;
    const [state, setState] = React.useState({
        visible: false,
        loading: false,
        rowChecked: [],
        indexChecked: 0,
        idChecked: [],
        checkedName: '',
        powerName: '',
    });
    const [groupListState, requestGroupList] = useGroupList();
    // // 获取node列表 传值
    const [nodeListState] = useNodeList();
    const [deleteState, requestDelete] = useGroupDelete();
    const handleNameChange = (type: string, value: string) => {
        setState(prevState => ({
            ...prevState,
            checkedName: value,
        }));
    };
    const columns: ColumnProps<groupTableProps>[] = [
        {
            title: '序号',
            dataIndex: 'index',
            width: 70,
            key: 'index',
        },
        {
            title: '角色',
            dataIndex: 'label',
            width: '50%',
            key: 'label',
            render: (text, record, index) => {
                return (
                    <Input
                        allowClear={false}
                        required={true}
                        defaultValue={record.label}
                        disabled={state.indexChecked !== record.index - 1}
                        onChange={event => handleNameChange('label', event.target.value)}
                    />
                );
            },
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record) =>
                groupListState.dataSource.length >= 1 ? (
                    <Popconfirm
                        title={`确定删除${record.label}？`}
                        cancelText="取消"
                        okText="删除"
                        okType="danger"
                        onConfirm={() => handleDelete(record.key)}
                    >
                        <Button>删除</Button>
                    </Popconfirm>
                ) : null,
        },
    ];
    const handleDelete = (key: number) => {
        requestDelete(key).then(err => {
            if (err) {
                return notification.error({
                    message: '删除失败',
                    description: err,
                });
            }
            requestGroupList();
            pubPush.trigger('groupList');
        });
    };
    // 添加分组
    const [groupAddState, requestGroupAdd] = useGroupAdd();
    const handleAdd = () => {
        setState(prevState => ({
            ...prevState,
            visible: true,
        }));
    };
    const savingGroup = (val: {name: string}) => {
        const nodes = nodeListState.nodes.toString();
        requestGroupAdd({
            name: val.name,
            node_id: nodes,
        }).then(err => {
            if (err) {
                return message.error('添加失败，请重试');
            }
            setState(prevState => ({
                ...prevState,
                visible: false,
            }));
            requestGroupList();

            pubPush.trigger('groupList');
        });
    };
    const handleCancel = () => {
        setState(prevState => ({
            ...prevState,
            visible: false,
        }));
    };
    const [groupEditState, requestGroupEdit] = useGroupEdit();
    const handleSubmit = (event: React.MouseEvent<HTMLElement,MouseEvent>) => {
        // 提交-请求-成功后初始化
        event.preventDefault();
        validateFieldsAndScroll((errors, value) => {
            if (errors) return;
            const nodeIds = nodeListState.dataSource.map((ele: {id: number}) => {
                return ele.id;
            });
            let checkedList = [];
            for (let key in value) {
                if (nodeIds.includes(parseInt(key))) {
                    checkedList.push(value[key]);
                }
            }
            let nodeBox: number[] = [];
            checkedList.forEach(item => {
                item.forEach((ele: number) => {
                    nodeBox.push(ele);
                });
            });
            let node_id = Array.from(new Set(nodeBox)).toString();
            let newValue = {
                node_id: node_id,
                id: state.idChecked[0],
                name: state.checkedName,
            };
            requestGroupEdit(newValue).then(errors => {
                if (errors) return;
                requestGroupList();
                pubPush.trigger('groupList');
            });
        });
    };
    const handleCheckedChange = (id: number, row) => {
        setState(prevState => ({
            ...prevState,
            idChecked: id,
            rowChecked: row[0].node,
            indexChecked: row[0].index - 1,
            checkedName: row[0].label,
            powerName: row[0].label,
        }));

        nodeListState.dataSource.map((item: eleProps, index: number) => {
            const rowChecked = row[0].node.map((ele: string) => {
                return parseInt(ele);
            });
            let groupSelected = item.children.filter((ele :{id: number}) => rowChecked.includes(ele.id));
            let groupSelectedIds = groupSelected.map((ele: {id: number}) => {
                return ele.id;
            });
            setFieldsValue({
                [item.id.toString()]: groupSelectedIds,
            });
        });
    };
    React.useEffect(() => {
        if (groupListState.dataSource.length) {
            setState(prevState => ({
                ...prevState,
                rowChecked: groupListState.dataSource[state.indexChecked].node.map((ele: string) => {
                    return parseInt(ele);
                }),
                idChecked: [groupListState.dataSource[state.indexChecked]?.value],
                checkedName: groupListState.dataSource[state.indexChecked].label,
                powerName: groupListState.dataSource[state.indexChecked]?.label,
            }));
        }
    }, [groupListState.dataSource]);
    return (
        <Row>
            <AddGroup
                savingGroup={savingGroup}
                visible={state.visible}
                onCancel={handleCancel}
                loading={state.loading}
            />
            <Col span={8}>
                <Button onClick={handleAdd} type="primary" style={{marginBottom: 16}}>
                    添加分组
                </Button>
                <Table
                    rowKey="key"
                    dataSource={groupListState.dataSource}
                    columns={columns}
                    pagination={false}
                    loading={groupListState.loading}
                    rowSelection={{selectedRowKeys: state.idChecked, onChange: handleCheckedChange, type: 'radio'}}
                    bordered={false}
                    scroll={{x: false}}
                />
            </Col>
            <Col span={13} offset={3}>
                <h3 className={styles.groupEdit_PowerName}>{state.powerName}</h3>
                <Form style={{minHeight: 500}}>
                    {nodeListState.dataSource.map((item: eleProps, index: number) => {
                        let groupSelected = item.children.filter((ele: {id: number}) =>
                            state.rowChecked.includes(ele.id),
                        );
                        let groupSelectedId = groupSelected.map((ele: {id: number}) => {
                            return ele.id;
                        });
                        return (
                            <Col span={24} key={item.id}>
                                <Form.Item>
                                    {getFieldDecorator(item.id.toString(), {
                                        initialValue: groupSelectedId,
                                    })(<CheckGroup rowOptions={item} />)}
                                </Form.Item>
                            </Col>
                        );
                    })}
                </Form>
                <Button
                    type="primary"
                    size="large"
                    onClick={handleSubmit}
                    disabled={!state.checkedName}
                >
                    保存
                </Button>
            </Col>
        </Row>
    );
};

export default Form.create<FormComponentProps>({name: 'GroupEdit'})(GroupEdit);
