import React, { useState, useEffect } from "react";
import { Alert } from "react-native";
import { WebView } from "react-native-webview";
import { get } from "../../utils/storeInfo";
import * as FileSystem from "expo-file-system";
import * as MediaLibrary from "expo-media-library";
import * as Linking from "expo-linking";
import * as Clipboard from "expo-clipboard";
import Toast from "react-native-toast-message";
import MyModal from "../../components/MyModal";
import baseRequest from "../../utils/baseRequest";

export default function WebWithHeader({ navigation, route }) {
  //设置页面标题
  useEffect(() => {
    navigation.setOptions({
      title: route.params?.title,
    });
  }, [navigation, route]);

  //前往打开权限弹窗
  const [overlayVisible, setOverlayVisible] = useState(false);

  //设置cookies
  const [cookies, setCookies] = useState();
  useEffect(() => {
    async function getCookies() {
      const base = await baseRequest();
      setCookies({
        b_mid: base.b_mid,
        b_did: base.b_did,
        b_ver: base.b_ver,
        b_dt: base.b_dt,
        b_model: base.b_model,
        b_nt: base.b_nt,
        b_token: base.b_token,
      });
    }
    getCookies();
  }, []);

  const setCookieScript = `
  document.cookie = "b_mid=${cookies?.b_mid} ;";
  document.cookie = "b_did=${cookies?.b_did} ;";
  document.cookie = "b_ver=${cookies?.b_ver} ;";
  document.cookie = "b_dt=${cookies?.b_dt} ;";
  document.cookie = "b_model=${cookies?.b_model} ;";
  document.cookie = "b_nt=${cookies?.b_nt} ;";
  document.cookie = "b_token=${cookies?.b_token} ;";
  true;
`;

  //请求相册访问权限并保存
  const saveImage = async (data) => {
    const permission = await MediaLibrary.requestPermissionsAsync();
    if (permission.granted) {
      const base64Code = data.split("data:image/png;base64,")[1];
      const filename = FileSystem.cacheDirectory + "poster.png";

      await FileSystem.writeAsStringAsync(filename, base64Code, {
        encoding: FileSystem.EncodingType.Base64,
      });

      await MediaLibrary.saveToLibraryAsync(filename);

      Toast.show({
        type: "success",
        text1: "已保存到相册",
        topOffset: 60,
      });
    } else {
      setOverlayVisible(true);
    }
  };

  //保存内容到剪贴板
  const copy = async (data) => {
    await Clipboard.setStringAsync(data);
    Toast.show({
      type: "success",
      text1: "已复制到剪贴板",
      topOffset: 60,
    });
  };

  //唤起支付宝
  const handleUrlRedirect = (event) => {
    const { url } = event;

    // 对alipays:相关的scheme处理
    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
      try {
        // 尝试启动支付宝客户端
        Linking.openURL(url).catch(() => {
          // 启动支付宝客户端失败，弹出提示安装对话框
          Alert.alert(
            "支付宝提醒",
            "未检测到支付宝客户端，请安装后重试。",
            [
              {
                text: "立即安装",
                onPress: () => {
                  const alipayUrl = "https://d.alipay.com";
                  Linking.openURL(alipayUrl);
                },
              },
              { text: "取消", style: "cancel" },
            ],
            { cancelable: false }
          );
        });
        return true; // 应用程序处理了该URL
      } catch (error) {
        // 启动支付宝客户端失败，继续加载URL
        console.error(error);
      }
    }

    // weixin:相关的scheme处理
    if (url.startsWith("weixin:")) {
      try {
        // 尝试启动支付宝客户端
        Linking.openURL(url).catch(() => {
          // 启动微信客户端失败，弹出提示安装对话框
          Alert.alert(
            "微信提醒",
            "未检测到微信客户端，请安装后重试。",
            [{ text: "确认", style: "cancel" }],
            { cancelable: false }
          );
        });
        return true; // 应用程序处理了该URL
      } catch (error) {
        // 启动微信客户端失败，继续加载URL
        console.error(error);
      }
    }

    // 处理其他URL
    return true;
  };

  return (
    <>
      <WebView
        incognito
        source={{
          uri: route.params.uri,
        }}
        userAgent="FromWebview"
        onMessage={async (event) => {
          const msg = JSON.parse(event.nativeEvent.data);
          if (msg.type === "SAVE_IMAGE") {
            saveImage(msg.data);
          } else if (msg.type === "COPY_URL") {
            copy(msg.data);
          } else if (msg.type === "NAVIGATE") {
            navigation.navigate(msg.data.page, { ...msg.data.params });
          }
        }}
        injectedJavaScript={setCookieScript}
        originWhitelist={[
          "https://*",
          "http://*",
          "alipays://*",
          "alipay://*",
          "weixin://*",
        ]}
        onShouldStartLoadWithRequest={handleUrlRedirect}
      />
      <MyModal
        visible={overlayVisible}
        setVisible={setOverlayVisible}
        title="您还未打开媒体权限"
        content="是否前往设置开启权限？"
        cancel={() => {
          setOverlayVisible(false);
        }}
        confirm={() => {
          Linking.openSettings();
          setOverlayVisible(false);
        }}
      />
    </>
  );
}
