import { View, ScrollView, Text } from "@tarojs/components";
import Taro, { useDidShow, useRouter } from "@tarojs/taro";
import NavBarNormal from "@/components/NavBarNormal/index";
import PageCustom from "@/components/page-custom/index";
import { useEffect, useState } from "react";
import { isSuccess } from "@/utils";
import ChatRecordItem from "@/components/ChatRecordItem";
import { getVisitorInfo } from "@/service/visitor";
import { TSessionItem, TVisitorAgent } from "@/types/visitor";
import VisitorSummary from "./components/VisitorSummary";

import { getVisitorSessions } from "@/service/visitor";

import style from "./index.module.less";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import EmptyData, { EmptyDataSubInfo } from "@/components/EmptyData";

export default () => {
  const router = useRouter();
  const { visitorId } = router.params;
  const [visitor, setVisitor] = useState<TVisitorAgent>();
  const [totalCount, setTotalCount] = useState(0);

  if (!visitorId) {
    return <View>...</View>;
  }

  const fetchData = async () => {
    if (visitorId) {
      const response = await getVisitorInfo(visitorId);
      if (isSuccess(response.status)) {
        setVisitor(response.data);
      }
    }
  };

  const fetcher = async ([_url, { nextId, pageSize }]) => {
    const res = await getVisitorSessions({
      startId: nextId,
      pageSize,
      visitorId,
    });

    let _totalCount = res.data.totalCount;
    // 记录 totalCount
    if (_totalCount && _totalCount !== null) {
      setTotalCount(_totalCount);
    }
    return res.data;
  };

  const { list, loadMore } = useLoadMoreInfinite<TSessionItem[]>(
    createKey(`api/v1/my/visitor/sessions${visitorId}`, 5),
    fetcher
  );

  const newList = list.map((item: TSessionItem, itemIndex: number) => {
    let turns = totalCount - itemIndex;
    turns = turns <= 0 ? 1 : turns;
    return { ...item, visitTimes: turns };
  });

  const onScrollToLower = () => {
    loadMore();
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <PageCustom fullPage style={{ overflow: "hidden" }}>
      <NavBarNormal scrollFadeIn backText="访问详情"></NavBarNormal>
      {visitor ? <VisitorSummary data={visitor} /> : <></>}
      <View className="rounded-container-header">
        <View className="text-14 font-medium text-black font-pingfangSCMedium px-16 pb-14">
          访问记录
        </View>
      </View>
      <View className="flex-1 overflow-hidden w-full">
        <ScrollView
          scrollY
          onScrollToLower={onScrollToLower}
          style={{
            flex: 1,
            height: "100%", // 高度自适应
          }}
        >
          <View>
            <View className="flex flex-col gap-16 px-16 w-full pb-100">
              {newList.length <= 0 && (
                <EmptyData type="chat">
                  <EmptyDataSubInfo>
                    <View>当前暂无用户访问记录</View>
                    <View>你的智能体正在等待首次互动</View>
                  </EmptyDataSubInfo>
                </EmptyData>
              )}
              {newList.map((item) => {
                return (
                  <View className="w-full">
                    <View className="text-12 text-black leading-16">
                      {item?.msgTime.slice(0, 10)}
                    </View>
                    <View className="flex h-full w-full">
                      <View className="text-14 font-normal text-black leading-20 flex flex-col items-end">
                        <View className="text-14 leading-24">
                          {item?.msgTime.slice(10, 16)}{" "}
                        </View>
                      </View>
                      <View className="flex flex-1 w-full">
                        <View className={style.gutterLine}>
                          <View className={style.dot}></View>
                          <View className={style.line}></View>
                          <View className={style.dot}></View>
                        </View>
                        <View className="w-full h-full flex flex-col gap-8">
                          <View className="text-14 leading-24 text-title">
                            第{" "}
                            <Text className="text-primary text-16">
                              {item?.visitTimes}
                            </Text>{" "}
                            次访问你的智能体
                          </View>
                          <View className="text-12 text-gray-45">
                            访问时长： {item.chatSecondsDesc}
                          </View>
                          <View className="text-12 text-gray-45">
                            共进行了 {item.chatRoundCnt} 轮对话{" "}
                          </View>
                          <ChatRecordItem
                            sessionId={item.sessionId}
                            visitorId={visitorId}
                            showMoreButton
                          ></ChatRecordItem>
                        </View>
                      </View>
                    </View>
                  </View>
                );
              })}
            </View>
          </View>
        </ScrollView>
      </View>
    </PageCustom>
  );
};
