import React from 'react'
import {Button, Col, Form, Input, message, Modal, Row} from 'antd';
import Websocket from 'react-websocket';
/**
 * @ByYQL: TCPSocket调试框
 * Create 2024-4-11
 */
const TcpSocketModal = Form.create()(
class extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false, // 弹框显示状
            socketMessage:'消息面板：'
        }
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    componentWillUnmount() {
        // 组件卸载时关闭socket连接
        if (this.socket?.readyState === WebSocket.OPEN) {
            this.closeSocket();
        }
    }

    showModal = () => {
        this.setState({
            visible: true
        });
    };

    close = (e) => {
        // 组件卸载时关闭socket连接
        if (this.socket?.readyState === WebSocket.OPEN) {
            this.closeSocket();
        }
        this.setState({
            visible: false,
        });
    };

    handleSearch = (action) => {
        let that = this;
        this.props.form.validateFields((err, values) => {
            if(action === 'on'){
                // 初始化 WebSocket 连接
                that.socket = new WebSocket(values.IP + values.port);
                // 监听连接打开事件
                that.socket.onopen = () => {
                    that.setState({socketMessage:this.state.socketMessage + '\n' + '连接已打开'});
                };
                // 监听消息事件
                that.socket.onmessage = (message) => {
                    that.setState({socketMessage:this.state.socketMessage + '\n' + '收到服务器消息:'+ message.data});
                };
                // 监听连接关闭事件
                that.socket.onclose = () => {
                    that.setState({socketMessage:this.state.socketMessage + '\n' + '连接已关闭'});
                };
                // 监听错误事件
                that.socket.onerror = (error) => {
                    that.setState({socketMessage:this.state.socketMessage + '\n' + '连接发生错误:'+JSON.stringify(error)});
                };
            }else{
                if(!values.params){
                    message.warning('请输入发送入参');
                    return
                }
                if (this.socket?.readyState === WebSocket.OPEN) {
                    // 发送消息到服务器
                    that.socket.send(values.params);
                    that.setState({socketMessage:this.state.socketMessage + '\n' + '发送消息：'+values.params});
                } else {
                    that.setState({socketMessage:this.state.socketMessage + '\n' + '当前Socket为关闭状态'+this.socket.readyState});
                }
            }
        });
    };

    //关闭socket
    closeSocket = () => {
        this.socket.close();
        this.props.form.setFieldsValue({params: ''});
    };
    //清空消息面板
    cleanUpMessage = ()=>{
        this.setState({socketMessage:'消息面板：'});
    };

    onRef = (ref) => {
        this.child = ref;
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { TextArea } = Input;
        return (
            <Modal
                title="Socket调试"
                visible={this.state.visible}
                onCancel={this.close}
                width={'40%'}
                footer={null}>
                <Form>
                    <Row gutter={15}>
                        <Col span={12}>
                            <Form.Item label={'IP地址：'}>
                                {getFieldDecorator('IP', {
                                    rules: [{required: true,message: 'Input IP!'}],
                                })(<Input placeholder="Input IP!" />)}
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item label={'端口：'}>
                                {getFieldDecorator('port', {
                                    rules: [{required: true,message: 'Input port!'}],
                                })(<Input placeholder="Input port!" />)}
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <Button style={{width:'160px'}} type="primary" onClick={()=>this.handleSearch('on')}>连接 Socket</Button>
                        </Col>
                        <Col span={12}>
                            <Button style={{width:'160px'}} type="danger" onClick={()=> {this.closeSocket()}}>断开 Socket</Button>
                        </Col>
                    </Row>
                    <Row>
                        <Form.Item label={'发送内容：'}>
                            {getFieldDecorator('params', {
                            })(<TextArea rows={6} placeholder="Input string value!" />)}
                        </Form.Item>
                    </Row>
                    <Row>
                        <Col span={12}>
                            <Button style={{width:'160px'}} type="primary" onClick={()=>this.handleSearch('send')}>发送 Message</Button>
                        </Col>
                        <Col span={12}>
                            <Button style={{width:'160px'}} type="dashed" onClick={()=> {this.cleanUpMessage()}}>清空消息面板</Button>
                        </Col>
                    </Row>

                    <TextArea style={{marginTop:'15px'}} rows={12}  value={this.state.socketMessage}/>
                </Form>
            </Modal>
        )
    }
}
);
export default TcpSocketModal;
