import React from 'react';
import { Button } from 'antd';
import 'brace/mode/javascript';
import AceEditor from 'react-ace';
import FormulaForm from './FormulaForm';
import { getModal } from '@/webPublic/one_stop_public/utils/utils';

const Modal = getModal();

export default class FormulaAll extends React.Component {
	constructor(props) {
		super(props);
		const value = props.value;
		this.state = {
			isFormula: false, // 是否展示公式选择栏
			isOne: false, // 是否为用户点击,排除渲染时重复展示
			content: value,
		};
	}

	triggerChange = (changedValue) => {
		// Should provide an event to pass value to Form.
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			const value = nextProps.value;
			this.setState({ content: value });
		}
	}

	change = (value) => {
		if (!('value' in this.props)) {
			this.setState({ content: value });
		}
		this.triggerChange(value);
	};

	cutFormula = () => {
		this.setState({
			isFormula: true,
			isOne: true,
		});
	};
	// 关闭公式选择栏操作函数
	cutCloseFormula = () => {
		this.setState({
			isFormula: false,
		});
	};
	append = (func) => {
		const newC =
			this.state.content != null ? this.state.content + func : func != null ? func + '' : '';

		if (!('value' in this.props)) {
			this.setState({ content: newC });
		}
		this.triggerChange(newC);
	};
	render() {
		const { content, isFormula, isOne } = this.state;
		const xxx = (
			<AceEditor
				height={isFormula ? 600 : 300}
				width={isFormula ? 1200 : '100%'}
				placeholder="请输入公式"
				mode={'javascript'}
				theme={'textmate'}
				fontSize={14}
				onChange={this.change}
				showPrintMargin={true}
				showGutter={true}
				highlightActiveLine={true}
				value={content}
				name="UNIQUE_ID_OF_DIV"
				// keyboardHandler="vim"
				setOptions={{
					enableBasicAutocompletion: true,
					enableLiveAutocompletion: true,
					enableSnippets: true,
					showLineNumbers: true,
					tabSize: 2,
				}}
				editorProps={{ $blockScrolling: true }}
			/>
		);
		return (
			<div>
				<Button icon="fullscreen" size="small" type="danger" onClick={this.cutFormula}>
					全屏编辑
				</Button>
				{isFormula ? (
					<Modal
						width="1200px"
						destroyOnClose
						title={'公式编辑'}
						visible={isFormula}
						footer={null}
						onCancel={() => this.setState({ isFormula: false })}>
						<FormulaForm
							editor={xxx}
							append={this.append}
							cutCloseFormula={this.cutCloseFormula}
							isOne={isOne}
							isFormula={true}
						/>
					</Modal>
				) : (
					xxx
				)}
			</div>
		);
	}
}