import React, { useState, useCallback } from 'react';
import isPlainObject from 'lodash/isPlainObject';
import isArray from 'lodash/isArray';

const { CodeControl } = window?.VisualEngineUtils || {};

const { Button, CnBalloon, CnMessage } = window.CNUI || {};

export function JsonEditor(props) {
  const [visible, setVisible] = useState(false);
  const [code, setCode] = useState('');
  const { value, onChange } = props;
  const edit = () => {
    if (value) {
      if (isPlainObject(value) || isArray(value)) {
        try {
          setCode(JSON.stringify(value, null, '\t'));
        } catch (e) {}
        setVisible(true);
      }
    }
  };

  const onOk = () => {
    try {
      const result = JSON.parse(code);
      if (result) {
        onChange?.(result);
        setCode('');
        setVisible(false);
      }
    } catch (e) {
      CnMessage.error('数据不符合JSON格式');
    }
  };

  return (
    <div className=''>
      <CnBalloon
        // type={'primary'}
        visible={visible}
        align={'tr'}
        v2
        onVisibleChange={(v) => {
          setVisible(v);
        }}
        closable
        triggerType={'click'}
        title={'JSON编辑器'}
        trigger={
          <Button size={'small'} style={{ width: '160px' }} onClick={edit}>
            JSON编辑器
          </Button>
        }
      >
        <CodeControl
          value={code}
          options={{ minimap: { enabled: false }, lineNumbers: 'off' }}
          className=''
          mode='json' // 'javascript', 'json', 'html', 'css', 'jsx'
          fontSize={14}
          tabSize={2}
          // readOnly={false}
          style={{ width: '260px', height: 200 }}
          onChange={(code) => {
            setCode(code);
          }}
          // // 如果为 false 或者 0 则不启动节流阀
          throttle={600}
          lineNumbers={'off'}
          enableOutline={false}
          // enableSuggestion
          // defaultSuggestion
          // enableBlurChange
          // diyWordSuggestion
          // checkSyntax // 是否开启预编译检查（限js）
          // // customeSuggestion={getSuggestion}
          // onEditorDidMount={(editor, monaco) => {
          //   console.log('editor, monaco:::>>>', editor, monaco);
          // }} // 编辑器初始化完成
        />
        <div
          style={{
            paddingTop: '10px',
            borderTop: '1px solid #ddd',
            display: 'flex',
            justifyContent: 'flex-end',
          }}
        >
          <Button
            onClick={() => {
              setCode('');
              setVisible(false);
            }}
            size={'small'}
            // type={'secondary'}
          >
            取消
          </Button>
          &nbsp;&nbsp;
          <Button onClick={onOk} size={'small'} type={'secondary'}>
            确定
          </Button>
        </div>
      </CnBalloon>
    </div>
  );
}
