/**
 * 知识库
 */

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

import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";
import BottomBar from "@/components/BottomBar";
import FigureListItem from "@/components/list/FigureListItem";
import IconEye from "@/components/icon/IconEye";
import IconA from "@/components/icon/IconA";
import IconQ from "@/components/icon/IconQ";
import WemetaSwitch from "@/components/WemetaSwitch";
import KnowledgeIcon from "@/components/KnowledgeIcon";
import ShareToEntPopup from "./components/ShareToEntPopup";
import { useEffect, useState } from "react";
import CardEditable from "@/components/card/card-editable/index";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import {
  getMyKnowledgeDetail,
  getEntKnowledgeDetail,
  deleteKnowledgeQa,
  updateExactAnswer,
  deleteMyKnowledge,
} from "@/service/knowledge";
import { TKnowledgeDetail,TQAListItem } from "@/types/knowledge";
import { isSuccess } from "@/utils";
import { useModalStore } from "@/store/modalStore";
import style from "./index.module.less";

export default function Index() {
  const router = useRouter();
  const { knowledgeId, entId } = router.params;
  const [checked, setChecked] = useState(false);
  const [detail, setDetail] = useState<TKnowledgeDetail | null>(null);

  const isEnt = (entId !== undefined)
  const { showModal } = useModalStore();
  const [showPopup, setShowPopup] = useState(false);
  

  const handleEdit = (qaId: number | string) => {
    Taro.navigateTo({
      url: `/pages/editor-knowledge-item/index?knowledgeId=${knowledgeId}&qaId=${qaId}&knowledgeTitle=${detail?.title}`,
    });
  };
  
  const handleShare = async () => {
    setShowPopup(true)
  };
  
  // 删除问答项
  const handleDeleteItem = async (qaId: number | string) => {
    if (!detail) {
      return;
    }
    showModal({
      content: "确定删除该问答项吗？",
      onConfirm: async () => {
        const { status } = await deleteKnowledgeQa(detail.knowledgeId, qaId);
        if (isSuccess(status)) {
          Taro.showToast({ title: "删除成功", icon: "success" });
          getDetail(detail.knowledgeId);
        }
      },
    });
  };

  // 获取详情
  const getDetail = async (knowledgeId: number) => {
    const response =  !isEnt ? await getMyKnowledgeDetail(knowledgeId) : await getEntKnowledgeDetail(knowledgeId, entId);
    if (isSuccess(response.status) && response.data) {
      setDetail(response.data);
      setChecked(response.data.enableExactAnswer);
    }
  };

  // 开启/关闭 精准问答模式
  const handleEnableExactAnswer = async () => {
    if (!detail?.knowledgeId) {
      return;
    }
    const { status } = await updateExactAnswer(detail.knowledgeId, !checked);
    if (isSuccess(status)) {
      setChecked(!checked);
    }
  };

  const handleDeleteKnowledge = async () => {
    if (!detail) {
      return;
    }
    showModal({
      content: "确认删除文件及其全部知识？",
      onConfirm: async () => {
        const { status } = await deleteMyKnowledge(detail.knowledgeId);
        if (isSuccess(status)) {
          await Taro.showToast({ title: "删除成功", icon: "success" });
          setTimeout(() => {
            Taro.navigateBack();
          }, 2000);
        }
      },
    });
  };

  useDidShow(() => {
    knowledgeId && getDetail(parseInt(knowledgeId));
  });

  const createCardOptions = (item: TQAListItem) => {
    if(isEnt){
      return []
    }
    return [
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleDeleteItem(item.qaId)}>
        删除
      </View>,
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleEdit(item.qaId)}>编辑</View>,
    ]
  }

  return (
    <PageCustom>
      <NavBarNormal backText="知识库"></NavBarNormal>
      <View className="w-full overflow-hidden">
        <View className="p-16">
          <View className="mb-16">
            <FigureListItem
              figure={() => {
                return <KnowledgeIcon data={detail}/>
              }}
              rightRenderer={() => (
                !isEnt ? <View>
                  <IconEye />
                </View> : <></>
              )}
            >
              <View className="text-14 leading-22 truncate">
                {detail?.title}
              </View>
              <View className="text-12 leading-20 text-gray-45">
                {detail?.createTime} | {detail?.fileSizeStr}
              </View>
            </FigureListItem>
          </View>
          {!isEnt && <View className="flex rounded-12 p-16 gap-16 bg-white">
            <View className="flex-1">
              <View className="text-14 font-medium leading-22 text-black pb-2">
                精准QA模式
              </View>
              <View className="text-12 leading-20 text-gray-45">
                知识转问答，助力AI更高效作答
              </View>
            </View>

            <View className="flex-center">
              <WemetaSwitch
                checked={checked}
                onChange={handleEnableExactAnswer}
              ></WemetaSwitch>
            </View>
          </View>}
        </View>

        <View className="pb-100">
          <View className="rounded-container-header">
            <View className="text-14 font-medium leading-22 px-16 pb-16">
              问答列表共
              <Text className="text-primary">{detail?.qaList.length}</Text>条
            </View>
          </View>
          <View className={isEnt ? style.scrollContainerHigher : style.scrollContainer}>
            {detail?.qaList.map((item) => {
              return (
                <View className="flex flex-col gap-16 px-16 mb-16">
                  <CardEditable
                    buttons={createCardOptions(item)}
                  >
                    <View className="flex items-start mb-8 gap-8">
                      <View className="flex-center h-28">
                        <IconQ />
                      </View>
                      <View className="flex-1 font-medium text-14 leading-28">
                        {item.questions[0]}
                      </View>
                    </View>

                    <View className="flex items-start gap-8">
                      <View className="flex-center  h-28">
                        <IconA />
                      </View>
                      <View className="flex-1 text-12 leading-20 text-gray-45 truncate">
                        <View className="truncate">{item.answer}</View>

                        {!!item.links.length && (
                          <View className="pb-12">
                            {item.links.map((link) => {
                              return (
                                <View>
                                  查看链接 <Text>{link}</Text>
                                </View>
                              );
                            })}
                          </View>
                        )}
                        {!!item.pics.length && (
                          <View className="pb-12">
                            {item.pics.map((pic) => {
                              return (
                                <View>
                                  <Image
                                    src={pic}
                                    mode="widthFix"
                                    className="w-full"
                                  ></Image>
                                </View>
                              );
                            })}
                          </View>
                        )}
                      </View>
                    </View>
                  </CardEditable>
                </View>
              );
            })}
          </View>
        </View>
        {!isEnt && <BottomBar>
          <View
            className="button-rounded button-plain button-warn w-88"
            onClick={handleDeleteKnowledge}
          >
            删除
          </View>
          <View className="button-rounded button-primary flex-1" onClick={handleShare}>
            共享到企业知识
          </View>
        </BottomBar>}
        

        {(knowledgeId!== undefined) && <ShareToEntPopup knowledgeId={knowledgeId} setShowPopup={setShowPopup} showPopup={showPopup}/>}
        
      </View>
    </PageCustom>
  );
}
