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

type CodeTestProps = {
    data: any
    report: any
    codePlayerConnect?: any
    // topicStatus: '0' | '1'  0 失败 1 成功  undefined 没有说成功或者失败
    updateActivity?: (activityId: string, topicConfig: string, topicResult: string, topicStatus?: '0' | '1') => Promise<any>
    preActive?: (data: any) => boolean | void
}

// 编码测验
const CodeTest: React.FC<CodeTestProps> = (props) => {

    const { data = {}, report, codePlayerConnect, updateActivity, preActive } = props

    
    // 未作答， 做答完成  校验成功 校验失败
    const [status, setStatus] = useState<'' | 'finish' | 'success' | 'error'>('')
    const [currentData, setCurrentData] = useState(data)
    // 用来判断是否点击过按钮
    const [hasClick, setHasClick] = useState(0)

    const { title = '', topic = '', buttonName = '', required = false } = currentData

    const onClick = () => {
        if (preActive && preActive(data)) return
        setHasClick((pre) => ++pre)
        report()
        openCodePlayer()
    }

    const openCodePlayer = async () => {
        if (!codePlayerConnect) return
        let _data = {...currentData}
        let _code = _data.code ?? ''
        let _status = status
        codePlayerConnect(
            _data,   // 当前数据
            () => {  // 打开后回调
                // 不是输入输出校验 为主观校验，完成后状态直接为已作答
                if (data.verifyMode && data.verifyMode != 'INPUT_OUTPUT' && _status !== 'finish') {
                    updateActivity?.(data.id, JSON.stringify(_data), _code, undefined)
                    setStatus(_status = 'finish')
                }
            },
            (code: string) => { // 代码编辑回调
                _code = code
                if (!_status) {
                    setStatus(_status = 'finish')
                }
                updateActivity?.(data.id, JSON.stringify(_data), _code, _status === 'success' ? '1' : _status === 'error' ? '0' : undefined)
            },
            (pass: boolean) => {// 代码运行结果回调  true 运行成功  false 运行失败
                setStatus(_status = (pass ? 'success' : 'error'))
                updateActivity?.(data.id, JSON.stringify(_data), _code, pass ? '1' : '0')
            }
        )
        // // 打开
        // const hander = codePlayerConnect.open()
        // if (!hander) return
        // // 发送初始数据
        // const sendRef = await codePlayerConnect.send(hander, currentData)

        // let _data = {...currentData}
        // let code = _data.code ?? ''
        // // 监听
        // codePlayerConnect?.listenChange(hander, (e: any) => {
        //     // _data = {..._data, code: e}
        //     // _data.code = e ?? ''
        //     // setCurrentData(_data)
        //     code = e ?? ''
        //     updateActivity?.(data.id, JSON.stringify(_data), e ?? '', status === 'success' ? '1' : '0')
        // })
        // codePlayerConnect?.listenResult(hander, (e: any) => {
        //     const pass = e.pass
        //     setStatus(pass ? 'success' : 'error')
        //     updateActivity?.(data.id, JSON.stringify(_data), code, pass ? '1' : '0')
        // })
    }

    useEffect(() => {
        if (data?.topicResult != undefined) {
            setCurrentData({...data, code: data?.topicResult})
            setStatus('finish')
            setHasClick(1)
        } else {
            setCurrentData({...data})
            setStatus('')
        }
        if (data?.topicStatus) {
            setStatus(data?.topicStatus === '1' ? 'success' : 'error')
            setHasClick(1)
        }
    }, [data])

    return (
        <div className='codetest codetest-active' data-hasclick={!!hasClick} contentEditable={false} data-required={required}>
            <div className='title'>编码测验</div>

            <div className='codetest-topic'>{topic}</div>

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

            <div className='codetest-btns'>
                {
                    status === '' ? <Button onClick={onClick} type='primary' style={{ minWidth: '88px' }}>{buttonName}</Button> :
                        status === 'finish' ? <div onClick={onClick} className='codetest-btns-btn' style={{ '--color': '#1677ff', '--hover': '#e8f1ff' } as any}>已作答，可重新进入修改</div> :
                            status === 'success' ? <div onClick={onClick} className='codetest-btns-btn' style={{ '--color': '#30c213', '--hover': '#eaf9e7' } as any}>已通过校验，可重新进入修改</div> :
                                status === 'error' ? <div onClick={onClick} className='codetest-btns-btn' style={{ '--color': '#f5222d', '--hover': '#fee9ea' } as any}>未通过校验，可重新进入修改</div> : <></>
                }
            </div>
        </div>
    )
}

export default CodeTest