import PageCustom from "@/components/page-custom/index";
import { View, Image } from "@tarojs/components";
import { useEffect, useRef, useState } from "react";
import ComponentList from "@/components/component-list";

import NavBarNormal from "@/components/NavBarNormal/index";
import Taro, { getCurrentPages, useDidShow, useRouter } from "@tarojs/taro";
import { isSuccess } from "@/utils";

import IconArrowLeft from "@/components/icon/icon-arrow-left";
import IconHomeOutline from "@/components/icon/IconHomeOutline";
import AgentActionBar from "@/components/AgentPage/components/AgentActionBar";
import {
  getAgent,
} from "@/service/agent";
import style from "./index.module.less";
import {  DEFAULT_AVATAR_BG } from '@/config'
import { sceneUnzip } from "@/service/wechat";
import { postLog } from "./profile";
import { useIsLogin } from "@/xiaolanbenlib/hooks/data/useAuth";
import useSWR from "swr";
import { TAgentDetail } from "@/types/agent";

export default function Profile() {
  const [agentProfile, setAgentProfile] = useState<TAgentDetail|null>(null)
  // const { agentProfile, clearProfileAgent } = useAgentStore();
  const params = useRouter().params;
  const isLogin = useIsLogin();

  const [agentId, setCurrentAgentId]  = useState<null|string>(null)
  const [shareKey, setShareKey] = useState<null|string>(null)
  const [bg, setBg] = useState('')
  
  console.log(agentProfile, agentProfile?.status)

  const fetchAgentProfile = async (agentId: string, shareKey?:string) => {
    if(shareKey){
      shareKey = decodeURIComponent(shareKey)
    }
    const response = await getAgent(agentId, shareKey);
    const result = isSuccess(response.status)
    const agent = response.data
    if (result && agent) {
      agent.components = (agent.components ?? []).filter(item => item.enabled)
      setAgentProfile(agent)
    }
    return agent
  }

  const setPageBg = (_agent:TAgentDetail)=> {
    setBg(_agent?.avatarUrl ?? DEFAULT_AVATAR_BG)
  }

  // 定时 30 秒请求一次 log 接口
  useSWR( (agentId && (agentProfile?.status === 'normal')) ? ['/blue-aiagent/api/v1/agent/visitor/log', {
    agentId: agentId, 
    shareKey: shareKey,
    }] : false
    ,
    ([_url, data]) => {
      
      if(isLogin){
        postLog(data.agentId, data.shareKey ?? '')
      } 
    },
    {
      refreshInterval: 30000,
      revalidateOnFocus: false,
      shouldRetryOnError: false,
    }
  );

  // 解码
  const decodeSceneValue = async (sceneValue: string) => {
    const response = await sceneUnzip(sceneValue);
    if (isSuccess(response.status)) {
      try {
        const originalScene = JSON.parse(response.data.originalScene) as {
          shareKey?: string;
          agentId?: string;
        };
        if (originalScene.agentId) {
          console.log("originalScene:", originalScene);
          const _agent = await fetchAgentProfile(
            originalScene.agentId,
            originalScene.shareKey ?? ""
          );
          _agent && setPageBg(_agent)
          setCurrentAgentId(originalScene.agentId)
          setShareKey(originalScene.shareKey ?? "")
          
          // postLog(originalScene.agentId, originalScene.shareKey ?? "");
        }
      } catch (e) {
        Taro.showToast({
          title: "没有对应的知能体",
          icon: "error",
        });
      }
    }
  };
  console.log(params.scene, "场景值");


  const fetchPageData = async (params:any)=> {
    const _agent = await fetchAgentProfile(params.agentId, params.shareKey ?? "");
    _agent && setPageBg(_agent)
    setCurrentAgentId(params.agentId)
    setShareKey(params.shareKey ?? "")
  }
  
  useEffect(() => {
    // 通过小程序码识别打开的页面
    const scene = decodeURIComponent(params.scene ?? "");
    if (scene.length <= 32 && scene.length > 0) {
      // 有值，且小于 32 位，说明需要解码
      // 判断是否需要解压 shareKey
      decodeSceneValue(scene);
    }

    return ()=> {
      setCurrentAgentId(null)
      setShareKey(null)
    }
  }, []);



  // 正常分享出来的页面
  useEffect(() => {
    if (params.agentId) {
      fetchPageData(params)
    }
  }, [params.agentId]);

  const renderNavBarLeft = () => {
    const pages = getCurrentPages();
    console.log(pages, "当前页面");
    // 有后退页，则不显示 home 按钮

    if (pages.length > 1 && pages[0].route !== "pages/profile/index") {
      return (
        <View className={style.navButtons}>
          <View
            className="flex-center"
            onClick={() => {
              Taro.navigateBack();
            }}
          >
            <IconArrowLeft></IconArrowLeft>
          </View>
        </View>
      );
    }
    return (
      <View className={style.navButtons}>
        <View
          className="flex-center"
          onClick={() => {
            Taro.switchTab({
              url: "/pages/index/index",
            });
          }}
        >
          <IconHomeOutline></IconHomeOutline>
        </View>
      </View>
    );
  };

  const renderButton = ()=> {
    // 如果智能体交接了，则可以跳去新智能体
    if(agentProfile?.toAgentId){
      return <View className="button-rounded-big" onClick={()=> {
        Taro.redirectTo({
          url: `/pages/profile/index?agentId=${agentProfile?.toAgentId}`
        });
      }}>前往访问</View>
    }
    
    // 下线了
    return <View className="button-rounded-big" onClick={()=> {
      Taro.navigateBack()
    }}>知道了</View>
  }

   // 如果智能体被删除或其它异常情况
   if (agentProfile?.status === "deleted" || agentProfile?.deletedTip?.length) {
    return (
      <PageCustom fullPage>
        <View className="w-full h-full">
          <NavBarNormal leftColumn={renderNavBarLeft}></NavBarNormal>
        <View className="w-full h-full flex flex-col items-center justify-center">
          <View className="max-w-[280px]">
            <View className="mb-12">{agentProfile?.deletedTip}</View>
            {renderButton()}
          </View>
        </View>
      </View>
      </PageCustom>
    );
  }

  return (
    <PageCustom styleBg={bg}>
      <View className="w-full">
        <NavBarNormal blur scrollFadeIn scrollFadeInDelta={240}  leftColumn={renderNavBarLeft}></NavBarNormal>
        {agentProfile && <View className="blur-rounded-container">
          <AgentActionBar isVisitor agent={agentProfile}></AgentActionBar>
          <View className="flex flex-col w-full p-16 gap-12">
            <ComponentList
              components={agentProfile.components ?? []}
            ></ComponentList>
          </View>
        </View>}
      </View>
    </PageCustom>
  );
}
