/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-01-04 13:46:15
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-11-20 17:52:27
 * @FilePath: /CostAccountingSys/src/components/SQLEditor/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useEffect, useState } from 'react';
import MonacoEditor from 'react-monaco-editor';
import { Form, message, Modal, Input } from 'antd';
import './style.less';
import { copyToClipboard } from '@/utils/tooljs';

interface SQLEditorProps {
    name: string;
    label: string;
    rules: { required: boolean; message: string }[];
    form: any; // 你可以根据你的表单库提供更具体的类型
    width?: string; // 可选的宽度属性
    height?: string;
    value?: string;
}

function extractSqlParameters(sqlQuery:string) {
    // 正则表达式匹配冒号开头的参数名，如 :param
    const paramRegex = /#(\w+)/g;
    const params = [];
  
    let match;
    while (match = paramRegex.exec(sqlQuery)) {
      params.push(match[1]); // 将匹配的参数名添加到数组中
    }
  
    return params;
  }

const SQLEditor: React.FC<SQLEditorProps> = ({ name, label, rules, form, width = '100%', value = '', height = '100%' }) => {
    const [editorValue, setEditorValue] = useState(value);
    const [modalForm] = Form.useForm();
    const handleSQLEditorChange = (newValue: string) => {
        setEditorValue(newValue); 
        form.current.setFieldValue(name, newValue);
    };

    const copyHandle = ()=>{
        copyToClipboard(editorValue as string);
        message.success('复制成功！');
    }

    const verifyHandle = ()=>{
        const params = extractSqlParameters(editorValue as string);
        

        Modal.confirm({
            title:'验证参数',
            icon:null,
            content:(
                <Form form={modalForm} layout="vertical">
                    {[...new Set(params)].map(param => (
                        <Form.Item
                            key={param}
                            label={`${param}`}
                            name={param}
                            rules={[{ required: true, message: `请输入${param}` }]}
                        >
                            <Input />
                        </Form.Item>
                    ))}
                </Form>
            ),
            onOk: () => {
                return new Promise((resolve, reject) => {
                    modalForm.validateFields()
                        .then(values => {
                            let finalSql = editorValue as string;
                            params.forEach(param => {
                                finalSql = finalSql.replace(new RegExp(`#${param}`, 'g'), values[param]);
                            });
                            copyToClipboard(finalSql);
                            message.success('替换参数值并复制成功！');
                            resolve(true);
                        }).catch(errorInfo => {
                            reject(errorInfo);
                        });
                });
            }
        })
    }

    const editorDidMount = (editor:any, monaco:any) => {
        editor.focus();
    };
    
    const handleEditorWillMount = (monaco: any) => {
        // 绑定事件确保粘贴未被拦截
        monaco.editor.onDidPaste(() => {
            console.log('Pasted content');
        });
    };

    useEffect(() => {
        setEditorValue(form.current.getFieldValue(name));
    }, [form, name]);

    return (
        <Form.Item
            name={name}
            label={label}
            rules={rules}
            getValueProps={() => ({ value: editorValue })}
        >
            <div className='sql_editor' style={{ border: '1px solid #CFD7E6', borderRadius: 4 }}>
                <MonacoEditor
                    language="sql"
                    theme="vs-light"
                    value={editorValue}
                    options={{
                        selectOnLineNumbers: true,
                        // autoIndent: true,
                        
                        automaticLayout: true,
                        fontSize: 14,
                        pasteAs:{
                            enabled:true,
                            showPasteSelector:'afterPaste'
                        }
                    }}
                
                    width={width}
                    height={height}
                    onChange={handleSQLEditorChange}
                    editorDidMount={editorDidMount}
                    editorWillMount={handleEditorWillMount}
                />
                <div className='editerFooter'>
                       <div className='a' onClick={()=>copyHandle()}>原文复制</div>
                       <div className='b' onClick={()=>verifyHandle()}>替换参数值并复制</div>
                </div>
            </div>
        </Form.Item>
    );
};

export default SQLEditor;
