import React, { useEffect, useState } from 'react';
import { Layout, Row, Col, message, Button, Modal, Result } from 'antd';
import PageDesignDescForm from './components/PageDesignDescForm';
import BugList from './components/BugList';
import OperatorLog from './components/OperatorLog';
import { parseMessageData, PageWidgetData, UserActionData,siderStyle, contentStyle, PageIssueData} from './index.d';

import ReconnectingWebSocket from 'reconnecting-websocket';
import { PlusOutlined } from '@ant-design/icons';

const { Sider, Content } = Layout;

const TestingPage = () => {
    const [messageApi, contextHolder] = message.useMessage();
    const [ userActionLogState, setUserActionLogState] = useState<UserActionData[]>([]);
    const [ currentWidget, setCurrentWidget] = useState<PageWidgetData>();
    const [ connection, setConnection] = useState<'ready'|'open'| 'error' | 'close'>('ready');
    const [ showModal, setShowModal] = useState<boolean>(false);

    const [ bugList, setBugList] = useState<PageIssueData[]>([]);

    // 接收HMI用户操作数据
    const onMessage = (event: MessageEvent) => {
        parseMessageData(event, (data) => {
          new Promise((resolve) => {
            setUserActionLogState((prev) => {
                resolve([...prev, { ...data, serial: prev.length + 1}]);
                return [...prev, { ...data, serial: prev.length + 1}];
            });
          }).then(newValue => {
              console.log(newValue);
              // @ts-ignore
              setCurrentWidget(newValue);
          });
        });
      };
    
    useEffect(()=>{
    const rws = new ReconnectingWebSocket('ws://192.168.0.24:10000');
    rws.addEventListener('message', onMessage);
    rws.reconnect(5);

    // 连接成功
    rws.addEventListener('open', () =>{ 
        setConnection('open');
        messageApi.open({
            type: 'success',
            content: 'HMI客户端连接成功!',
        });
    });

    rws.addEventListener('error', () =>{ 
        setConnection('error');
        messageApi.open({
            type: 'error',
            content: 'HMI客户端连接发生错误!',
        });
    });

    rws.addEventListener('close', () =>{ 
        setConnection('close');
        messageApi.open({
            type: 'warning',
            content: 'HMI客户端连接已关闭!',
        });
    });

    }, []);

    const OnLogSelected = (action: UserActionData) => {
        setCurrentWidget(
            {
                page: action.page,
                widget: action.widget,
                action: action.action
            }
        );
    }

    const addBug = (data: PageIssueData) => {
        new Promise((resolve) => {
            setBugList((prev) => {
                resolve([...prev, { ...data, serial: prev.length + 1}]);
                return [...prev, { ...data, serial: prev.length + 1}];
            });
          }).then(newValue => {
              console.log(newValue);
              // @ts-ignore
              setBugList(newValue);
          });
    }

    const onRemoveBug = (data: PageIssueData) => {
        new Promise((resolve) => {
            setBugList((prev) => {
                resolve([...prev, { ...data, serial: prev.length + 1}]);
                return [...prev, { ...data, serial: prev.length + 1}];
            });
          }).then(newValue => {
              console.log(newValue);
              // @ts-ignore
              setBugList(newValue);
          });
    }

    const onSubmit = () => {
        setShowModal(true);
    }

    const onModalOk = () =>{
        setShowModal(false);
        window.location.reload();
    }

    const onModalCancel = () =>{
        setShowModal(false);
        window.location.reload();
    }


    return (
        <Layout style={{height: '100vh'}}>
             {contextHolder}
            <Content style={contentStyle}>
                <Row>
                    <Col span={24}>
                        <OperatorLog onLogSelected={OnLogSelected} dataSource={userActionLogState} onSubmitBug={addBug} />
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <BugList dataSource={bugList} onRemove={onRemoveBug}/>
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <Button type="primary" onClick={onSubmit} block>
                            <PlusOutlined />
                            提交
                        </Button>
                    </Col>
                </Row>
                <Modal
                    title="页面问题提交"
                    open={showModal}
                    onOk={onModalOk}
                    onCancel={onModalCancel}
                >
                    <Result
                        status="success"
                        title="页面测试已提交成功!"
                        subTitle="总计10个错误，已找到{bugList.lengt}个错误"
                        extra={[
                        <Button type="primary" key="console">
                            OK
                        </Button>,
                        <Button key="buy">Buy Again</Button>,
                        ]}
                    />
                </Modal>
            </Content>
      </Layout>
    )
}
export default TestingPage;