import { NavBar } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import { ArrowLeft } from "@nutui/icons-react-taro";
import { getStorageSync, navigateBack } from "@tarojs/taro";
import {
  getVipCustomersGiftListApi,
  receiveVipCustomersGiftApi,
} from "../../api/gift";
import { useEffect, useState } from "react";

const Gift = () => {
  const [giftList, setGiftList] = useState([]);

  const getGiftList = async () => {
    // 圈子id 从本地存储中获取
    const mainId = getStorageSync("vipInfo").game_id;
    if (!mainId) {
      return;
    }

    const res: any = await getVipCustomersGiftListApi({ main_id: mainId });
    if (res.code === 200) {
      setGiftList(res.data);
    }
  };

  const getGift = async (item) => {
    const res: any = await receiveVipCustomersGiftApi(item);
    if (res.code === 200) {
      const data = [...giftList];
      data.forEach((ite: any) => {
        if (ite.id === item.id) {
          ite.is_received = true;
        }
      });
      setGiftList(data);
    }
  };

  useEffect(() => {
    getGiftList();
  }, []);
  return (
    <View>
      <NavBar
        back={
          <>
            <ArrowLeft />
            返回
          </>
        }
        fixed
        onBackClick={(e) => {
          e.preventDefault();
          navigateBack({ delta: 1 });
        }}
      >
        礼包中心
      </NavBar>
      <View className="pt-[60px]">
        {giftList.map((item: any) => (
          <View className="flex items-center justify-between px-[10px] border-b-[1px] border-[#f2f2f2] pb-[10px]">
            <View className="text-[14px]">
              <View>{item.gift_name}</View>
              <View className="text-[12px] text-[#999]">{item.gift_desc}</View>
            </View>

            <View
              className={`font-[800] text-center py-[4px] w-[60px] rounded-[10px] text-[14px] ${
                item.is_received
                  ? "text-[#999] bg-[#f2f2f2]"
                  : "text-[#fff] bg-[#5c64ac]"
              }`}
              onClick={() => {
                if (item.is_received) {
                  return;
                }
                getGift(item);
              }}
            >
              {item.is_received ? "已领取" : "领取"}
            </View>
          </View>
        ))}
      </View>
    </View>
  );
};

export default Gift;
