// @ts-ignore
/* eslint-disable */
import Taro, { getCurrentInstance, useReady } from "@tarojs/taro";
import { Button, Camera, Canvas, Image, View } from "@tarojs/components";
import { useState } from "react";
import { ocrAction } from "@/utils";
import ScanCode_FlashClose from "../../../resources/ScanCode_FlashClose@3x.png";
import ScanCode_Flash from "../../../resources/ScanCode_Flash@3x.png";
import ScanCode_Frame from "../../../resources/ScanCode_Frame.png";
import ScanCode_Close from "../../../resources/ScanCode_Close@3x.png";
import ScanCode_Cam from "../../../resources/ScanCode_Cam@3x.png";
import ScanCode_Pic from "../../../resources/ScanCode_Pic@3x.png";

interface ScanParams {
  type: "idcard" | "bankcard";
}

// 选择图片函数
const chooseImage = async () => {
  return new Promise((resolve, reject) => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album"],
      success: (res) => {
        resolve(res.tempFilePaths[0]);
      },
      fail: (res) => {
        reject(new Error(`选择图片失败: ${res.errMsg}`));
      },
    });
  });
};

export default function Page() {
  const instance = getCurrentInstance();
  const params = instance?.router?.params as unknown as ScanParams;

  const [data, setData] = useState({
    skipphotoStatus: "0",
    flash: false,
    bottom: 125,
    windowWidth: 300,
    touchPadding: 36,
    windowHeight: 200,
    isShowImage: true,
    showCamera: false,
    path: "",
    cameraAuth: true,
    top: 386,
    left: 24,
    width: 666,
    height: 464,
    globalStatusBarHeight: 0,
    globalIos: false,
    image: "",
    scanType: "idcard",
  });

  useReady(() => {
    if (params.type === "idcard") {
      Taro.setNavigationBarTitle({
        title: "身份证识别",
      });
    }
    if (params.type === "bankcard") {
      Taro.setNavigationBarTitle({
        title: "银行卡识别",
      });
    }

    initData();
  });

  const showTool = () => {
    setData((prev) => ({ ...prev, showCamera: true }));
  };

  const error = (e) => {
    console.log("camera加载失败");
    setData((prev) => ({ ...prev, cameraAuth: false }));
  };

  const handleSetting = (e) => {
    if (!e.detail.authSetting["scope.camera"]) {
      Taro.showModal({
        title: "",
        content: "若不打开授权，则无法拍照！",
        showCancel: false,
      });
    } else {
      setData((prev) => ({ ...prev, cameraAuth: true }));
    }
  };

  const initData = () => {
    Taro.getSystemInfo({
      success: (res) => {
        let rate = res.windowHeight < 800 ? (res.windowHeight - 110) / 698 : 1;
        let bottom = data.bottom * rate;
        let globalStatusBarHeight = res.statusBarHeight
          ? res.statusBarHeight * 2
          : 0;
        let top = data.top + globalStatusBarHeight;
        let temp = (top - globalStatusBarHeight) * rate - 88 - 48 - 60;
        if (temp < 20) {
          top = (60 + 20 + 88 + 48) / rate + globalStatusBarHeight;
          bottom = bottom - (20 - temp) * rate;
        }
        setData((prev) => ({
          ...prev,
          globalStatusBarHeight: globalStatusBarHeight,
          globalIos: true,
          bottom: bottom,
          touchPadding: data.touchPadding * rate,
          top: top * rate,
          height: ((data.height * rate) / 4) * 4,
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight,
        }));
      },
    });
  };

  const changeFlash = () => {
    setData((prev) => ({ ...prev, flash: !prev.flash }));
  };

  const goPre = () => {
    Taro.navigateBack({
      delta: 1,
    });
  };

  const chooseImg = async (e) => {
    try {
      const imagePath = await chooseImage();
      const result = await ocrAction(imagePath, params.type);

      console.log("result", result);
      Taro.eventCenter.trigger("ocr", {
        result: result,
      });

      Taro.navigateBack({
        delta: 1,
      });
    } catch (e) {
      console.error(e);
      console.error("因为没有真的上传图片，所以走到出错的逻辑里了");
      Taro.showToast({
        title: "出错啦...",
        icon: "error",
      });
    }
  };

  const takePhotoAction = (e) => {
    setData((prev) => ({ ...prev, isShowImage: true }));
    const ctx = Taro.createCameraContext();
    ctx.takePhoto({
      quality: "high",
      success: (res) => {
        loadTempImagePath(res.tempImagePath);
      },
    });
  };

  const loadTempImagePath = (filePath) => {
    let { windowWidth, windowHeight } = data;
    let rate = windowWidth / 375;
    let image_x = (data.left / 2) * rate;
    let image_y = (data.top / 2) * rate;
    let image_width = (375 - (2 * data.left) / 2) * rate;
    let image_height = (data.height / 2) * rate;

    console.log("filePath", filePath);

    Taro.getImageInfo({
      src: filePath,
      success: (res) => {
        const canvas = Taro.createCanvasContext("image-canvas");
        canvas.drawImage(filePath, 0, 0, windowWidth, windowHeight);
        Taro.showLoading({
          title: "数据处理中...",
          icon: "loading",
          duration: 10000,
        });

        canvas.setStrokeStyle("rgba(0, 0, 0, 0)");
        canvas.strokeRect(image_x, image_y, image_width, image_height);
        canvas.draw();

        setTimeout(function () {
          Taro.canvasToTempFilePath({
            canvasId: "image-canvas",
            x: image_x,
            y: image_y,
            width: image_width,
            height: image_height,
            destWidth: image_width,
            destHeight: image_height,
            success: function (res) {
              setData((prev) => ({
                ...prev,
                image: res.tempFilePath,
                isShowImage: false,
              }));
              Taro.hideLoading();
              console.log("res.tempFilePath", res.tempFilePath);
              ocrAction(res.tempFilePath, params.type)
                .then((result) => {
                  console.log("result", result);
                  Taro.eventCenter.trigger("ocr", {
                    result: result,
                  });

                  Taro.navigateBack({
                    delta: 1,
                  });
                })
                .catch((e) => {
                  setData((prev) => ({ ...prev, isShowImage: true }));
                  console.error("因为没有真的上传图片，所以走到出错的逻辑里了");
                  Taro.showToast({
                    title: "出错啦...",
                    icon: "loading",
                  });
                });
            },
            fail: function (e) {
              Taro.showToast({
                title: "出错啦...",
                icon: "loading",
              });
            },
          });
        }, 1000);
      },
    });
  };

  return (
    <View className="relative h-screen w-full">
      {/* 背景遮罩 */}
      {data.isShowImage && (
        <Canvas
          className={"absolute h-screen w-full"}
          canvasId="image-canvas"
          devicePosition={"back"}
          resolution={"high"}
        />
      )}

      {data.cameraAuth ? (
        <Camera
          flash={data.flash ? "on" : "off"}
          onInitDone={showTool}
          mode="normal"
          devicePosition="back"
          onError={error}
          className="fixed top-0 h-screen w-full"
        >
          {data.showCamera && (
            <View className="flex h-screen flex-col">
              {/* 顶部区域 */}
              <View style={{ height: `${data.top}rpx` }}>
                <View style={{ height: `${data.top}rpx` }} className="header">
                  <View
                    style={{ paddingTop: `${data.globalStatusBarHeight}rpx` }}
                    className="title h-22 text-center text-xl leading-10 text-white"
                  >
                    {data.title}
                  </View>

                  {data.flash ? (
                    <Image
                      className="mt-8 ml-6 h-6 w-6"
                      src={ScanCode_FlashClose}
                      onClick={changeFlash}
                    />
                  ) : (
                    <Image
                      className="mt-8 ml-6 h-6 w-6"
                      src={ScanCode_Flash}
                      onClick={changeFlash}
                    />
                  )}
                </View>
              </View>

              {/* 中间区域 */}
              <View className="flex">
                <View
                  style={{ height: `${data.height}rpx` }}
                  className="flex flex-1 flex-wrap content-between"
                >
                  <View className="column flex w-full justify-between">
                    <Image className="h-4 w-4" src={ScanCode_Frame} />
                    <Image
                      style={{ transform: "rotate(90deg)" }}
                      className="h-4 w-4"
                      src={ScanCode_Frame}
                    />
                  </View>
                  <View className="bottom-column flex w-full items-end justify-between">
                    <Image
                      style={{ transform: "rotate(270deg)" }}
                      className="h-4 w-4"
                      src={ScanCode_Frame}
                    />
                    <Image
                      style={{ transform: "rotate(180deg)" }}
                      className="h-4 w-4"
                      src={ScanCode_Frame}
                    />
                  </View>
                </View>

                <View style={{ flex: `0 0 ${data.left}px`, order: -1 }} />
                <View style={{ flex: `0 0 ${data.left}px` }} />
              </View>

              {/* 底部区域 */}
              <View className="flex flex-1 flex-col">
                <View className="pt-4 text-center text-sm leading-5 text-white opacity-50">
                  拍摄要求：清晰完整，避免缺边、模糊、反光。
                </View>
                <View className="flex h-32 w-full flex-1 flex-col items-center justify-end">
                  <View className="flex h-18 w-full flex-row items-center">
                    <Image
                      onClick={goPre}
                      className="ml-16 h-8 w-8"
                      src={ScanCode_Close}
                    />
                    <Image
                      onClick={takePhotoAction}
                      className="mx-auto h-18 w-18"
                      src={ScanCode_Cam}
                    />
                    <Image
                      onClick={chooseImg}
                      className="mr-16 h-8 w-8"
                      src={ScanCode_Pic}
                    />
                  </View>
                  <View
                    style={{ height: `${data.bottom}px` }}
                    className="w-full"
                  />
                </View>
              </View>
            </View>
          )}
        </Camera>
      ) : (
        <View className="fixed top-0 h-screen w-full bg-gray-500">
          <View className="flex h-screen flex-col">
            {/* 布局结构保持不变 */}
            <View style={{ height: `${data.top}rpx` }} />
            <View className="flex">
              <View
                style={{ height: `${data.height}rpx` }}
                className="flex-1"
              />
              <View style={{ flex: `0 0 ${data.left}px` }} />
              <View style={{ flex: `0 0 ${data.left}px` }} />
            </View>
            <View />
          </View>

          <View className="fixed top-0 flex h-screen flex-col">
            <View style={{ height: `${data.top}rpx` }} className="header">
              <View
                style={{ paddingTop: `${data.globalStatusBarHeight}rpx` }}
                className="title h-22 text-center text-xl leading-20 text-white"
              >
                {data.title}
              </View>
            </View>

            <View className="flex flex-1 items-center justify-center">
              <View className="relative -top-11 text-center text-sm text-white">
                暂无权限访问摄像头，请点击下方按钮设置权限
              </View>
            </View>

            <View className="relative -top-6 w-full text-center">
              <Button
                type="primary"
                className="w-24"
                openType="openSetting"
                onOpenSetting={handleSetting}
              >
                设置
              </Button>
            </View>

            <View>
              <View className="flex h-32 w-full flex-1 flex-col items-center justify-end">
                <View className="flex h-18 w-full flex-row items-center">
                  <Image
                    onClick={goPre}
                    className="ml-16 h-8 w-8"
                    src={ScanCode_Close}
                  />
                  <Image
                    onClick={takePhotoAction}
                    className="mx-auto h-18 w-18"
                    src={ScanCode_Cam}
                  />
                  <Image
                    onClick={chooseImg}
                    className="mr-16 h-8 w-8"
                    src={ScanCode_Pic}
                  />
                </View>
                <View
                  style={{ height: `${data.bottom}px` }}
                  className="w-full"
                />
              </View>
            </View>
          </View>
        </View>
      )}

      {/* 显示图片的覆盖层 */}
      {!data.isShowImage && data.image && (
        <View className="fixed top-0 h-screen w-full bg-black">
          <View className="flex h-screen flex-col">
            <View style={{ height: `${data.top}rpx` }} />
            <View className="flex">
              <View style={{ height: `${data.height}rpx` }} className="flex-1">
                <Image className="h-full w-full" src={data.image} />
              </View>
              <View style={{ flex: `0 0 ${data.left}px`, order: -1 }} />
              <View style={{ flex: `0 0 ${data.left}px` }} />
            </View>
            <View />
          </View>
        </View>
      )}
    </View>
  );
}
