/** @format */

import * as React from 'react';
import {Col, Form, Row, Icon, Typography, message} from 'antd';
import Input from '../../../../components/input';
import Select from '../../../../components/select/select';
import CheckGroup from './checkGroup';
import Button from '../../../../components/button';
import {useGroupList, useNodeList, AccountSaveProps} from '../../../../service/accountList';
import {FormComponentProps} from 'antd/es/form';
import {GetFieldDecoratorOptions} from 'antd/es/form/Form';
import styles from '../styles/accountList.module.scss';
import pubPush from '../../../../utils/eventProxy';
import {detectCapsLock} from "../../../../utils/utils"
import {adminUserNamePattern, adminPasswordPattern, phonePattern} from '../../../../const/regular'
const {Text} = Typography;

const formItemLayout = {
    labelCol: {
        xs: {span: 24},
        sm: {span: 8},
    },
    wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
    },
};
import {eleProps} from '../groupEdit';
import { passWordValidator } from '../../../../utils/passwordValidator';

export interface ValuesProps {
    admin_email: string;
    admin_name: string;
    admin_password: string;
    admin_phone: string;
    rbc_info: {
        group_id: number;
        name: string;
        node_id: string[];
    }
}
interface AdminSetProp {
    loading?: boolean;
    values?: {} | ValuesProps;
    onsubmit?: (value: AccountSaveProps) => void;
    history: any;
};
interface groupProps{
    onChange?: (val: number) => {};
    value: number;
};
interface NodeSelectedItemProps {
    index: number;
    key: number;
    label: string;
    node: string[];
    value:number;
}
interface stateProps {
    rowChecked: [],
    group_id: string | number,
    initialValue: [],
}
interface FormChildProps extends GetFieldDecoratorOptions{
    label: string;
    indexKey: string;
    Component: React.ReactNode;
}
interface FormItemProps {title: string; child: FormChildProps[]}

const AdminSet = (props: AdminSetProp & FormComponentProps) => {
    const {form, onsubmit, values, history} = props;
    const {getFieldDecorator, validateFieldsAndScroll, setFieldsValue} = form;

    // 所有组列表
    const [state, setState] = React.useState<stateProps>({
        rowChecked: [],
        group_id: '',
        initialValue: [],
    });
    //大小写state
    const [capsLockState,setCapsLockState]=React.useState({
        input_passWord_capsLock:false
    })
    const [groupListState, requestGroupList] = useGroupList();
    // 获取node列表 传值
    const [nodeListState] = useNodeList();
    const pIds = nodeListState.dataSource.map((ele:  {pid: number; id: number}) => {
        if(!ele.pid) {
            return ele.id
        }
    });
    const handleGroupSetting = () => {
        const path = '/home/users/groupEdit';
        history.push(path);
    };
    const GroupSelect = React.forwardRef((props: groupProps, ref) => {
        const {onChange, value} = props;
        const handleChangeGroup = (id: number) => {
            onChange(id);
            let dataSource = groupListState.dataSource;
            //加上自定义
            // let dataSource = state.groupDataSource.length ? state.groupDataSource:groupListState.dataSource;
            const nodeSelectedList = dataSource.filter(item => item.key === id);
            nodeListState.dataSource.map((item: eleProps) => {
                const rowChecked = nodeSelectedList[0].node.map((ele: string) => {
                    return parseInt(ele);
                });
                let groupSelected = item.children.filter(ele => rowChecked.includes(ele.id));
                groupSelected = groupSelected.map(ele => {
                    return ele.id;
                });
                setFieldsValue({
                    [item.id.toString()]: groupSelected,
                });

            });

            setState(prevState => ({
                ...prevState,
                group_id: id,
            }));
        };
        return (
            <div className={styles.setSelect}>
                <Select
                    placeholder="请选择"
                    options={groupListState.dataSource}
                    loading={groupListState.loading}
                    value={value}
                    onChange={handleChangeGroup}
                />
                <Icon className={styles.groupIcon} title="组设置" onClick={handleGroupSetting} type="setting" theme="filled" />
            </div>
        )
    });
    const formItems: FormItemProps = [
        {
            title: '账号信息',
            child: [
                {
                    label: '账户名',
                    indexKey: 'admin_name',
                    initialValue: values ? values.admin_name : '',
                    rules: [
                        {
                            required: true,
                            message: '请输入用户名',
                        },
                        {
                            pattern: adminUserNamePattern,
                            message: '用户名为2-12位的字母或数字'
                        }
                    ],
                    Component: <Input  autoComplete="off" placeholder="请输入账户名" disabled={values && JSON.stringify(values) !== "{}"} />,
                },
                {
                    label: '密码',
                    indexKey: 'admin_passwd',
                    initialValue: values ? values.admin_password : '',
                    Component: <Input.PassWord onKeyPress={(event:React.KeyboardEvent<HTMLInputElement>)=>{
                        setCapsLockState(prevState => ({...prevState, input_passWord_capsLock: detectCapsLock(event)}))
                    }} autoComplete="off" placeholder="请输入密码"/>
                    ,
                    rules: [
                        {
                            required: true,
                            message: '请输入密码',
                        },
                        {
                            pattern: adminPasswordPattern,
                            message: '密码为8-12位，必须包含字母与数字'
                        }
                    ],
                },
                {
                    label: '邮箱',
                    indexKey: 'admin_email',
                    initialValue: values ? values.admin_email : '',
                    Component: <Input  placeholder="请输入邮箱地址" />,
                    rules: [
                        {
                            required: true,
                            message: '请输入邮箱',
                        },
                        {
                            type: 'email',
                            message: '请输入正确的邮箱地址',
                        },
                    ],
                },
                {
                    label: '联系电话',
                    initialValue: values ? values.admin_phone : '',
                    indexKey: 'admin_phone',
                    Component: <Input autoComplete="off" placeholder="请输入手机号" />,
                    rules: [
                        {
                            pattern: phonePattern,
                            message: '请输入正确的电话号码'
                        }
                    ]
                },
            ],
        },
        {
            title: '权限信息',
            child: [
                {
                    label: '组',
                    indexKey: 'group_id',
                    initialValue: values?values?.rbc_info?.name: '',
                    rules: [
                        {
                            required: true,
                            message: '请选择组名',
                        },
                    ],
                    Component: (
                        <GroupSelect />
                    ),
                },
            ],
        },
    ];
    const handleBack = () => {
        const path = '/home/users/list';
        history.push(path);
    };
    const handleSubmit = () => {
        validateFieldsAndScroll((errors, value) => {
            if (errors) return;
            let newValue = JSON.parse(JSON.stringify(value));
            let checkedList = [],
                nodeIds: number[] = [];
            nodeListState.dataSource.forEach((ele: {id: number}) => {
                nodeIds.push(ele.id);
            });
            for (let key in value) {
                if (nodeIds.includes(parseInt(key))) {
                    checkedList.push(value[key]);
                    delete newValue[key];
                }
            }
            let checkIds: number[] = [];
            checkedList.forEach(item => {
                item.forEach((ele: number) => {
                    checkIds.push(ele)
                });
            });
            newValue.group_id = state.group_id;
            newValue.node_id =  Array.from(new Set(checkIds.concat(pIds))).toString();
            onsubmit(newValue);
        });
    };
    React.useEffect(() => {
        // 监听（添加订阅）
        pubPush.addEventListener('groupList', () => {
            requestGroupList();
        })
    }, []);
    React.useEffect(() => {
        let data = JSON.parse(JSON.stringify(groupListState.dataSource));
        // 添加
        if(data.length && JSON.stringify(values) !== "{}") {
            // 修改

            // 若有自定义--添加进data
            /*            let isExist = false;
                        data.forEach(ele => {
                            if(ele.key == values?.rbc_info?.group_id){
                                isExist = true ;
                                return;
                            }
                        });
                        if(!isExist){
                            data.push({
                                index: groupListState.dataSource.length,
                                key: values?.rbc_info?.group_id,
                                value: values?.rbc_info?.group_id,
                                label: values?.rbc_info?.name,
                                node: values?.rbc_info?.node_id,
                            });
                        }*/
            setState(prevState => ({
                ...prevState,
                group_id: values?.rbc_info?.group_id,
                rowChecked: groupListState.dataSource[0]?.node.map(ele => {
                    return parseInt(ele);
                }),
            }))
        }
    }, [values]);
    return (
        <Form {...formItemLayout} className={styles.setForm}>
            <div className={styles.capsTip}>
                {capsLockState.input_passWord_capsLock ? <Text type='warning'>大写键盘已开启</Text> : null}
            </div>
            {formItems?.map((element: FormItemProps, index: number) => {
                return (
                    <Row gutter={24} key={index}>
                        <h3>{element.title}</h3>
                        {
                            element.child?.map((item: FormChildProps) => {
                                const {label, indexKey, rules, Component, ...rest} = item;
                                return (
                                    <Col span={12} key={indexKey}>
                                        <Form.Item label={label}>
                                            {getFieldDecorator(indexKey as string, {
                                                rules,
                                                ...rest,
                                            })(Component)}
                                        </Form.Item>
                                    </Col>
                                );
                            })}
                    </Row>
                );
            })}
            {nodeListState.dataSource.map((item: eleProps, index: number) => {
                let groupSelected: number[] = [];
                if(values && JSON.stringify(values) !== "{}"){ // 编辑
                    let groupIds = item.children.filter((ele: {id: number}) => values?.rbc_info.node_id.includes(ele.id + ''));
                    groupSelected = groupIds.map((ele: {id: number}) => {
                        return ele.id;
                    });
                }
                return (
                    <Col span={24} offset={4} key={index}>
                        <Form.Item>
                            {getFieldDecorator(item.id.toString(), {
                                initialValue: groupSelected,
                            })(<CheckGroup rowOptions={item} isDisabled />)}
                        </Form.Item>
                    </Col>
                );
            })}
            <Col  offset={4}>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className={styles.saveBtn} onClick={handleSubmit}>
                        保存
                    </Button>
                    <Button onClick={handleBack}>返回</Button>
                </Form.Item>
            </Col>
        </Form>
    );
};
export default Form.create<AdminSetProp & FormComponentProps>({name: 'AdminSet'})(AdminSet);
