import React, {Component} from 'react';
import {Button, Col, Collapse, Form, Input, notification, Row} from 'antd';
import ReactJson  from 'react-json-view';
import {BUTTON} from '../../../../gui-common/components/AntdTypes';
import {ipcRenderer} from '../../polyfills';
import SessionStyles from '../Session/Session.css';

const ButtonGroup = Button.Group;
const { Panel } = Collapse;

export default class GetAppData extends Component {

  constructor (props) {
    super(props);
    this.state = {
      loading: false,
      apiPath: null,
      responseName: null,
    }

    const { saveAppdata } = this.props;

    ipcRenderer.on('receive-appdata', (evt, args) => {
      this.setState({loading: false})
      const {responseName, response, e} = JSON.parse(args);
      if (e != null || response.code !== 0) {
        notification.error({
          message: `请求发生错误`,
        });
      } else {
        saveAppdata(responseName, response);
      }
    });

  }

  render () {
    const { t, requestAppdata, appdata } = this.props;
    const keys = Object.keys(appdata);
    const pannels = []
    for (let i = 0; i < keys.length; i ++) {
      const key = keys[i];
      const value = appdata[key];
        pannels[i] = {title: key, content: value, key: i };
    }

    return <Row>
      <Col span={10}
           style={{ textAlign: 'right' }}>
        <Form
          name="basic"
          labelCol={{span: 5}}
          wrapperCol={{span: 19}}

        >
          <Form.Item
            label={t('api path')}
            name={t('api path')}
          >
            <Input className={SessionStyles.capsBoxFont} placeholder='Please enter the api path' style={{width: '80%'}} onChange={(value) => {
              this.setState({apiPath: value.target.value})
            }}/>
          </Form.Item>

          <Form.Item
            label={t('response name')}
            name={t('response name')}
          >
            <Input className={SessionStyles.capsBoxFont} placeholder='Please enter the response name' style={{width: '80%'}} onChange={(value) => {
              this.setState({responseName: value.target.value})
            }}/>
          </Form.Item>
        </Form>

        <Button key="confirm" type={BUTTON.PRIMARY} disabled={this.state.loading} onClick={ () => {
          this.setState({loading: true})
          const apiPath = this.state.apiPath;
          const responseName = this.state.responseName;
          requestAppdata(apiPath, responseName)
        } }>{t('confirm')} </Button>
      </Col>
      <Col span={2}>
        {/* 这里是空行，可以添加样式来设置高度或其他样式 */}
      </Col>
      <Col span={12}>
        <Collapse>
          {pannels.map((element)=> (
            <Panel header={element.title} key={element.key}>
              <div style={{ width: '100%', overflow: 'auto' }}>
                <ReactJson src={element.content} name={null} />
              </div>
            </Panel>
          ))}
        </Collapse>
      </Col>
    </Row>;
  };
}