import * as React from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Spin, message, Form } from 'antd';
import { LeftOutlined } from '@ant-design/icons';
import Step1Drawer from './Step1Drawer';
import Step2Config from './Step2Config';
import { useQuestionAnswerFormStore } from './store';
import { apis } from '@/apis';
import LocalStorage from '@/LocalStorage';
import './style.scss';

const QuestionAnswerForm: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const [form] = Form.useForm();
    
    // 检查是否使用 Mock 数据
    const isDemo = import.meta.env.VITE_USE_MOCK === 'true';
    
    // 检查是否从 list 页面跳转而来（第一步）
    const isFromList = location.state?.fromList === true;
    
    const {
        step,
        pageLoading,
        appTypeList,
        appVisibleList,
        appProjectList,
        knowledgeList,
        modelList,
        rerankModelList,
        isAppPro,
        visibleFlag,
        vipList,
        topPValue,
        tempValue,
        isVisible,
        isVisibleCus,
        isVisibleSlice,
        isDeepThinkVisible,
        isMultiRound,
        automatic,
        name,
        appId,
        createFlag,
        inputs,
        selectedIcon,
        previewBg,
        setStep,
        setPageLoading,
        setAppTypeList,
        setAppVisibleList,
        setAppProjectList,
        setKnowledgeList,
        setModelList,
        setRerankModelList,
        setIsAppPro,
        setVisibleFlag,
        setVipList,
        setTopPValue,
        setTempValue,
        setIsVisible,
        setIsVisibleCus,
        setIsVisibleSlice,
        setIsDeepThinkVisible,
        setIsMultiRound,
        setAutomatic,
        setName,
        setAppId,
        setCreateFlag,
        setInputs,
        setSelectedIcon,
        setPreviewBg,
    } = useQuestionAnswerFormStore();

    const userInfo = LocalStorage.getUserInfo();
    const userId = (userInfo?.id ?? '').toString();

    // 初始化数据
    React.useEffect(() => {
        const id = location?.state?.id;
        init(id);
    }, []);

    const init = async (id?: string) => {
        setPageLoading(true);
        try {
            // 加载基础数据
            await Promise.all([
                fetchKnowledgeList(),
                fetchAppTypeList(),
                fetchAppVisibleList(id),
                fetchAppProTypeList(),
                fetchRerankModelList(),
            ]);

            // 如果是编辑模式，加载应用详情
            if (id) {
                await fetchAppDetail(id);
            } else {
                setCreateFlag(true);
            }
        } catch (error) {
            console.error('初始化失败:', error);
            message.error('加载失败');
        } finally {
            setPageLoading(false);
        }
    };

    // API 调用函数（支持 Mock 数据）
    const fetchKnowledgeList = async () => {
        if (isDemo) {
            setKnowledgeList([
                { label: '政务服务知识库', value: 'know_001', createBy: 'user_001' },
                { label: '市场监管法规库', value: 'know_002', createBy: 'user_002' },
                { label: '财税政策知识库', value: 'know_003', createBy: 'user_003' },
            ]);
            return;
        }
        try {
            const res = await apis.fetchTakaiKnowledgeList();
            const list = res.data.map((item: any) => ({
                label: item.name,
                value: item.knowledgeId,
                createBy: item.createBy,
            }));
            setKnowledgeList(list);
        } catch (error) {
            console.error('获取知识库列表失败:', error);
        }
    };

    const fetchAppTypeList = async () => {
        if (isDemo) {
            setAppTypeList([
                { label: '智能问答', value: '10' },
                { label: '文档分析', value: '20' },
                { label: '数据分析', value: '30' },
                { label: '专业应用', value: '62' },
            ]);
            return;
        }
        try {
            const res = await apis.fetchTakaiAppTypeList('app_type');
            const list = res.data.map((item: any) => ({
                label: item.dictLabel,
                value: item.dictCode,
            }));
            setAppTypeList(list);
        } catch (error) {
            console.error('获取应用类型失败:', error);
        }
    };

    const fetchAppVisibleList = async (id?: string) => {
        if (isDemo) {
            const list = [
                { label: '公开', value: '0' },
                { label: '私有', value: '1' },
            ];
            setAppVisibleList(list);
            if (!id) {
                form.setFieldValue('visible', list[0]?.value);
                setVisibleFlag(list[0]?.value);
            }
            return;
        }
        try {
            const res = await apis.fetchTakaiAppTypeList('app_visible');
            const list = res.data.map((item: any) => ({
                label: item.dictLabel,
                value: item.dictValue,
            }));
            setAppVisibleList(list);
            if (!id) {
                form.setFieldValue('visible', list[0]?.value);
                setVisibleFlag(list[0]?.value);
            }
        } catch (error) {
            console.error('获取可见性类型失败:', error);
        }
    };

    const fetchAppProTypeList = async () => {
        if (isDemo) {
            setAppProjectList([
                { label: '政务服务中心', value: '100', children: [{ label: '窗口服务', value: '101' }] },
                { label: '市场监管局', value: '200', children: [{ label: '企业注册', value: '201' }] },
                { label: '大数据局', value: '300', children: [{ label: '数据共享', value: '301' }] },
            ]);
            return;
        }
        try {
            const res = await apis.fetchTakaiAppTypeList('projectTree');
            const list = res.data?.reduce((acc: any, item: any) => {
                acc.push({
                    label: item.label,
                    value: `${item.value}`,
                });
                return acc;
            }, []);
            setAppProjectList(list);
        } catch (error) {
            console.error('获取项目类型失败:', error);
        }
    };

    const fetchRerankModelList = async () => {
        if (isDemo) {
            setRerankModelList([
                { label: 'bge-reranker-v2-m3', value: 'bge-reranker-v2-m3' },
                { label: 'bge-reranker-base', value: 'bge-reranker-base' },
            ]);
            return;
        }
        try {
            const res = await apis.fetchRerankModelList();
            const list = res.data.map((item: any) => ({
                label: item.model,
                value: item.model,
            }));
            setRerankModelList(list);
        } catch (error) {
            console.error('获取重排模型失败:', error);
        }
    };

    const fetchAppDetail = async (app_id: string) => {
        try {
            const res = await apis.fetchTakaiApplicationDetail(app_id);
            const info = res.data.detail;
            
            setAppId(info.appId);
            setTopPValue(info.topP as number);
            setTempValue(info.temperature as number);
            setName(info.name);
            
            // 解析 RAG 配置
            const data_info = JSON.parse(info.knowledgeInfo);
            
            if (data_info.param_desc === 'custom') {
                setIsVisibleCus(true);
            }
            if (data_info.rerank_status === true) {
                setIsVisible(true);
            }
            if (data_info.slice_config_type === 'fixed') {
                setIsVisibleSlice(true);
            }
            if (info.typeId === 62) {
                setIsAppPro(true);
            }
            if (info.model === 'Qwen3-30B') {
                setIsDeepThinkVisible(true);
            }
            if (data_info.is_multi_round === 'Y') {
                setIsMultiRound(true);
            }

            // 填充表单
            form.setFieldsValue({
                id: info.id,
                name: info.name,
                desc: info.desc,
                prompt: info.prompt,
                topP: info.topP,
                topK: info.topK,
                temperature: info.temperature,
                knowledge_ids: info.knowledgeIds,
                model: info.model,
                iconColor: info.iconColor,
                iconType: info.iconType,
                questionList: info.questionlist?.map((q: any) => q.question) || [],
                max_token: info.maxToken,
                appProId: info.appProId,
                typeId: info.typeId,
                visible: info.visible || '0',
                sort: info.sort,
                param_desc: data_info.param_desc,
                show_recall_result: data_info.show_recall_result,
                recall_method: data_info.recall_method,
                rerank_status: data_info.rerank_status,
                rerank_model_name: data_info.rerank_model_name,
                slice_config_type: data_info.slice_config_type,
                slice_count: data_info.slice_count,
                is_multi_round: data_info.is_multi_round === 'Y',
                multi_round: data_info.multi_round,
                groupVisible: info.groupVisible === '1',
            });

            setVisibleFlag(info.visible || '0');
            if (info.vipList && info.vipList.length > 0) {
                setVipList(info.vipList);
            }
            if (info.iconType) {
                setSelectedIcon(info.iconType);
            }
            if (info.iconColor) {
                setPreviewBg(info.iconColor);
            }

            setCreateFlag(LocalStorage.getStatusFlag('appCenter:questionAnswer:edit'));
        } catch (error) {
            console.error('获取应用详情失败:', error);
            message.error('加载应用详情失败');
        }
    };

    // 事件处理函数
    const handleAppChange = (typeId: number) => {
        if (typeId === 62) {
            setIsAppPro(true);
        } else {
            setIsAppPro(false);
        }
    };

    const handleVisibleChange = (value: any) => {
        setVisibleFlag(value);
    };

    const handleRemoveVip = (userId: string) => {
        if (userId === 'all') {
            setVipList([]);
        } else {
            setVipList(vipList.filter(item => item.userId !== userId));
        }
    };

    const handleVipConfirm = (users: any[]) => {
        setVipList(users);
        message.success(`已选择 ${users.length} 个用户`);
    };

    const handleNext = async () => {
        try {
            const values = await form.validateFields(['name', 'desc', 'appProId', 'iconType']);
            form.setFieldValue('questionList', inputs.map(input => input.value));
            setStep(2);
        } catch (error) {
            console.error('验证失败:', error);
        }
    };

    const handleBack = () => {
        if (step === 2) {
            // 如果是第二步，返回 list 页面并打开 Drawer
            navigate('/appCenter/questionAnswer', { state: { openDrawer: true } });
        } else {
            // 如果已经在第一步，直接返回
            navigate(-1);
        }
    };

    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            const data = {
                ...values,
                questionList: inputs.map(input => input.value),
                knowledge_info: JSON.stringify({
                    param_desc: values.param_desc,
                    show_recall_result: values.show_recall_result,
                    recall_method: values.recall_method,
                    rerank_status: true,
                    rerank_model_name: values.rerank_model_name,
                    slice_config_type: values.slice_config_type,
                    slice_count: values.slice_count,
                    is_multi_round: values.is_multi_round ? 'Y' : 'N',
                    multi_round: values.multi_round,
                    rerank_index_type_list: values.knowledge_ids?.map((id: string) => ({
                        index_type_id: 0,
                        knowledge_id: id,
                    })) || [],
                    recall_index_type_list: values.recall_method === 'embedding' || values.recall_method === 'mixed'
                        ? values.knowledge_ids?.map((id: string) => ({
                            index_type_id: 0,
                            knowledge_id: id,
                        })) || []
                        : [],
                }),
                userId,
                iconColor: previewBg,
                vipList,
            };

            let res;
            if (appId) {
                res = await apis.modifyTakaiApplicationApi(appId, data);
            } else {
                res = await apis.createTakaiApplicationApi(data);
            }

            if (res.data === 9) {
                message.error('没有配置审核人，请联系管理员');
            } else if (res.data === 1) {
                message.success('操作成功');
                navigate({ pathname: '/appCenter/questionAnswer' }, { replace: true });
            } else {
                message.error('操作失败');
            }
        } catch (error) {
            console.error('提交失败:', error);
        }
    };

    const handleSave = async () => {
        message.info('保存功能待实现');
    };

    if (pageLoading) {
        return (
            <div className='page-layout'>
                <div className="list-header with-back">
                    <div className="list-header-title">
                        <button className="back-btn" onClick={() => navigate(-1)} title="返回">
                            <LeftOutlined />
                        </button>
                        <h3>{appId ? '编辑 RAG 应用' : '创建 RAG 应用'}</h3>
                    </div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: 100 }}>
                    <Spin size="large" />
                </div>
            </div>
        );
    }

    return (
        <div className='page-layout'>
            <div className="list-header with-back">
                <div className="list-header-title">
                    <button className="back-btn" onClick={handleBack} title="返回">
                        <LeftOutlined />
                    </button>
                    <h3>{appId ? '编辑 RAG 应用' : '创建 RAG 应用'}</h3>
                </div>
            </div>

            {/* 步骤 1：使用 Drawer 式表单 */}
            <Step1Drawer
                open={step === 1}
                onClose={() => navigate(-1)}
                form={form}
                appTypeList={appTypeList}
                appVisibleList={appVisibleList}
                appProjectList={appProjectList}
                isAppPro={isAppPro}
                visibleFlag={visibleFlag}
                vipList={vipList}
                userInfo={userInfo}
                inputs={inputs}
                selectedIcon={selectedIcon}
                previewBg={previewBg}
                onAppChange={handleAppChange}
                onVisibleChange={handleVisibleChange}
                onRemoveVip={handleRemoveVip}
                onVipConfirm={handleVipConfirm}
                onNext={handleNext}
                onIconChange={setSelectedIcon}
                onBgColorChange={setPreviewBg}
                onInputsChange={setInputs}
            />
            
            {/* 步骤 2：RAG 参数配置 */}
            {step === 2 && (
                <Step2Config
                    form={form}
                        knowledgeList={knowledgeList}
                        modelList={modelList}
                        rerankModelList={rerankModelList}
                        topPValue={topPValue}
                        tempValue={tempValue}
                        isVisible={isVisible}
                        isVisibleCus={isVisibleCus}
                        isVisibleSlice={isVisibleSlice}
                        isDeepThinkVisible={isDeepThinkVisible}
                        isMultiRound={isMultiRound}
                        automatic={automatic}
                        name={name}
                        onTopPChange={setTopPValue}
                        onTempChange={setTempValue}
                        onModelChange={(value) => {
                            const list = rerankModelList.filter((item: any) => item.model === value);
                            form.setFieldValue('max_token', list[0]?.maxToken);
                            form.setFieldValue('rerank_model_name', list[0]?.bindingModel);
                        }}
                        onRecallMethodChange={() => {}}
                        onSliceCountChange={(value) => {
                            if (value === 'fixed') {
                                setIsVisibleSlice(true);
                            } else {
                                setIsVisibleSlice(false);
                            }
                        }}
                        onMultiRoundChange={setIsMultiRound}
                        onAutomaticChange={(checked) => {
                            setAutomatic(checked);
                            if (!checked) {
                                form.setFieldValue('param_desc', 'strict');
                                setTopPValue(0.5);
                                setTempValue(0.5);
                            }
                        }}
                        onBack={handleBack}
                        onSubmit={handleSubmit}
                        onSave={handleSave}
                        createFlag={createFlag}
                        appId={appId}
                    />
                )}
        </div>
    );
};

export default QuestionAnswerForm;
