import { View, Text, } from "@tarojs/components";
import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";
import NavBarNormal from "@/components/NavBarNormal/index";
import PageTitle from '@/components/PageTitle'
import PageCustom from "@/components/page-custom/index";
import IconArrowDownRounded from '@/components/icon/IconArrowDownRounded';
import DataCard from './components/DataCard'
import VisitorList from "./components/VisitorList";
import  AgentList from "./components/AgentList";
import { useEffect, useState } from "react";
import { useAgentStore, useAgentStoreActions } from "@/store/agentStore";
import { getVisitorSummary, type TVisitorSummary } from '@/service/visitor'
import { isSuccess } from "@/utils";
import { TAgent } from "@/types/agent";
// import eventBus, {BUS_EVENTS} from '@/utils/EventBus'
import { TVisitorAgent } from "@/types/visitor";
import { getVisitorList } from "@/service/visitor";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import CheckLoginPopup from '@/components/CheckLoginPopup'
import BlurContainer from '@/components/BlurContainer'

export default () => {

  const agents = useAgentStore((state) => state.agents);
  const { fetchAgents } = useAgentStoreActions();

  const [show, setShow] = useState(false);

  // 是否显示选择器
  const [currentAgent, setCurrentAgent] = useState<TAgent|null>(null)
  const [summary, setSummary] = useState<TVisitorSummary>()

  const fetcher = async ([_url, {nextId, pageSize}, [agentId]]) => {
    const res = await getVisitorList({ startId: nextId, pageSize, agentId});
    return res.data;
  };
  const { list, loadMore, mutate } = useLoadMoreInfinite<TVisitorAgent[]>(
    createKey(`getVisitorList ${currentAgent?.agentId}`, 20, [currentAgent?.agentId]),
    fetcher, {
      revalidateOnMount: false
    });


  // 统计数据
  const fetchSummary = async () => {
    const response = await getVisitorSummary(currentAgent?.agentId)
    if(isSuccess(response.status)){
      setSummary(response.data)
    }
  }

  const fetchInitData = async () => {
    await fetchAgents();
  }

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

  useEffect(() => {
    fetchSummary()
    mutate()
  }, [currentAgent])

  useDidShow(()=> {
    mutate()
  })


  // 登录完成后
  const onLoginEnd = ()=> {
    fetchInitData()
    fetchSummary()
    mutate()
  }



  useReachBottom(() => {
    loadMore()
  })

  const unprocessedDislikeCnt = summary?.unprocessedDislikeCnt ?? 0

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

  return (
    <PageCustom>
      <NavBarNormal scrollFadeIn leftColumn={()=> <PageTitle>数据分析</PageTitle>}>
      </NavBarNormal>
      <View className="w-full pt-8 px-16 pb-16">
        <View className="flex items-center gap-8 mb-16">
          <View className="bg-white rounded-12 py-12 px-16" onClick={()=> setCurrentAgent(null)}>
            <View className={`${currentAgent?.agentId ? 'text-black' : 'text-gray-4' }`}>全部</View>
          </View>
          <View className="flex flex-1 items-center gap-2 bg-white rounded-12 p-12 truncate" onClick={()=> setShow(true)}>
              <View className="flex-1 text-14 leading-22 truncate">
                {currentAgent ? <View className="text-black truncate">{currentAgent?.name}</View> : <View className="text-gray-4">请选择智能体</View> }
              </View>

              <View className="flex-center">
                <IconArrowDownRounded/>
              </View>
            </View>
        </View>

        <View className="grid grid-cols-2 gap-8 bg-white rounded-12 p-12 mb-12">
          <DataCard text="今日访问次数" unitText="次" value={summary?.todayPv ?? 0} />
          <DataCard text="今日对话人数" unitText="人" value={summary?.todayChatUv ?? 0} />
          <DataCard text="累计访问次数" unitText="次" value={summary?.sumPv ?? 0} />
          <DataCard text="累计对话人数" unitText="人" value={summary?.sumChatUv ?? 0} />
          <DataCard text="好评" unitText="条" value={summary?.unreadLikeCnt ?? 0} />
          <DataCard onClick={()=> {
            if(unprocessedDislikeCnt <= 0) {
              return;
            }
            const query = currentAgent?.agentId ? `agentId=${currentAgent.agentId}` : ''
            Taro.navigateTo({
              url: `/pages/dislike-messages/index?${query}`
            })

          }} text="待处理差评" unitText="条" value={unprocessedDislikeCnt} arrow />
        </View>

        <AgentList show={show} setShow={setShow} currentAgent={currentAgent} setCurrentAgent={setCurrentAgent}></AgentList>

        <CheckLoginPopup onEnd={onLoginEnd}></CheckLoginPopup>
      </View>
      <BlurContainer>
        <VisitorList list={list} agentId={currentAgent?.agentId}></VisitorList>
      </BlurContainer>
    </PageCustom>
  );
};
