// 嵌iframe、适配移动端
import { useEffect, useMemo, useState, useRef, useContext } from "react";
import { useLocation, useParams } from "react-router-dom";
import { getFlowApi, readOnlineFlows } from "../../../controllers/API/flow";
import { FlowType } from "../../../types/flow";
import { generateUUID } from "../../../utils";
import ChatPanneM from "./ChatPanneM";
import { useTranslation } from "react-i18next";
import { deleteChatApi, getChatsApi } from "../../../controllers/API";
import { captureAndAlertRequestErrorHoc } from "../../../controllers/request";
import { useDebounce, useTable } from "../../../util/hook";
import { TabsContext } from "../../../contexts/tabsContext";
import SkillTemps from "../../SkillPage/components/SkillTemps";
import titIconL from "../../../assets/chatM/tit-icon-l.png";
import titIconR from "../../../assets/chatM/tit-icon-r.png";

export default function chatShare() {
    const { id: flowId } = useParams()
    const location = useLocation();
    const searchParams = new URLSearchParams(location.search);
    const libId = searchParams.get('lib')
    const tweak = searchParams.get('tweak')
    const { t } = useTranslation();
    const [open, setOpen] = useState(false)
    // 对话列表
    const { chatList, chatsRef, addChat, deleteChat } = useChatList()
    const queryString = useMemo(() => {
        const params = [];

        if (libId) params.push(`knowledge_id=${libId}`);
        if (tweak) params.push(`tweak=${tweak}`);

        return params.length > 0 ? `&${params.join('&')}` : '';
    }, [libId, tweak])
    const chatIdRef = useRef('')
    const handlerSelectFlow = async (node: FlowType) => {
        // 会话ID
        chatIdRef.current = generateUUID(32)
        setOpen(false)
        // add list
        addChat({
            "flow_name": node.name,
            "flow_description": node.description,
            "flow_id": node.id,
            "chat_id": chatIdRef.current,
            "create_time": "-",
            "update_time": "-"
        })

        const flow = await getFlowApi(node.id)
        setFlow(flow)
        setChatId(chatIdRef.current)
        // setFace(false)
    }
    // 
    const { flow: initFlow } = useContext(TabsContext);
    const [flow, setFlow] = useState<FlowType>(null)
    const {
        data: onlineFlows,
        loading,
        search,
    } = useTable<FlowType>({}, (param) =>
        readOnlineFlows(param.page, param.keyword).then((res) => {
          return res;
        })
    );
    const [chatId, setChatId] = useState<string>('')
    console.log(flowId,libId,tweak)
    useEffect(() => {
        flowId && getFlowApi(flowId).then(node => {
            // 会话ID
            setFlow(node)
            setChatId(generateUUID(32))
        })
    }, [flowId])
  // select chat
  const handleSelectChat = useDebounce(async (chat) => {
    if (chat.chat_id === chatId) return

    const flow = initFlow?.id === chat.flow_id ? initFlow : await getFlowApi(chat.flow_id)

    // if (!flow) {
    //     setInputState({ lock: true, errorCode: '1004' })
    //     clearHistory()
    //     return setFace(false)
    // }

    setFlow(flow)
    setChatId(chat.chat_id)
}, 100, false)
    if (!flowId) return <div>请选择技能</div>

    return <div className="chatShareM">
        {/* <div className="chatShareM-tit">
            <img src={titIconL} alt=""/>
            <p>对话名称</p>
            <img src={titIconR} alt=""/>
        </div> */}
        {flow
            ? <div className="flex-1 chat-box h-screen relative">
                {flow && <ChatPanneM version='v2' queryString={queryString} chatId={chatId} flow={flow} />}
            </div>
            :<div className="flex-1 chat-box h-screen overflow-hidden relative">
                <p className="text-center mt-[100px] text-sm text-gray-600">{t('chat.selectChat')}</p>
            </div>}
    </div>
    // flow ? <ChatPanne version='v2' queryString={queryString} chatId={chatId} flow={flow} /> : null
};
/**
 * 本地对话列表
 */
const useChatList = () => {
    const [chatList, setChatList] = useState([])
    const chatsRef = useRef(null)

    useEffect(() => {
        getChatsApi().then(setChatList)
    }, [])

    return {
        chatList,
        chatsRef,
        addChat: (chat) => {
            const newList = [chat, ...chatList]
            // localStorage.setItem(ITEM_KEY, JSON.stringify(newList))
            setChatList(newList)
            setTimeout(() => {
                chatsRef.current.scrollTop = 1
            }, 0);
        },
        deleteChat: (id: string) => {
            // api
            captureAndAlertRequestErrorHoc(deleteChatApi(id).then(res => {
                setChatList(oldList => oldList.filter(item => item.chat_id !== id))
            }))
        }
    }
}