<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import superagent from 'superagent';

import { Table, Card, Modal, Button, Input } from 'antd';

import { loadMocker, setMockerActiveModule } from '../../business/mocker/action';

class Mocker extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      showModal: false,
      modalShowData: {},
      cgiParams: {}
    };

    this.handleActive = this.handleActive.bind(this);
    this.handleModalOk = this.handleModalOk.bind(this);
    this.handleShowResult = this.handleShowResult.bind(this);
    this.handleParamsChange = this.handleParamsChange.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.isLoaded && (this.props.isLoaded !== nextProps.isLoaded)) {
      const { mockerData } = nextProps;
      let curRoute = mockerData.route;
      let mockerParams = mockerData.params || [];
      let { cgiParams } = this.state;

      let url = curRoute;

      if (mockerParams.length) {
        mockerParams.forEach((item) => {
          if (item.defaultValue) {
            cgiParams[item.name] = item.defaultValue;
          }
        });

        this.setState({
          cgiParams: cgiParams
        });
      }
    }
  }

  componentDidMount() {
    console.log('Mocker componentDidMount', this.props);

    this.fetch();
  }

  fetch() {
    this.props.loadMocker(this.props.routeParams.mockerName);
  }

  getMockModuleByPost(url, data) {
    return new Promise((resolve, reject) => {
      superagent.post(url)
        .set('Content-Type', 'application/json')
        .send(data)
        .withCredentials()
        .end((err, res) => {
          if (err) {
            return reject(err);
          }

          resolve(res.body);
        });
    });
  }

  getMockModuleByGet(url, data) {
    return new Promise((resolve, reject) => {
      superagent.get(url)
        .query(data)
        .withCredentials()
        .end((err, res) => {
          if (err) {
            return reject(err);
          }

          resolve(res.body);
        });
    });
  }

  handleActive(name) {
    this.props.setMockerActiveModule(this.props.routeParams.mockerName, name);
  }

  handleModalOk() {
    this.setState({
      showModal: false,
      modalShowData: {},
    });
  }

  handleShowResult(query = {}) {
    const { mockerData } = this.props;
    const actualURL = this.getActurlURL();
    console.log('mockerData', mockerData, actualURL);

    if (mockerData.method === 'post') {
      this.getMockModuleByPost(actualURL, query)
        .then((data) => {
          console.log(data);
          this.setState({
            showModal: true,
            modalShowData: data,
          })
        })
        .catch((err) => {
          console.error(err)
        });
    } else {
      this.getMockModuleByGet(actualURL, query)
        .then((data) => {
          console.log(data);
          this.setState({
            showModal: true,
            modalShowData: data,
          })
        })
        .catch((err) => {
          console.error(err)
        });
    }
  }

  handleParamsChange(fieldName, event) {
    let { cgiParams } = this.state;

    cgiParams[fieldName] = event.target.value;

    this.setState({
      cgiParams: cgiParams
    });
  }

  getColumns() {
    const { mockerData } = this.props;
    const activeModule = mockerData.activeModule || '';

    return [{
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Button type="primary" size="large" onClick={this.handleShowResult.bind(this, record.query)}>
          {text}
        </Button>
      ),
    }, {
      title: 'Version',
      dataIndex: 'version',
      key: 'version',
    }, {
      title: 'Author',
      dataIndex: 'author',
      key: 'author',
    }, {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
    }, {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <span>
          {
            (record.name !== activeModule) ?
              <a href="javascript:;" onClick={this.handleActive.bind(this, record.name)}>Active It</a>
              : <span>Aready active</span>
          }

          <span className="ant-divider" />
          <a href="#">Edit</a>

          <span className="ant-divider" />
          <a href="#">Delete</a>
        </span>
      ),
    }];
  }

  getActurlURL() {
    const { mockerData } = this.props;
    const { cgiParams } = this.state;

    let curUrl = mockerData.route;

    if (Object.keys(cgiParams).length) {
      Object.keys(cgiParams).forEach((key) => {
        curUrl = curUrl.replace(':' + key, cgiParams[key]);
      })
    }

    console.log('curUrl', curUrl);
    return curUrl;
  }

  render() {
    const { isLoaded, mockerData, route } = this.props;
    const { showModal, modalShowData } = this.state;

    const data = mockerData.modules;
    const columns = this.getColumns();

    let curUrl = this.getActurlURL();

    return (
      <div>
        <h3>location</h3>
        <p>{JSON.stringify(location)}</p>
        <h3>route</h3>
        <p>{JSON.stringify(route)}</p>

        {
          isLoaded ? (
            <div>
              <Card>
                <h2>{mockerData.name} - {mockerData.version} - {mockerData.author} - {mockerData.description}</h2>
                <p>route: {mockerData.route}</p>
                <div>
                  {
                    mockerData.params && mockerData.params.length ? (
                      mockerData.params.map((item, index) => {
                        return <div key={index}>
                          {item.name}:
                          <Input placeholder={item.name}
                                 defaultValue={item.defaultValue}
                                 onChange={this.handleParamsChange.bind(this, item.name)}
                          />
                        </div>
                      })
                    ) : null
                  }

                  <Button type="primary" size="large" onClick={this.handleShowResult.bind(this, {})}>
                    {mockerData.method} : {curUrl}
                  </Button>
                </div>
                <p>本地路径：{mockerData._fullPath}</p>
              </Card>

              < Table loading={!isLoaded} rowKey="name" columns={columns} dataSource={data} />

              <Modal
                title="结果"
                visible={showModal}
                footer={[
                  <Button key="submit" type="primary" size="large" onClick={this.handleModalOk}>
                    知道了
                  </Button>,
                ]}
              >
                  <textarea name="cgidata" id="cgidata" style={{ width: '100%', minHeight: '600px' }}
                            value={JSON.stringify(modalShowData, null, 2)} readOnly></textarea>
              </Modal>
            </div>
          ) : null
        }
      </div>
    )
  }
}

function mapStateToProps(state) {<commit_msg>feat: modal 框增加 onOk 和 onCancel 处理，以便关闭modal<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import superagent from 'superagent';

import { Table, Card, Modal, Button, Input } from 'antd';

import { loadMocker, setMockerActiveModule } from '../../business/mocker/action';

class Mocker extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      showModal: false,
      modalShowData: {},
      cgiParams: {}
    };

    this.handleActive = this.handleActive.bind(this);
    this.handleModalHide = this.handleModalHide.bind(this);
    this.handleShowResult = this.handleShowResult.bind(this);
    this.handleParamsChange = this.handleParamsChange.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.isLoaded && (this.props.isLoaded !== nextProps.isLoaded)) {
      const { mockerData } = nextProps;
      let curRoute = mockerData.route;
      let mockerParams = mockerData.params || [];
      let { cgiParams } = this.state;

      let url = curRoute;

      if (mockerParams.length) {
        mockerParams.forEach((item) => {
          if (item.defaultValue) {
            cgiParams[item.name] = item.defaultValue;
          }
        });

        this.setState({
          cgiParams: cgiParams
        });
      }
    }
  }

  componentDidMount() {
    console.log('Mocker componentDidMount', this.props);

    this.fetch();
  }

  fetch() {
    this.props.loadMocker(this.props.routeParams.mockerName);
  }

  getMockModuleByPost(url, data) {
    return new Promise((resolve, reject) => {
      superagent.post(url)
        .set('Content-Type', 'application/json')
        .send(data)
        .withCredentials()
        .end((err, res) => {
          if (err) {
            return reject(err);
          }

          resolve(res.body);
        });
    });
  }

  getMockModuleByGet(url, data) {
    return new Promise((resolve, reject) => {
      superagent.get(url)
        .query(data)
        .withCredentials()
        .end((err, res) => {
          if (err) {
            return reject(err);
          }

          resolve(res.body);
        });
    });
  }

  handleActive(name) {
    this.props.setMockerActiveModule(this.props.routeParams.mockerName, name);
  }

  handleModalHide() {
    this.setState({
      showModal: false,
      modalShowData: {},
    });
  }

  handleShowResult(query = {}) {
    const { mockerData } = this.props;
    const actualURL = this.getActurlURL();
    console.log('mockerData', mockerData, actualURL);

    if (mockerData.method === 'post') {
      this.getMockModuleByPost(actualURL, query)
        .then((data) => {
          console.log(data);
          this.setState({
            showModal: true,
            modalShowData: data,
          })
        })
        .catch((err) => {
          console.error(err)
        });
    } else {
      this.getMockModuleByGet(actualURL, query)
        .then((data) => {
          console.log(data);
          this.setState({
            showModal: true,
            modalShowData: data,
          })
        })
        .catch((err) => {
          console.error(err)
        });
    }
  }

  handleParamsChange(fieldName, event) {
    let { cgiParams } = this.state;

    cgiParams[fieldName] = event.target.value;

    this.setState({
      cgiParams: cgiParams
    });
  }

  getColumns() {
    const { mockerData } = this.props;
    const activeModule = mockerData.activeModule || '';

    return [{
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Button type="primary" size="large" onClick={this.handleShowResult.bind(this, record.query)}>
          {text}
        </Button>
      ),
    }, {
      title: 'Version',
      dataIndex: 'version',
      key: 'version',
    }, {
      title: 'Author',
      dataIndex: 'author',
      key: 'author',
    }, {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
    }, {
      title: 'Action',
      key: 'action',
      render: (text, record) => (
        <span>
          {
            (record.name !== activeModule) ?
              <a href="javascript:;" onClick={this.handleActive.bind(this, record.name)}>Active It</a>
              : <span>Aready active</span>
          }

          <span className="ant-divider" />
          <a href="#">Edit</a>

          <span className="ant-divider" />
          <a href="#">Delete</a>
        </span>
      ),
    }];
  }

  getActurlURL() {
    const { mockerData } = this.props;
    const { cgiParams } = this.state;

    let curUrl = mockerData.route;

    if (Object.keys(cgiParams).length) {
      Object.keys(cgiParams).forEach((key) => {
        curUrl = curUrl.replace(':' + key, cgiParams[key]);
      })
    }

    console.log('curUrl', curUrl);
    return curUrl;
  }

  render() {
    const { isLoaded, mockerData, route } = this.props;
    const { showModal, modalShowData } = this.state;

    const data = mockerData.modules;
    const columns = this.getColumns();

    let curUrl = this.getActurlURL();

    return (
      <div>
        <h3>location</h3>
        <p>{JSON.stringify(location)}</p>
        <h3>route</h3>
        <p>{JSON.stringify(route)}</p>

        {
          isLoaded ? (
            <div>
              <Card>
                <h2>{mockerData.name} - {mockerData.version} - {mockerData.author} - {mockerData.description}</h2>
                <p>route: {mockerData.route}</p>
                <div>
                  {
                    mockerData.params && mockerData.params.length ? (
                      mockerData.params.map((item, index) => {
                        return <div key={index}>
                          {item.name}:
                          <Input placeholder={item.name}
                                 defaultValue={item.defaultValue}
                                 onChange={this.handleParamsChange.bind(this, item.name)}
                          />
                        </div>
                      })
                    ) : null
                  }

                  <Button type="primary" size="large" onClick={this.handleShowResult.bind(this, {})}>
                    {mockerData.method} : {curUrl}
                  </Button>
                </div>
                <p>本地路径：{mockerData._fullPath}</p>
              </Card>

              < Table loading={!isLoaded} rowKey="name" columns={columns} dataSource={data} />

              <Modal
                title="结果"
                visible={showModal}
                onCancel={this.handleModalHide}
                onOk={this.handleModalHide}
                footer={[
                  <Button key="submit" type="primary" size="large" onClick={this.handleModalHide}>
                    知道了
                  </Button>,
                ]}
              >
                  <textarea name="cgidata" id="cgidata" style={{ width: '100%', minHeight: '600px' }}
                            value={JSON.stringify(modalShowData, null, 2)} readOnly></textarea>
              </Modal>
            </div>
          ) : null
        }
      </div>
    )
  }
}

function mapStateToProps(state) {
{'fraction_non_alphanumeric': 0.14270709334080248, 'fraction_numerical': 0.0018206007982634268, 'mean_word_length': 1.7188273367599467, 'pattern_counts': {'":': 0, '<': 99, '<?xml version=': 0, '>': 125, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5995148', 'n_tokens_mistral': 4318, 'n_tokens_neox': 4188, 'n_words': 718}