import { MatController } from "@/controller/MatController";
import { MatchModule } from "@/modules/match";
import { QueditorModule } from "@queenjs-modules/queditor";
import { switchSceneProdComp } from "@queenjs-modules/queditor/module/controls/Queen3dCtrl/actions/geom";
import { PackMat } from "@queenjs-modules/queditor/objects";
import { queenApi } from "queenjs";

export default function createController(
  match: MatchModule,
  queditor: QueditorModule
) {
  const ctrl = new MatController();

  const switchComp = (compName = "") => {
    switchSceneProdComp.call(
      queditor.controls.queen3dCtrl,
      queditor.store.pack.scenes[0].products[0].id,
      compName
    );
  };

  function findCompDef(product: any, compName = "") {
    return product.components.find((c: any) => c.name == compName);
  }

  function renderGroupMat(matsGroup: MatsMatchComp, isCreate = true) {
    const targetPro = queditor.helper.findProductDef(matsGroup.productId);
    if (!targetPro) return;
    const targetCom = findCompDef(targetPro, matsGroup.name);
    if (!targetCom) return;

    const mat = queditor.helper.findMatDef(matsGroup.matIds[matsGroup.index]);
    if (!mat) return;
    queditor.actions.updatePackProductCompMat(targetCom, mat, isCreate);
  }

  function clearCompMat(matsGroup: MatsMatchComp) {
    const targetPro = queditor.helper.findProductDef(matsGroup.productId);
    if (!targetPro) return;
    const targetCom = findCompDef(targetPro, matsGroup.name);
    if (!targetCom) return;
    queditor.actions.updatePackProductCompMat(targetCom, PackMat.create());
  }

  ctrl.matItemAction = (
    key: string,
    matsGroup: MatsMatchComp,
    index: number,
    currentMats: PackMat
  ) => {
    switch (key) {
      case "delete":
        match.actions.deleteGroupMat(matsGroup, index);
        break;
      case "rename":
        ctrl.renameGroupMat(currentMats);
        break;
    }
  };

  ctrl.matGroupAction = (key: string, matsGroup: MatsMatchComp) => {
    switch (key) {
      case "rename":
        ctrl.renameMatGroup(matsGroup);
        break;
      case "lock":
        ctrl.lockMatGroup();
        break;
      case "clear":
        ctrl.clearMatGroup(matsGroup);
        // removePackMat? 是否删除面料列表数据
        switchComp(matsGroup.name);
        clearCompMat(matsGroup);
        break;
    }
  };

  ctrl.switchGroupMatIndex = (matsGroup: any, index: number) => {
    matsGroup.index = index;
    renderGroupMat(matsGroup, false);
  };

  ctrl.saveMatch = () => {
    match.store.designDetail.scenePack.source = queditor.store.pack;
    match.actions.saveDesign();
  };

  ctrl.findMatById = (matId: string) => {
    const mats = queditor.store.pack.mats;
    return mats?.find((element) => element.id == matId);
  };

  ctrl.findProductById = (productId: string) => {
    const products = queditor.store.pack.products;
    return products?.find((element) => element.id == productId);
  };

  ctrl.isGroupActive = (matsGroup: MatsMatchComp) => {
    return queditor.store.currActiveProdComp?.name == matsGroup.name;
  };

  ctrl.switchGroupIndex = (matsGroup: MatsMatchComp) => {
    switchComp(matsGroup.name || "");
  };

  ctrl.unbindScroll = () => {
    const app = queditor.controls.queen3dCtrl.queen3d.getAppInstance();
    app.unbind("tap:click");
    ctrl.scrollEl = undefined;
  };

  ctrl.initScroll = (el) => {
    const app = queditor.controls.queen3dCtrl.queen3d.getAppInstance();

    app.on("tap:click", (geom: any, clicked: boolean) => {
      if (!clicked) return;
      const scrollEl = el.$el.querySelector(".content");
      ctrl.scrollEl = scrollEl;
      scrollToElement();
    });
  };

  function scrollToElement() {
    if (!ctrl.scrollEl) return;
    const doms = ctrl.scrollEl.querySelectorAll(".JSDrop");
    if (!doms.length) return;
    const index = match.store.menuOptions.sourceData.mat.findIndex(
      (d: any) => d.name == queditor.store.currActiveProdComp?.name
    );

    ctrl.scrollEl.scrollTo({
      top: doms[index].offsetTop - doms[0].offsetTop,
      behavior: "smooth",
    });
  }

  ctrl.initEvent = () => {
    // drag to mesh
    // queditor.actions.on("updatePackProductCompMat:success", (...args) => {
    //   console.error("updatePackProductCompMat:success*************");
    //   scrollToElement();
    // });

    // drag to group
    queditor.controls.drager.on(
      "drop:selfDrop",
      async (event: DragEvent, { type, data }: any, extraData: any) => {
        const dropData = await data();
        if (type == "asset3d.mat") {
          dropMat(dropData, extraData);
        } else if (type == "asset3d.mesh") {
          dropMesh(dropData, extraData);
        }
      }
    );
  };

  ctrl.destroy = () => {
    queditor.controls.drager.unbind("drop:selfDrop");
  };

  function dropMesh(dropData: any, target: any) {
    console.log("dropData: ", dropData, target);
    //
  }

  // 拖拽面料
  function dropMat(mat: PackMat, extraData: any) {
    const currGroup = findmatsGroup(extraData);
    if (!currGroup.matIds) currGroup.matIds = [];

    if (currGroup.matIds.includes(mat.id)) {
      queenApi.messageError("不能重复添加色卡");
      return;
    }
    // update mat
    const targetPro = queditor.helper.findProductDef(extraData.productId);
    const targetCom = findCompDef(targetPro, extraData.name);
    if (!targetCom) return;

    queditor.actions.updatePackProductCompMat(targetCom, mat, true);
    currGroup.matIds.push(mat.id);
    currGroup.index = currGroup.matIds.length - 1;
  }

  function findmatsGroup(target: MatsMatchComp) {
    const currGroup = match.store.menuOptions.sourceData.mat.find(
      (r: MatsMatchComp) =>
        r.name == target.name && r.productId == target.productId
    );
    return currGroup;
  }

  return ctrl;
}
