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

import Taro, { useDidShow } from "@tarojs/taro";
import { useEffect, useRef, useState } from "react";

import { TCorrectionItem } from "@/types/correction";
import { getCorrectionList } from "@/service/correction";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";

import IconA from "@/components/icon/IconA";
import IconQ from "@/components/icon/IconQ";
import CardEditable from "@/components/card/card-editable/index";
import { deleteCorrection } from '@/service/correction'

import { useModalStore } from "@/store/modalStore";
import { isSuccess } from "@/utils";

export interface Iprops {
  entId?: number|string
  setTotalCount: (count: number) => void;
}
const Index = ({entId, setTotalCount}: Iprops) => {

  const { showModal } = useModalStore((state) => state.actions);

  const fetcher = async ([_url, {nextId, pageSize}, [_entId]]) => {
    const res = await getCorrectionList({ startId: nextId, pageSize, entId: _entId});
    return res.data;
  };


  const {data, list, loadMore, pageIndex, mutate } = useLoadMoreInfinite<TCorrectionItem[]>(
    createKey(`api/v1/my/correction/list${entId}`, 20, [entId]),
    fetcher);

  const onScrollToUpper = async () => {
    console.log('toUpper')
    loadMore()
  }



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

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

  useEffect(() => {
    if(data &&  pageIndex === 1) {
      setTotalCount(data?.[0].totalCount || 0)
    }
  }, [data, pageIndex]);


  const handleEdit = (id: number|string) => {
    Taro.navigateTo({
      url: `/pages/editor-correction-item/index?correctionId=${id}`,
    });
  };

  // 删除问答项
  const handleDeleteItem = async (id: number|string) => {

    showModal({
      content: "确定删除吗？",
      onConfirm: async () => {
        const { status } = await deleteCorrection(id);
        if (isSuccess(status)) {
          Taro.showToast({ title: "删除成功", icon: "success" });
          mutate()
        }
      },
    });
  };


  const createCardOptions = (item: TCorrectionItem) => {
    return [
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleDeleteItem(item.id)}>
        删除
      </View>,
      <View className="flex-1 w-full h-full py-12 flex-center" onClick={() => handleEdit(item.id)}>编辑</View>,
    ]
  }
  return (
    <View className="flex-1 h-full overflow-hidden">
    <ScrollView
      scrollY
      onScrollToUpper={onScrollToUpper}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      <View className="mx-16 pb-32">
      {list.map((item) => {
        return (
          <View className="flex flex-col gap-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-4 truncate">
                  <View className="truncate">{item.answer}</View>

                  {!!item.links.length && (
                    <View className="pb-12 truncate">
                      {item.links.map((link) => {
                        return (
                          <View className="truncate">
                            链接: <Text className="truncate">{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>
    </ScrollView>
    </View>
  );
};

export default Index;
