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

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

import IconArrowLeft from "@/components/icon/icon-arrow-left";
import IconHomeOutline from "@/components/icon/IconHomeOutline";
import SummaryBar from "@/components/AgentPage/components/SummaryBar";
import { useAgentStore } from "@/store/agentStore";
import style from "./index.module.less";
import { sceneUnzip } from "@/service/wechat";
import { postLog } from "./profile";
import { useIsLogin } from "@/xiaolanbenlib/hooks/data/useAuth";

export default function Profile() {
  const { agentProfile, fetchAgentProfile, createAgent } = useAgentStore();
  const params = useRouter().params;
  const isLogin = useIsLogin();

  // 解码
  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);
          fetchAgentProfile(
            originalScene.agentId,
            originalScene.shareKey ?? ""
          );
          postLog(originalScene.agentId, originalScene.shareKey ?? "");
        }
      } catch (e) {
        Taro.showToast({
          title: "没有对应的知能体",
          icon: "error",
        });
      }
    }
  };
  console.log(params.scene, "场景值");
  // 通过小程序码识别打开的页面
  useEffect(() => {
    const scene = decodeURIComponent(params.scene ?? "");
    if (scene.length <= 32 && scene.length > 0) {
      // 有值，且小于 32 位，说明需要解码
      // 判断是否需要解压 shareKey
      decodeSceneValue(scene);
    }
  }, []);

  // 正常分享出来的页面
  useEffect(() => {
    if (params.agentId) {
      fetchAgentProfile(params.agentId, params.shareKey ?? "");
      isLogin && postLog(params.agentId, params.shareKey);
    }
  }, [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>
    );
    // return (
    // <View className={style.navButtons}>
    //   {pages.length > 1 && (
    //     <>
    //       <View
    //         className="flex-center"
    //         onClick={() => {
    //           Taro.navigateBack();
    //         }}
    //       >
    //         <IconArrowLeft></IconArrowLeft>
    //       </View>
    //       <View className={style.navGapLine}></View>
    //     </>
    //   )}

    //   <View
    //     className="flex-center"
    //     onClick={() => {
    //       Taro.switchTab({
    //         url: "/pages/index/index",
    //       });
    //     }}
    //   >
    //     <IconHomeOutline></IconHomeOutline>
    //   </View>
    // </View>
    // );
  };

  const handleCreate = async () => {
    try {
      const agentDetail = await createAgent();
      if (agentDetail) {
        if (agentDetail) {
          Taro.navigateTo({
            url: `/pages/agent/index?agentId=${agentDetail.agentId}`,
          });
        }
        // Taro.navigateTo({
        //   url: `/pages/agent/index?agentId=${agentDetail.agentId}`
        // })
      }
    } catch (e) {}
  };

  const renderButton = ()=> {
    // 如果智能体交接了，则可以跳去新智能体
    if(agentProfile?.toAgentId){
      return <View className="button-rounded-big" onClick={()=> {
        Taro.navigateTo({
          url: `/pages/profile/index?agentId=${agentProfile?.toAgentId}`
        });
      }}>前往访问</View>
    }
    // 下线了
    return <View className="button-rounded-big">知道了</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={agentProfile?.avatarUrl}>
      <View className="w-full">
        <NavBarNormal leftColumn={renderNavBarLeft}></NavBarNormal>
        {agentProfile && <View className="blur-rounded-container">
          <SummaryBar isVisitor agent={agentProfile}></SummaryBar>
          <View className="flex flex-col w-full p-16 gap-12">
            <ComponentList
              components={agentProfile.components ?? []}
            ></ComponentList>
          </View>
        </View>}
      </View>
    </PageCustom>
  );
}
