import { getConfigContent, saveConfigContent } from '@/services/webConfig/api';
import { Button, Modal, notification } from 'antd';
import React, { Children, useState } from 'react';
import AceEditor from 'react-ace';
import styles from './webMenu.less';
import 'ace-builds/src-noconflict/mode-json';
import 'ace-builds/src-noconflict/theme-solarized_light';

const ConfigWrapper = props => {
  const { value, children, onChange, ...rest } = props;
  const [text, setText] = useState('');
  const [visible, setVisible] = useState(false);

  const showModal = () => {
    if (!value) {
      notification.warning({
        message: '请先填写配置文件名称',
        duration: 3,
      });
      return;
    }
    getConfigContent(value)
      .then(res => {
        if (res.code === 0) {
          setText(res.data);
        }
      })
      .catch(e => {
        console.error(e);
      });
    setVisible(true);
  };

  const handleOk = () => {
    let content;
    let err = false;
    try {
      content = JSON.parse(text);
    } catch (error) {
      notification.error({
        message: '编辑内容必须是json格式',
        duration: 5,
      });
      err = true;
    }
    if (!err) {
      saveConfigContent(value, JSON.stringify(JSON.parse(text), null, 4))
        .then(res => {
          if (res.code === 0) {
            notification.success({
              message: '保存成功',
              duration: 3,
            });
            setVisible(false);
          }
        })
        .catch(error => {
          console.error(error);
        });
    }
  };

  const handleChange = v => {
    onChange(v[v.length - 1] || '');
  };

  return (
    <div style={{ display: 'flex' }}>
      {Children.map(children, child =>
        React.cloneElement(child, {
          ...rest,
          value: value ? [value] : [],
          mode: 'tags',
          onChange: handleChange,
        }),
      )}
      {<Button onClick={showModal}>编辑文件</Button>}
      <Modal
        title="编辑配置"
        visible={visible}
        onOk={handleOk}
        width={650}
        className={styles.modal}
        maskClosable={false}
        onCancel={() => setVisible(false)}
      >
        <AceEditor
          mode="json"
          theme="solarized_light"
          value={text}
          name="UNIQUE_ID_OF_DIV"
          fontSize={14}
          showPrintMargin
          showGutter
          width="100%"
          wrapEnabled
          highlightActiveLine
          setOptions={{
            enableBasicAutocompletion: false,
            enableLiveAutocompletion: false,
            enableSnippets: false,
            showLineNumbers: true,
            tabSize: 2,
          }}
          onChange={v => {
            setText(v);
          }}
          rows={10}
        />
      </Modal>
    </div>
  );
};
export default ConfigWrapper;
