import { BgLayer, BgType } from "../base/BgLayer";
import { BorderLayer } from "../base/BorderLayer";
import { BoxLayer } from "../base/BoxLayer";
import { Padding, Scene } from "../base/Scene";
import { loadImage } from "../base/utils";
import { AreaGroup, AreaGroups, Color, Settings } from "./common";
import {
  FillerConfig,
  FillerData,
  FillerResource,
  FillerCallback,
} from "./FillerData";
import { FillerScene } from "./FillerScene";
import { LineArtLayer } from "./LineArtLayer";
import { WorkLayer } from "./WorkLayer";

window.addEventListener("load", () => {
  function extractIdRegex(url: string) {
    const regex = /\/share\/([\w-]+)/;
    const match = url.match(regex);
    return match ? match[1] : null;
  }

  let currentUrl = window.location.href;
  console.log("current url:", currentUrl);
  let host = currentUrl.substring(0, currentUrl.indexOf("/share"));
  let id = extractIdRegex(currentUrl);
  console.log("host:", host);
  console.log("id:", id);

  // 从url参数中获取uuid
  const urlParams = new URLSearchParams(window.location.search);
  let uuid: string | null = urlParams.get("u") || urlParams.get("uuid"); // 尝试从 URL 参数中获取 UUID
  // if (!uuid) return;

  if (!id) id = "test";

  let zipUrl = `${host}/proxy/zips/v2/number_mini/1501/${id}.zip`;
  // let zipUrl = `http://localhost/66657ef03ba2da1daebcdd95.zip`;  // 本地跑docker nginx试试跨域
  if (host.includes("art.pcoloring.com")) {
    // 线上不走代理，直接请求pcoloring
    zipUrl = `https://pcoloring.com/zips/v2/number_mini/1501/${id}.zip`; // pcoloring.com 已经增加了art.pcoloring.com的跨域许可
    // zipUrl = `https://d2mb6s2cy1zg97.cloudfront.net/zips/v2/number_mini/1501${id}.zip`; // 直接访问cdn还不行
  }
  // console.log("zipUrl:", zipUrl);
  // init(`http://localhost:6889/proxy/zips/v2/number_mini/1501/6735bd3ab494234e4abc1db1.zip`);
  // init(`http://localhost:6889/proxy/zips/v2/number_mini/1501/${id}.zip`);
  init(id, uuid, zipUrl);
});

async function test() {
  let canvas = document.querySelector("#canvas") as HTMLCanvasElement;
  canvas.width = canvas.clientWidth * window.devicePixelRatio;
  canvas.height = canvas.clientHeight * window.devicePixelRatio;
  let resource = await loadResource();
  let ctx = canvas.getContext("2d")!;
  ctx.fillStyle = "red";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(resource.page, 0, 0);
}

async function init(id: string, uuid: string | null, zipUrl: string) {
  console.log(id, uuid, zipUrl);

  // 先从服务器获取tasklist，如果获取不到，后面的都没有意义，可以直接退出
  let taskList: number[] = [];
  if (uuid) {
    taskList = await fetchTasklistFromRemote(id, uuid);
  }

  let playButton = document.querySelector("#play-button") as HTMLDivElement;
  let canvas = document.querySelector("#canvas") as HTMLCanvasElement;
  let gl = canvas.getContext("webgl2", {
    premultipliedAlpha: false,
  }) as WebGL2RenderingContext;
  let pixelRatio = window.devicePixelRatio;

  canvas.width = canvas.clientWidth * pixelRatio;
  canvas.height = canvas.clientHeight * pixelRatio;
  let scene = new FillerScene(gl, pixelRatio, window, false);

  let resource = await loadResource();

  // 没有从服务器上获取到用户uuid对应的tasklist，那就用默认顺序
  if (!taskList || taskList.length <= 0) {
    taskList = [];
    for (let areaGroup of resource.config) {
      for (let area of areaGroup.areas) {
        taskList.push(area.id);
      }
    }
  }

  playButton.style.zIndex = "200";

  // 加载设置项，学个新语法 ...
  let settings: Settings = {
    hintStyle: "default",
    sound: true,
    vibrate: true,
    autoNext: true,
    ...JSON.parse(localStorage.getItem("settings") || "{}"),
  };

  let fillerData = new FillerData(
    new FillerConfig(settings),
    resource,
    gl,
    taskList,
  );

  scene.fillerData = fillerData;

  console.log("resource", resource);
  scene.setContentPadding(new Padding(0, 0, 0, 0));

  let width = fillerData.width;
  let height = fillerData.height;
  scene.setContentSize(width, height);

  if (resource.bg) {
    scene.addLayer(
      new BgLayer(scene, resource.bg, scene.width, scene.height, BgType.Repeat),
    );
  }
  scene.addLayer(new BoxLayer(scene, 0, 0, width, height));

  let workLayer = new WorkLayer(scene, fillerData);

  scene.addLayer(workLayer);

  scene.addLayer(new LineArtLayer(scene, resource.page, width, height));

  workLayer.initTask();

  playButton.addEventListener("click", () => onPlay(workLayer));

  // 直接自动播放，不用用户点击
  onPlay(workLayer);
}

async function fetchTasklistFromRemote(id: string, uuid: string) {
  let tasklist = null;
  const apiUrl: string = `/api/tasks?uuid=${uuid}&art=${id}`; // 您的后端 API 接口地址

  try {
    const response: Response = await fetch(apiUrl, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
      },
    });

    if (response.ok) {
      console.log("获取task数据成功:");
      tasklist = await response.json();
    } else {
      console.error("未获取到task数据");
    }

    return tasklist;
  } catch (error: any) {
    console.error("网络请求或服务器错误:", error);
  }
}

async function loadResource(): Promise<FillerResource> {
  let prefix = "/assets/res/6a18f7d9957ac783bad75479";

  let arr = [
    fetch(`${prefix}/config.json`).then((res) => res.json()),
    loadImage(`${prefix}/page.png`),
    loadImage(`${prefix}/map.png`),
    loadImage(`/assets/fonts/numbers_roboto_500.png`),
  ];

  let [config, page, map, numberImage, bgImage, special] =
    await Promise.all(arr);

  return new FillerResource(
    config as AreaGroups,
    page as HTMLImageElement,
    map as HTMLImageElement,
    numberImage as HTMLImageElement,
    [],
    special as HTMLImageElement,
    bgImage as HTMLImageElement,
  );
}

async function onPlay(workLayer: WorkLayer) {
  let img = document.getElementById("poster-img") as HTMLImageElement;
  img.style.zIndex = "0";
  let playButton = document.getElementById("play-button") as HTMLDivElement;
  playButton.style.zIndex = "0";

  await workLayer.replay();

  playButton.style.zIndex = "200";
}
