totalgoal

 avatar
unknown
plain_text
17 days ago
10 kB
3
Indexable
import React, { useState, useEffect } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  Image,
  TouchableWithoutFeedback,
} from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import { useRouter } from "expo-router";
import { Icons } from "../../constants/Screen/Icons";
import ExtensionHome from "../../app/ExtensionHome/[extensionhome]";
import iconextension from "../../assets/images/four-extension.png";
import api from "../../constants/API";
import AsyncStorage from "@react-native-async-storage/async-storage";
import { Fonts } from "../../constants/Fonts";
import { Colors } from "../../constants/Colors";

export default function TotalSetGoalScreen() {
  const router = useRouter();
  const [goalList, setGoalList] = useState([]);
  const [goalStatusList, setGoalStatusList] = useState([]);
  const [lessonType, setLessonType] = useState([]);

  useEffect(() => {
    fetchSelectedClass();
    fetchGoalStatus();
    fetchLessonType();
  }, []);

  const fetchSelectedClass = async () => {
    try {
      const userId = await AsyncStorage.getItem("UserID");
      if (userId) {
        fetchSkills(userId); // Gọi API ngay khi lấy được lớp
      }
    } catch (error) {
      console.error("Error while getting class data:", error);
    }
  };

  const fetchSkills = async (classValue) => {
    try {
      const response = await api.get(/Goal/user/${classValue}, {
        timeout: 5000, // Thời gian chờ tối đa là 5 giây
        headers: {
          'Content-Type': 'application/json'
        }
      });
      setGoalList(response.data); // Giả sử API trả về một mảng kỹ năng
      console.log("API Response:", response); // In toàn bộ phản hồi API
      console.log("Response Data:", response.data); // In phần dữ liệu API trả về

    } catch (error) {
      console.error("Error while retrieving skill data:", error);
    }
  };

  const getStatusName = (statusID) => {
    const status = goalStatusList.find((s) => s.id === statusID);
    return status ? status.name : "chưa kích hoạt";
  }
  const getLessonTypeName = (LessonTypeID) => {
    const lessonname = lessonType.find((l) => l.id === LessonTypeID);
    return lessonname ? lessonname.name : "chưa kích hoạt";
  }

  const fetchGoalStatus = async () => {
    try {
      const response = await api.get(/GoalStatus, {
        timeout: 5000,
        headers: {
          "Content-Type": "application/json",
        },
      });
      setGoalStatusList(response.data);
    } catch (error) {
      console.error("Error while retrieving GoalStatus data:", error);
    }
  };
  const fetchLessonType = async () => {
    try {
      const response = await api.get(/LessonType/all, {
        timeout: 5000,
        headers: {
          "Content-Type": "application/json",
        },
      });
      setLessonType(response.data);
    } catch (error) {
      console.error("Error while retrieving LessonType data:", error);
    }
  };

  const calculateDays = (start, end) => {
    if (!start || !end) return "N/A"; // Kiểm tra nếu dữ liệu bị thiếu

    const startDate = new Date(start.split("T")[0]); // Lấy phần ngày
    const endDate = new Date(end.split("T")[0]);

    const difference = (endDate - startDate) / (1000 * 60 * 60 * 24); // Chia số mili-giây để ra số ngày

    return difference; // Trả về số ngày
  };
  const formatDate = (dateString) => {
    if (!dateString) return "N/A"; // Kiểm tra nếu không có dữ liệu

    const [year, month, day] = dateString.split("T")[0].split("-"); // Tách năm, tháng, ngày
    return ${day}-${month}-${year}; // Định dạng lại thành DD-MM-YYYY
  };

  //extension
  const [showExtension, setShowExtension] = useState(false);
  const [extensionPosition, setExtensionPosition] = useState({ x: 300, y: 30 });
  const [isDragging, setIsDragging] = useState(false);
  const [expandedItem, setExpandedItem] = useState(null);

  const handleTouchStart = () => setIsDragging(true);

  const handleTouchMove = (e) => {
    if (isDragging) {
      setExtensionPosition({
        x: e.nativeEvent.pageX,
        y: e.nativeEvent.pageY,
      });
    }
  };

  const handleTouchEnd = () => {
    setIsDragging(false);
    toggleExtension();
  };

  const toggleExtension = () => setShowExtension((prev) => !prev);
  const closeExtension = () => setShowExtension(false);
  const toggleExpand = (id) => {
    setExpandedItem(expandedItem === id ? null : id);
  };

  return (
    <LinearGradient colors={Colors.PRIMARY} style={styles.container}>
      {showExtension && (
        <TouchableWithoutFeedback onPress={closeExtension}>
          <View style={styles.overlay} />
        </TouchableWithoutFeedback>
      )}
      <View style={styles.header}>
        <TouchableOpacity
          style={styles.goBackButton}
          onPress={() => router.back()}
        >
          <Image source={Icons.back} style={styles.back} />
        </TouchableOpacity>
        <Text style={styles.title}>Tổng Hợp Mục Tiêu</Text>
        <View style={styles.extension}>
          {showExtension && (
            <ExtensionHome onClose={() => setShowExtension(false)} />
          )}
        </View>
        <View
          style={[
            styles.extensionhome,
            { left: extensionPosition.x, top: extensionPosition.y },
          ]}
          onStartShouldSetResponder={() => true}
          onResponderGrant={handleTouchStart}
          onResponderMove={handleTouchMove}
          onResponderRelease={handleTouchEnd}
        >
          <Image source={iconextension} style={styles.iconextension} />
        </View>
      </View>
      <FlatList
        data={goalList}
        renderItem={({ item }) => (
          <TouchableOpacity onPress={() => toggleExpand(item.id)}>
            <LinearGradient
              colors={
                item.statusID === 1
                  ? Colors.GREENN
                  : item.statusID === 2
                    ? Colors.RED
                    : Colors.WHITE
              }
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
              style={styles.lessonItem}
            >
              <View style={styles.containerItem}>
                <View style={styles.containerIcon}>
                  <Image
                    source={
                      item.statusID === 1
                        ? Icons.dung
                        : item.statusID === 2
                          ? Icons.sai
                          : Icons.setting
                    }
                    style={styles.Icon}
                  />
                </View>
                <View
                  colors={
                    item.statusID === 1 ? Colors.GREENN : Colors.RED
                  }
                >
                  <Text
                    style={[
                      styles.lessonTextItem,
                      {
                        color:
                          item.statusID === 1 ? "#000" : "#FFF",
                      },
                    ]}
                    onPress={()=> router.push("/Chapter/chapter")}
                  >
                    [Mục tiêu học tập]
                  </Text>
                  <Text
                    style={[
                      styles.timeText,
                      {
                        color:
                          item.statusID === 1 ? "#000" : "#FFF",
                      },
                    ]}
                  >
                    Thời gian: {calculateDays(item.dateStart, item.dateEnd)} ngày
                  </Text>
                  <Text
                    style={[
                      styles.lessonTextItems,
                      {
                        color:
                          item.statusID === 1 ? "#fff" : "#fbd54c",
                      },
                    ]}
                  >
                    Trạng thái: {getStatusName(item.statusID)}
                  </Text>
                  {expandedItem === item.id && (
                    <View style={styles.detailsContainer}>
                      <Text
                        style={[
                          styles.timeText,
                          {
                            color:
                              item.statusID === 1 ? "#000" : "#FFF",
                          },
                        ]}
                      >
                        Ngày bắt đầu: {formatDate(item.dateStart)}
                      </Text>
                      <Text
                        style={[
                          styles.timeText,
                          {
                            color:
                              item.statusID === 1 ? "#000" : "#FFF",
                          },
                        ]}
                      >
                        Ngày kết thúc: {formatDate(item.dateEnd)}
                      </Text>
                      <Text
                        style={[
                          styles.timeText,
                          {
                            color:
                              item.status === 1 ? "#000" : "#FFF",
                          },
                        ]}
                      >
                        Số lượng bài học: {item.numberLesson}
                      </Text>
                      <Text
                        style={[
                          styles.timeText,
                          {
                            color:
                              item.statusID === 1 ? "#000" : "#FFF",
                          },
                        ]}
                      >
                        Kỹ năng áp dụng: {getLessonTypeName(item.lessonTypeID)}
                      </Text>
                    </View>
                  )}
                </View>
              </View>
            </LinearGradient>
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.id}
      />
    </LinearGradient>
  );
}
Editor is loading...
Leave a Comment