/**
 * 知识库
 */

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


import WemetaSwitch from "@/components/WemetaSwitch";

import Popup from "@/components/popup/popup";
import { useEffect, useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import {
  shareToEnt,
} from "@/service/knowledge";
import { useUserStore } from "@/store/userStore";
import { TEntItem } from "@/types/user";
import { isSuccess } from "@/utils";


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

export default function Index({knowledgeId, showPopup, setShowPopup }:IProps) {

  const {entList, fetchMyEntList} = useUserStore()
  const [shareEntList, setShareEntList] = useState(entList ?? []);


  const handleSwitchChange = async (ent: TEntItem, checked: boolean)=> {
    if(!knowledgeId){
      return false;
    }
    const response = await shareToEnt({
      knowledgeIds: [knowledgeId],
      toEntId: ent.entId,
    })
    if(isSuccess(response.status)){
      Taro.showToast({title: checked ? '分享成功' : '取消分享成功'})
      setShareEntList((prev) => {
        if(checked){
          return [...prev, ent]
        }
        return  prev.filter( item => item.entId !== ent.entId)
      })
    }
  }

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

  const renderContent = ()=> {
    if(!entList.length){
      return <View className="rounded-8 bg-gray-3 py-20 text-center">
        <View className="leading-24 text-gray-4 font-medium text-14 mb-4">
          暂未加入任何企业
        </View>

        <View
          className="text-primary"
          onClick={() => {
            Taro.navigateTo({
              url: "/pages/contact-us/index",
            });
          }}
        >
          联系我们
        </View>
      </View>
    }

    return <View className="flex flex-col gap-12 pb-24" style={{maxHeight: '60vh', overflow: 'auto'}}>
      {entList.map(ent=> {
        return <View className="flex items-center rounded-8 bg-gray-3 px-16 py-24">
            <View className="flex-1 text-black font-medium text-14 leading-22">{ent.entName}</View>
            <WemetaSwitch
              checked={!!shareEntList.find((item)=> item.entId === ent.entId)}
              onChange={(checked) => handleSwitchChange(ent, checked)}
            ></WemetaSwitch>
        </View>
      })}
    </View>

  }


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

      {renderContent()}

    </Popup>
  );
}
