/**
 * 知识库
 */

import { Text, View, Image, ScrollView } from "@tarojs/components";

import WemetaRadio from "@/components/WemetaRadio";

import Popup from "@/components/popup/popup";
import { useEffect, useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import { shareToEnts, getSharedEnts } from "@/service/knowledge";
import { useUserStore } from "@/store/userStore";
import { TEntItem } from "@/types/user";
import { isSuccess } from "@/utils";
import EmptyData, { EmptyDataSubInfo } from "@/components/EmptyData";
import BottomBar from "@/components/BottomBar";
import WemetaButton from "@/components/buttons/WemetaButton";



interface IProps {
  knowledgeId: string | number;
  showPopup: boolean;
  setShowPopup: (show: boolean) => void;
}

export default function Index({
  knowledgeId,
  showPopup,
  setShowPopup,
}: IProps) {
  const { entList, fetchMyEntList } = useUserStore();
  const [sharedEntIds, setSharedEntIds] = useState<string[]>([]);
  const [currentEnts, setCurrentEnts] = useState<TEntItem[]>([]);

  const parsedEntList = entList.map( item => {
    if(sharedEntIds.includes(item.entId as string)){
      return {...item, shared: true}
    }
    return {...item, shared: false}
  })

  const handleSwitchChange = async (ent: TEntItem & {shared: boolean}) => {
    if(ent.shared){
      return;
    }
    setCurrentEnts((prev) => {
      if(!prev?.find(item => item.entId === ent.entId)){
        return [...prev, ent]
      }
      return  prev.filter( item => item.entId !== ent.entId)
    })
  };

  const submit = async () => {
    if (!knowledgeId || !currentEnts.length) {
      return false;
    }
    console.log(currentEnts, '当前企业')
    const ents = currentEnts.map((item)=> item.entId).filter(item => item !== undefined)
    if(!ents.length){
      return
    }
    const response = await shareToEnts(knowledgeId, ents);
    if (isSuccess(response.status)) {
      if(!response.data.failEntIds.length){
        Taro.showToast({ title: "分享成功" });
        fetchSharedEnts()
        setShowPopup(false)
        setCurrentEnts([])
      }else{
        // todo 分开处理展示结果
        Taro.showToast({ title: "分享失败" });
      }

    }
  };

  const fetchData = ()=> {
    fetchMyEntList();
  }
  const fetchSharedEnts = async ()=> {
    const response = await getSharedEnts(knowledgeId)
    if(isSuccess(response.status)){
      setSharedEntIds(response.data.entIds)
    }
  }

  useDidShow(() => {
    fetchData()
  });

  useEffect(()=> {
    setCurrentEnts([])
    fetchSharedEnts()
  }, [knowledgeId])

  const renderContent = () => {
    if (!parsedEntList.length) {
      return (
        <View className="h-[320px]">
          <EmptyData type="box">
            <EmptyDataSubInfo>暂未加入任何企业</EmptyDataSubInfo>
            <View
              className="button-rounded button-primary-light button-border-primary button-inline-flex mt-20"
              onClick={() => Taro.navigateTo({ url: "/pages/contact-us/index" })}
            >
              联系我们
            </View>
          </EmptyData>
        </View>
      );
    }

    return (
      <View
        className="flex flex-col gap-12 pb-88"
        style={{ maxHeight: "66vh", overflow: "auto" }}
      >
        {parsedEntList.map((ent) => {
          return (
            <View
              className="flex items-center rounded-8 bg-gray-3 px-16 py-20"
              onClick={() => handleSwitchChange(ent)}
            >
              <View className="flex-1 text-black font-medium text-14 leading-22 font-pingfangSCMedium">
                {ent.entName}
              </View>
              <WemetaRadio
                checkbox
                disabled={ent.shared}
                checked={ent.shared || !!currentEnts.find((item)=> item.entId === ent.entId)}
              ></WemetaRadio>
            </View>
          );
        })}
      </View>
    );
  };

  return (
    <Popup setShow={setShowPopup} show={showPopup} title="共享至">
      <View className="text-gray-4 leading-20 mb-16 text-12">
        开启后，该组织下的所有成员都可引用。
      </View>

      {renderContent()}

      {(!!parsedEntList.length) ? <BottomBar>
        <WemetaButton className="flex-1" disabled={!currentEnts.length} onClick={submit}>
          确定
        </WemetaButton>
      </BottomBar> : <></>}
    </Popup>
  );
}
