import { useState } from "react";
import { View } from "@tarojs/components";
import PageCustom from "@/components/page-custom/index";
import NavBarNormal from "@/components/NavBarNormal/index";

import KnowledgePicker from "@/components/KnowledgePicker";
import Taro, { useUnload } from "@tarojs/taro";
import { uploadImage } from "@/utils/http";
import { useComponentStore } from "@/store/componentStore";

import type { TMediaType } from "@/types/index";
import { EComponentType, EKnowlegeTypes } from "@/consts/enum";

import UploaderGrid from "@/components/UploaderGrid";
import BottomBar from "@/components/BottomBar";
import { TKnowledgeItem } from "@/types/knowledge";

interface Props {
  editMode?: boolean;
}

export default function Index({ editMode }: Props) {
  let currentComponent = useComponentStore((state) => state.currentComponent);

  const { saveComponent } = useComponentStore();
  const loading = useComponentStore((state) => state.loading);

  const [mediaValue, setMediaValue] = useState<TMediaType[]>(
    currentComponent?.data?.media ?? []
  );

  const handleSubmit = async () => {
    if (!currentComponent?.data?.id) {
      return;
    }
    if (loading) {
      return;
    }
    const c = {
      data: {
        media: mediaValue,
        layout: currentComponent.data.layout ?? "mini",
        id: currentComponent.data.id,
        index: currentComponent.data.index,
      },
      enabled: currentComponent?.enabled ?? true,
      type: EComponentType.media,
    };

    await saveComponent(c);
    Taro.navigateBack();
  };

  let isUploading = false;
  const handleChooseMedia = () => {
    Taro.chooseMedia({
      count: 9,
      mediaType: ["image", "video"],
      sourceType: ["album", "camera"],
      async success(res) {
        isUploading = true;
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFiles;
        const arr: TMediaType[] = [];
        for (let t of tempFilePaths) {
          Taro.showLoading();
          const res = await uploadImage(t.tempFilePath);
          Taro.hideLoading();
          if (res?.publicUrl) {
            arr.push({
              duration: t.duration,
              height: t.height,
              width: t.width,
              size: t.size,
              url: res.publicUrl,
              fileType: t.fileType,
            });
            console.log(arr);
          } else {
            Taro.showModal({
              title: "上传异常",
              content: "文件上传失败",
              showCancel: false,
            });
          }
        }
        setMediaValue([...mediaValue, ...arr]);
        isUploading = false;
      },
      fail(err) {
        console.log(err);
        isUploading = false;
      },
    });
  };

  const handleDeleteMedia = (index: number, current: TMediaType) => {
    const results = mediaValue.filter((item) => item.url !== current.url);
    setMediaValue([...results]);
  };
  const [showPopup, setShowPopup] = useState(false);

  const showKnowlegePopup = () => {
    setShowPopup(true);
  };

  const onPicked = (picked?: TKnowledgeItem[]) => {
    if (picked) {
      const r = picked.map((item) => {
        return {
          size: item.fileSize,
          // 如果是视频，则 url 是 ossPath
          url: item.picUrl || item.ossPath || '',
          fileType: item.type,
        };
      });
      if (r.length) {
        setMediaValue([...mediaValue, ...r]);
      }
    }
  };

  return (
    <PageCustom isflex={false} bgColor="global-light-green-bg">
      <NavBarNormal>图片/视频</NavBarNormal>

      <View className="flex flex-col w-full px-16 pt-12 gap-12">
        <View className="text-primary" onClick={showKnowlegePopup}>
          知识库导入
        </View>
        <UploaderGrid
          onNewUpload={handleChooseMedia}
          list={mediaValue}
          onChange={() => {}}
          onDelete={handleDeleteMedia}
        />
      </View>
      <KnowledgePicker
        title="知识库-图片/视频"
        types={[EKnowlegeTypes.image, EKnowlegeTypes.video]}
        multi
        onPicked={onPicked}
        setShow={setShowPopup}
        show={showPopup}
      ></KnowledgePicker>
      <BottomBar>
        <View
          className="button-rounded button-primary flex-1"
          onClick={handleSubmit}
        >
          保存
        </View>
      </BottomBar>
    </PageCustom>
  );
}
