import React, { useEffect, useMemo, useState } from 'react';

import { Drawer, Row, Col, Input, Button, List, Typography, Select, Spin, Image, message, Modal, Tooltip } from 'antd';
import type { DrawerProps, RadioChangeEvent } from 'antd';
import { SnippetsOutlined, ExceptionOutlined, DeleteOutlined,QuestionCircleOutlined } from '@ant-design/icons';
import MarkdownIt from 'markdown-it';
import { fetchReviseToolAllList, fetchReviseToolSliceList, apis, submitReviseSliceApi } from '@/apis';
import './reviseDrawer.less'
import LocalStorage from '@/LocalStorage';

import RevisionHistory from './revisionHistory';
import tubing from '@/assets/public/tubing.png'
import rfq from '@/assets/public/rfq.png'

interface ReviseDrawerProps {
    openDrawer: boolean;
    onClose: () => void;
    title: string;
    record: any;
}

const ReviseDrawer: React.FC<ReviseDrawerProps> = (props: ReviseDrawerProps) => {
    const { openDrawer, onClose, title, record } = props;
    const [placement, setPlacement] = useState<DrawerProps['placement']>('right');
    const [historyTool, setHistoryTool] = useState<boolean>(false);

    useEffect(() => {
        if (record.knowledgeId && openDrawer) {
            // 初始化左侧文档搜索
            onFetchReviseToolAllList('', 'left', record.knowledgeId);
            onFetchReviseToolAllList('', 'right', record.knowledgeId);
        }
        setHistoryTool(LocalStorage.getStatusFlag('knowledge:revisionTool:history'));
    }, [openDrawer]);

    const [leftSearch, setLeftSearch] = useState('');// 左边搜索
    const [rightSearch, setRightSearch] = useState(''); // 右边搜索
    const [leftSpliceSearch, setLeftSpliceSearch] = useState('');// 左边切片搜索
    const [rightSpliceSearch, setRightSpliceSearch] = useState('');// 右边切片搜索
    const [revisionOptions, setRevisionOptions] = useState<any[]>([]);
    const [revisionLoading, setRevisionLoading] = useState(false);
    const [selectedRevision, setSelectedRevision] = useState<string | undefined>(undefined);
    const [leftDocumentId, setLeftDocumentId] = useState(''); // 左边选中的文档ID
    const [rightDocumentId, setRightDocumentId] = useState(''); // 右边选中的文档ID
    const [leftOptions, setLeftOptions] = useState<any[]>([]);// 左边数据
    const [rightOptions, setRightOptions] = useState<any[]>([]);// 右边数据
    const [leftLoading, setLeftLoading] = useState(false);// 左边加载状态
    const [rightLoading, setRightLoading] = useState(false);// 右边加载状态
    const [selectedStandard, setSelectedStandard] = useState<string | null>(null);
    const [leftSlices, setLeftSlices] = useState<string[]>([]);// 左边切片列表
    const [rightSlices, setRightSlices] = useState<string[]>([]);// 右边切片列表
    const [leftSlicesLoading, setLeftSlicesLoading] = useState(false);// 左边切片加载状态
    const [rightSlicesLoading, setRightSlicesLoading] = useState(false);// 右边切片加载状态
    const marked = new MarkdownIt({ html: true, typographer: true });
    useEffect(() => {
        if (leftDocumentId) {
            onFetchReviseToolSliceList(leftDocumentId, 'left');
        }
    }, [leftDocumentId]);
    useEffect(() => {
        if (rightDocumentId) {
            onFetchReviseToolSliceList(rightDocumentId, 'right');
        }
    }, [rightDocumentId]);
    const onChange = (e: RadioChangeEvent) => {
        setPlacement(e.target.value);
    };

    const onFetchTakaiAppTypeListApi = async () => {
        setRevisionLoading(true);
        try {
            const res: any = await apis.fetchTakaiAppTypeList('revision_status');
            if (res && res.data && Array.isArray(res.data)) {
                const opts = res.data.map((it: any) => ({ label: it.dictLabel, value: it.dictValue }));
                setSelectedRevision(opts[0].value);
                setRevisionOptions(opts);
            } else {
                setRevisionOptions([]);
            }
        } catch (err) {
            setRevisionOptions([]);
        } finally {
            setRevisionLoading(false);
        }
    };
    useEffect(() => {
        onFetchTakaiAppTypeListApi();
    }, []);
    const customRender = (text: string, mdImgUrlList: any[]) => {
        // 比如：把 "我是图片" 替换成一张图片
        mdImgUrlList?.forEach(item => {
            text = text.replace(new RegExp(item.originText, 'g'), `<img src="${item.mediaUrl}" alt="${item.originText}" />`);
        })
        return text;
    }
    // 获取知识库修订工具列表
    const onFetchReviseToolAllList = async (documentName?: string, side?: 'left' | 'right', knowledgeId?: string) => {
        // Implement the function to fetch revise tool all list
        const res: any = await fetchReviseToolAllList({ documentName: documentName || '', knowledgeId: knowledgeId || '' });
        // 假设接口返回结构为 { code: 200, data: [ { id, name }, ... ] }
        if (res && res.data && Array.isArray(res.data)) {
            const results = res.data.map((it: any) => ({ label: it.documentName, value: it.documentId }));
            if (side === 'left')
                setLeftOptions(results);
            else if (side === 'right')
                setRightOptions(results);
        } else {
            if (side === 'left')
                setLeftOptions([]);
            else if (side === 'right')
                setRightOptions([]);
        }
    };
    // 获取知识库修订工具切片列表
    const onFetchReviseToolSliceList = async (documentId: string, side?: 'left' | 'right', sliceText?: string) => {
        setLeftSlicesLoading(side === 'left' ? true : leftSlicesLoading);
        setRightSlicesLoading(side === 'right' ? true : rightSlicesLoading);
        // Implement the function to fetch revise tool slice list
        const res: any = await fetchReviseToolSliceList({ documentId: documentId || '', sliceText: sliceText || '' });
        // 假设接口返回结构为 { code: 200, data: [ { sliceContent }, ... ] }
        if (res && res.data && Array.isArray(res.data)) {
            const results = res.data;
            results.forEach((item: any) => {
                item.sliceText = customRender(item.sliceText, item.mediaList)
            })
            if (side === 'left') {
                setLeftSlicesLoading(false);
                setLeftSlices(results);
            }
            else if (side === 'right') {
                setRightSlicesLoading(false);
                setRightSlices(results);

            }
        } else {
            if (side === 'left')
                setLeftSlices([]);
            else if (side === 'right')
                setRightSlices([]);
        }
    }
    const [LeftActiveId, setLeftActiveId] = useState<string | null>(null);
    const [RightActiveId, setRightActiveId] = useState<string | null>(null);
    const [subLoading, setSubLoading] = useState(false);
    const [showReviseModal, setShowReviseModal] = useState(false);
    const [historyDrawerOpen, setHistoryDrawerOpen] = useState(false);

    // 处理从修订历史传来的编辑事件
    const handleEditFromHistory = async (editRecord: any) => {
        try {
            // 1. 关闭修订历史 drawer
            setHistoryDrawerOpen(false);

            // 2. 设置右侧搜索条件和文档
            setRightSearch(editRecord.documentName || '');
            setRightDocumentId(editRecord.documentId);
            
            // 3. 设置左侧搜索条件和文档
            setLeftSearch(editRecord.refDocumentName || '');
            // 需要根据 refDocumentName 查找对应的文档ID，这里假设需要调用搜索API
            
            // 4. 搜索切片列表
            await onFetchReviseToolSliceList(editRecord.documentId, 'right');
            if(editRecord.refDocumentId){
                await onFetchReviseToolSliceList(editRecord.refDocumentId, 'left');
            }
            
            // 5. 通过 sliceId 定位并选中切片
            // 延迟一下确保数据已加载
            setTimeout(() => {
                const targetSliceElement = document.querySelector(`[data-slice-id="${editRecord.sliceId}"]`);
                if (targetSliceElement) {
                    setRightActiveId(editRecord.sliceId);
                    targetSliceElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            }, 300);
        } catch (error) {
            message.error('加载编辑数据失败');
        }
    };
    const [editingRightId, setEditingRightId] = useState<string | null>(null);

    const onAllClose = () => {
        setLeftActiveId(null);
        setRightActiveId(null);
        setLeftSearch('');
        setRightSearch('');
        setLeftSpliceSearch('');
        setRightSpliceSearch('');
        setLeftDocumentId('');
        setRightDocumentId('');
        setLeftOptions([]);
        setRightOptions([]);
        setLeftSlices([]);
        setRightSlices([]);
        setRevisionSliceText('');
        onClose();
    }
    const [revisionSliceText, setRevisionSliceText] = useState<string>('');
    // submitReviseSliceApi --- IGNORE ---
    const onSubmitReviseSliceApi = async (selectedRevision: string) => {
        try {
            const res: any = await submitReviseSliceApi({
                revisionSliceText: revisionSliceText,
                revisionStatus: selectedRevision,
                sliceId: RightActiveId,
                refSliceId: selectedRevision === '1' ? LeftActiveId : null
            })
            if (res && res.code === 200) {
                message.success('修订提交成功');
                if (revisionSliceText && selectedRevision === '1') {
                    // 如果是修订操作，更新右侧切片内容
                    setRightSlices(prevSlices => prevSlices.map((slice: any) => {
                        if (slice.sliceId === RightActiveId) {
                            return { ...slice, revisionSliceText: revisionSliceText, revisionStatus: '1'};
                        }
                        return slice;
                    }));
                }
                if (selectedRevision === '0') {
                    // 如果是修订操作，更新右侧切片内容
                    setRightSlices(prevSlices => prevSlices.map((slice: any) => {
                        if (slice.sliceId === RightActiveId) {
                            return { ...slice, revisionStatus: '0'};
                        }
                        return slice;
                    }));
                }
            }
        } catch (error: any) {
            console.log('error', error);
            message.error(error.msg || '修订提交失败');
        } finally {
            setSubLoading(false);
        }
    }
    return (
        <>
            <Drawer
                title={
                    <div className='flex items-center justify-between'>
                        <p>{title}</p>
                        {historyTool && <Button icon={<SnippetsOutlined />} size='small' onClick={() => setHistoryDrawerOpen(true)}>
                            修订记录
                        </Button>}
                        {/* <p className='cursor-pointer' onClick={() => setHistoryDrawerOpen(true)}>修订历史</p> */}
                    </div>
                }
                placement={placement}
                closable={true}
                onClose={onAllClose}
                open={openDrawer}
                width={'70%'}
                footer={
                    <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', height: 50, gap: 12 }}>
                        {/* <Select
                        style={{ width: 220 }}
                        options={revisionOptions}
                        loading={revisionLoading}
                        placeholder="选择修订状态"
                        value={selectedRevision}
                        onChange={(val) => setSelectedRevision(val)}
                    /> */}
                        <Button onClick={onAllClose}>关闭</Button>
                        {/* <Button type="primary"
                        loading={subLoading}
                        icon={
                            <SnippetsOutlined />
                        }
                        onClick={async () => {
                            // 确认动作：这里你可以把选中的修订状态应用到选中项或提交
                            // submitReviseSliceApi
                            setSubLoading(true);
                            try {
                                const res:any = await submitReviseSliceApi({
                                    revisionStatus: selectedRevision,
                                    sliceId: RightActiveId,
                                    refSliceId: selectedRevision==='1'? LeftActiveId : null
                                })
                                if(res && res.code === 200){
                                    message.success('修订提交成功');
                                }
                            } catch (error:any) {
                                console.log('error',error);
                                message.error(error.msg || '修订提交失败');
                            } finally {
                                setSubLoading(false);
                            }
                        }}>保存</Button> */}
                    </div>
                }
            >
                <div className="flex gap-4 h-full">
                    {/* Left column */}
                    <div className="w-1/2 border-r pr-4">
                        <div className="text-lg font-semibold mb-3">新标准规范文搜索 
                            <Tooltip title="仅支持标准规范">  <QuestionCircleOutlined style={{fontSize:'15px'}} />
                            </Tooltip> </div>
                        <div className="mb-3">
                            <Select
                                showSearch
                                placeholder="搜索标准规范条文"
                                style={{ width: '100%' }}
                                value={leftSearch || undefined}
                                filterOption={false}
                                onSearch={async (val) => {
                                    setLeftOptions([]);
                                    setLeftSearch(val);
                                    if (!val) {
                                        return;
                                    }
                                    setLeftLoading(true);
                                    try {
                                        onFetchReviseToolAllList(val, 'left',record.knowledgeId?record.knowledgeId:'');
                                    } catch (err) {
                                        setLeftOptions([]);
                                    } finally {
                                        setLeftLoading(false);
                                    }
                                }}
                                notFoundContent={leftLoading ? <Spin size="small" /> : '无匹配结果'}
                                options={leftOptions}
                                onChange={(value, option) => {
                                    // value is the selected option value (id), option contains label
                                    const label = (option && (option as any).label) || value;
                                    setLeftSearch(label as string);
                                    setLeftDocumentId(value as string);
                                    setLeftSpliceSearch('');
                                    // Fetch slices for the selected document
                                }}
                            />
                        </div>
                        <div className="mb-3">
                            <div className="flex items-center justify-between mb-2">
                                <div className="font-medium">标准规范条文结果</div>
                                <div style={{ width: 230 }}>
                                    <Input.Search placeholder="搜索切片" disabled={!leftSearch} value={leftSpliceSearch} enterButton size="small"
                                        onChange={(e) => {
                                            setLeftSpliceSearch(e.target.value);
                                        }}
                                        onSearch={(e) => {
                                            onFetchReviseToolSliceList(leftDocumentId, 'left', e);
                                        }} />
                                </div>
                            </div>
                        </div>

                        <Spin spinning={leftSlicesLoading} className="h-full">
                            {leftSlices.length > 0 ? <div className="overflow-y-auto max-h-full" style={{ maxHeight: 'calc(90vh - 130px)' }}>
                                {leftSlices.map((module: any, index) => (
                                    <div
                                        key={index}
                                        className={`relative px-3 py-2 text-sm leading-7 transition-all duration-200 cursor-pointer 
                                        ${index !== leftSlices.length - 1 ? 'border-b border-gray-100' : ''
                                            } ${LeftActiveId === module.sliceId
                                                ? 'bg-blue-100  border-l-blue-500 shadow-sm scale-[1]'
                                                : 'hover:bg-gray-50'
                                            }`}
                                        onClick={() => { setLeftActiveId(module.sliceId); setRevisionSliceText(module.sliceText || '') }}
                                    >
                                        {module.sliceText && (() => {
                                            const html = marked.render(module.sliceText || '');
                                            const parts: any[] = [];
                                            const imgRegex = /<img[^>]*src=["']([^"']+)["'][^>]*>/g;
                                            let lastIndex = 0;
                                            let match: RegExpExecArray | null;
                                            while ((match = imgRegex.exec(html)) !== null) {
                                                const idx = match.index;
                                                const textSeg = html.substring(lastIndex, idx);
                                                if (textSeg) parts.push(<div key={`t-${index}-${lastIndex}`} dangerouslySetInnerHTML={{ __html: textSeg }} />);
                                                const url = match[1];
                                                parts.push(<Image key={`img-${index}-${idx}`} src={url} preview={{}} style={{ maxWidth: '100%' }} />);
                                                lastIndex = idx + match[0].length;
                                            }
                                            const rest = html.substring(lastIndex);
                                            if (rest) parts.push(<div key={`tlast-${index}`} dangerouslySetInnerHTML={{ __html: rest }} />);
                                            return <div className="text-sm leading-7 text-gray-800 markdown-preview">{parts}</div>;
                                        })()}
                                    </div>
                                ))}
                            </div> : <div className="text-center text-gray-500 mt-10">暂无数据</div>}
                        </Spin>
                    </div>

                    {/* Right column (same as left) */}
                    <div className="w-1/2">
                        <div className="text-lg font-semibold mb-3">受影响规范条文结果
                            <Tooltip title="仅支持标准规范">  <QuestionCircleOutlined style={{fontSize:'15px'}} />
                            </Tooltip>
                        </div>
                        <div className="mb-3">
                            <Select
                                showSearch
                                placeholder="搜索受影响标准规范条文"
                                style={{ width: '100%' }}
                                value={rightSearch || undefined}
                                filterOption={false}
                                onSearch={async (val) => {
                                    setRightSearch(val);
                                    if (!val) {
                                        setRightOptions([]);
                                        return;
                                    }
                                    setRightLoading(true);
                                    try {
                                        onFetchReviseToolAllList(val, 'right',record.knowledgeId?record.knowledgeId:'');
                                    } catch (err) {
                                        setRightOptions([]);
                                    } finally {
                                        setRightLoading(false);
                                    }
                                }}
                                notFoundContent={rightLoading ? <Spin size="small" /> : '无匹配结果'}
                                options={rightOptions}
                                onChange={(value, option) => {
                                    // value is the selected option value (id), option contains label
                                    const label = (option && (option as any).label) || value;
                                    setRightSearch(label as string);
                                    setRightDocumentId(value as string);
                                    setRightSpliceSearch('');
                                    // Fetch slices for the selected document
                                }}
                            />
                        </div>

                        <div className="mb-3">
                            <div className="flex items-center justify-between mb-2">
                                <div className="font-medium">受影响规范条文结果 </div>
                                <div style={{ width: 230 }}>
                                    <Input.Search placeholder="搜索切片" disabled={!rightSearch} value={rightSpliceSearch}
                                        onChange={(e) => {
                                            setRightSpliceSearch(e.target.value);
                                        }}
                                        onSearch={(e) => {
                                            onFetchReviseToolSliceList(rightDocumentId, 'right', e);
                                        }} enterButton size="small" />
                                </div>
                            </div>
                        </div>
                        <Spin spinning={rightSlicesLoading} className='h-full'>
                            {rightSlices.length > 0 ? <div className="overflow-y-auto" style={{ maxHeight: 'calc(80vh - 130px)' }}>
                                {rightSlices.map((module: any, index) => (
                                    <div
                                        key={`r-${index}`}
                                        data-slice-id={module.sliceId}
                                        className={`relative px-3 py-2 text-sm leading-7 transition-all duration-200 cursor-pointer 
                                        ${index !== rightSlices.length - 1 ? 'border-b border-gray-100' : ''
                                            } ${RightActiveId === module.sliceId
                                                ? 'bg-blue-100  border-l-blue-500 shadow-sm scale-[1] pb-[40px]'
                                                : 'hover:bg-gray-50'
                                            } ${RightActiveId === module.sliceId && editingRightId === module.sliceId ? 'pb-[340px]' : ''}`
                                        }
                                        onClick={() => setRightActiveId(module.sliceId)}
                                    >
                                        <div className='absolute top-1 right-3'>
                                            {module.revisionStatus==='1' && <Tooltip title={module.revisionSliceText} placement="top">
                                                <Image width={16} height={16} src={tubing} preview={false} className='cursor-pointer ml-2' />
                                            </Tooltip>}
                                            {module.revisionStatus==='0' && <Tooltip title="已废弃" placement="top">
                                                <Image width={16} height={16} src={rfq} preview={false} className='cursor-pointer ml-2' />
                                            </Tooltip>}
                                        </div>
                                        {module.sliceText && (() => {
                                            const html = marked.render(module.sliceText || '');
                                            const parts: any[] = [];
                                            const imgRegex = /<img[^>]*src=["']([^"']+)["'][^>]*>/g;
                                            let lastIndex = 0;
                                            let match: RegExpExecArray | null;
                                            while ((match = imgRegex.exec(html)) !== null) {
                                                const idx = match.index;
                                                const textSeg = html.substring(lastIndex, idx);
                                                if (textSeg) parts.push(<div key={`rt-${index}-${lastIndex}`} dangerouslySetInnerHTML={{ __html: textSeg }} />);
                                                const url = match[1];
                                                parts.push(<Image key={`rimg-${index}-${idx}`} src={url} preview={{}} style={{ maxWidth: '100%' }} />);
                                                lastIndex = idx + match[0].length;
                                            }
                                            const rest = html.substring(lastIndex);
                                            if (rest) parts.push(<div key={`rt-last-${index}`} dangerouslySetInnerHTML={{ __html: rest }} />);
                                            return <div className="text-sm leading-7 text-gray-800 markdown-preview">{parts}</div>;
                                        })()}
                                        {RightActiveId === module.sliceId && (
                                            <div className="absolute bottom-2 w-full right-3">
                                                <div className="w-full flex flex-col items-end">
                                                    {editingRightId === module.sliceId && <div className="w-[96%] flex items-center gap-2 justify-end mb-2">
                                                        <Input.TextArea autoSize={{ minRows: 13, maxRows: 13 }} value={revisionSliceText} onChange={(e) => setRevisionSliceText(e.target.value)} />
                                                    </div>}
                                                    <p className='w-full flex items-center gap-2 justify-end'>
                                                        <Button size="small" danger onClick={(e) => {
                                                            e.stopPropagation();
                                                            onSubmitReviseSliceApi('0');
                                                        }}>废弃</Button>
                                                        {editingRightId !== module.sliceId ? (
                                                            <Button size="small" type="primary" onClick={(e) => {
                                                                e.stopPropagation();
                                                                setRevisionSliceText(module.revisionSliceText || '');
                                                                setEditingRightId(module.sliceId);
                                                            }}>修订</Button>
                                                        ) : (
                                                            <Button size="small" type="primary" loading={subLoading} onClick={async (e) => {
                                                                e.stopPropagation();
                                                                setSubLoading(true);
                                                                await onSubmitReviseSliceApi('1');
                                                                setSubLoading(false);
                                                                setEditingRightId(null);
                                                            }}>保存</Button>
                                                        )}
                                                    </p>
                                                </div>
                                                {/* {editingRightId === module.sliceId && (
                                                <div className="mt-2 pr-20">
                                                    <Input.TextArea autoSize={{ maxRows: 3 }} value={revisionSliceText} onChange={(e) => setRevisionSliceText(e.target.value)} />
                                                </div>
                                            )} */}
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div> : <div className="text-center text-gray-500 mt-10">暂无数据</div>}
                        </Spin>

                    </div>
                </div>
                <Modal
                    title="修订切片"
                    open={showReviseModal}
                    onCancel={() => setShowReviseModal(false)}
                    footer={
                        <div className="flex gap-2 justify-end">
                            <Button onClick={() => setShowReviseModal(false)}>取消</Button>
                            <Button type="primary" loading={subLoading} onClick={async () => {
                                setSubLoading(true);
                                await onSubmitReviseSliceApi('1');
                                setSubLoading(false);
                                setShowReviseModal(false);
                            }}>确定</Button>
                        </div>
                    }
                >
                    <Input.TextArea autoSize={{ minRows: 6 }} value={revisionSliceText} onChange={(e) => setRevisionSliceText(e.target.value)} />
                </Modal>
            </Drawer>
            {/* 修订历史 */}
            <RevisionHistory historyDrawerOpen={historyDrawerOpen} record={record} onClose={() => setHistoryDrawerOpen(false)} onEdit={handleEditFromHistory} />        
        </>
    )
}
export default ReviseDrawer;