import React, { useState } from 'react'
import './index.less'
import EditorComponent from '../../components/RichEditor'
import CodeHighlight from './CodeHighlight'
import { Button } from 'antd'

type DemoProps = {
    data: any
    report: any
    exec?: () => void
    preActive?: (data: any) => boolean | void
}

const language: any = {
    shell: 'PowerShell',
    java: 'java',
    python: 'python'
}

// 示例演示
const Demo: React.FC<DemoProps> = (props) => {

    const { data = {}, report, exec, preActive } = props

    const { title = '', code = '', codeLanguage, buttonName = '', showCode = false, required = false } = data

    // 用来判断是否点击过按钮
    const [hasClick, setHasClick] = useState(0)
    
    const submit = async () => {
        if (preActive && preActive(data)) return
        setHasClick((pre) => ++pre)
        report()
        exec?.()
    }

    return (
        <div className='demo demo-active' contentEditable={false} data-hasclick={!!hasClick} data-required={required}>
            <div className='title'>示例演示</div>

            <div className='demo-content'>
                <EditorComponent value={title} readOnly/>
            </div>

            {
                showCode && <CodeHighlight value={code} lang={language[codeLanguage] ?? codeLanguage} />
            }

            <Button type='primary' onClick={submit} style={{ minWidth: '88px', marginTop: showCode ? '20px' : '4px' }}>{buttonName}</Button>
        </div>
    )
}

export default Demo