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

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

import { TCorrectionItem } from "@/types/correction";
import { getCorrectionList } from "@/service/correction";
import { useLoadMoreInfinite, createKey } from "@/utils/loadMoreInfinite";
import { deleteCorrection } from '@/service/correction'
import { useModalStore } from "@/store/modalStore";
import { isSuccess } from "@/utils";
import SliderAction from "@/components/SliderAction";

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}`, 10, [entId]),
    fetcher);  

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

  // useDidShow(()=> {
  //   mutate(undefined, { revalidate: true });
  // })
  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 createSliderButtons = (item: TCorrectionItem) => {
    return [
      {
        text: "删除",
        color: "#FF8200",
        onClick: () => {
          handleDeleteItem(item.id);
        },
      },
    ];
  };
  
  return (
    <View className="flex-1 h-full overflow-hidden">
    <ScrollView
      scrollY
      onScrollToUpper={onScrollToUpper}
      style={{
        flex: 1,
        height: "100%", // 高度自适应
      }}
    >
      <View className="flex flex-col gap-8 mx-16 pb-32">
        {list.map((item) => {
          return (
            <View className="rounded-12 overflow-hidden">
              <SliderAction actions={createSliderButtons(item)}>
                <View className="bg-white p-16" onClick={() => handleEdit(item.id)}>
                  <View className="text-14 leading-28 font-medium">{item.questions[0]}</View>
                </View>
              </SliderAction>
            </View>)
        })}
      </View>
    </ScrollView>
    </View>
  );
};

export default Index;
