import React, { Component } from 'react'
import { Form, message as Message, Spin } from 'antd'
import { AntIcon } from 'components'
import { cloneDeep } from 'lodash'
import MonacoEditor from 'react-monaco-editor'
import store from 'store'

const { getState } = store

const initialValues = {}

export default class form extends Component {
    state = {
        // 加载状态
        loading: true,
        ...getState('layout'),
    }

    // 表单实例
    form = React.createRef()

    code = React.createRef()

    // 初始化数据
    record = {}

    /**
     * mount后回调
     */
    componentDidMount() {
        this.props.created && this.props.created(this)
    }

    /**
     * 填充数据
     * 可以在设置this.record之后对其作出数据结构调整
     * [异步,必要]
     * @param {*} params
     */
    async fillData(params) {
        this.record = cloneDeep(params.record)
        //#region 从后端转换成前段所需格式
        this.code.current.editor.setValue(this.record.extCode || '')
        setTimeout(() => {
            this.code.current.editor.getAction(['editor.action.formatDocument'])._run()
        }, 100)
        //#endregion
        this.form.current.setFieldsValue(this.record)

        this.setState({
            loading: false,
        })
    }

    /**
     * 获取数据
     * 可以对postData进行数据结构调整
     * [异步,必要]
     * @returns
     */
    async getData() {
        const form = this.form.current

        const valid = await form.validateFields()
        if (valid) {
            const postData = form.getFieldsValue()
            if (this.record) {
                postData.id = this.record.id
            }
            //#region 从前段转换后端所需格式
            try {
                const code = JSON.parse(this.code.current.editor.getValue())
                if (code.constructor === Object) {
                    postData.extCode = JSON.stringify(code)
                } else {
                    throw new Error(0)
                }
            } catch {
                Message.error('错误的JSON格式')
            }
            //#endregion
            return postData
        }
    }

    //#region 自定义方法
    //#endregion

    render() {
        const { theme } = this.state

        return (
            <Form initialValues={initialValues} ref={this.form} className="yo-form">
                <Spin spinning={this.state.loading} indicator={<AntIcon type="loading" />}>
                    <div className="yo-form-group">
                        <MonacoEditor
                            height={300}
                            language="json"
                            theme={theme === 'dark' ? 'vs-dark' : 'default'}
                            options={{
                                fontSize: 12,
                            }}
                            ref={this.code}
                        />
                    </div>
                </Spin>
            </Form>
        )
    }
}
