import { useCtx } from "@/comm/ctx";
import ListModule from "..";
import { ItemObject, ShowItem } from "../objects/item";

const defaultImage = require("@/assets/default.png");
function loadImg(url: string, id: string, name: string): Promise<ShowItem> {
  return new Promise((resolve, reject) => {
    const { deviceCtrl } = useCtx();
    const m = new Image();
    if (url) {
      m.src = deviceCtrl.httpServer + url;
    } else {
      m.src = defaultImage;
    }
    m.onload = () => {
      resolve({
        id: id,
        w: m.width,
        h: m.height,
        url: url,
        offsetX: 0,
        offsetY: 0,
        x: 0,
        y: 0,
        z: 0,
        padding: 0,
        opacity: 0,
        currX: 0,
        currY: 0,
        show: false,
        offsetZ: 0,
        timer: 0,
        name,
        img: m,
      });
    };
  });
}
export default ListModule.action({
  async shuffleSelf(arr, size) {
    let index = -1;
    const length = arr.length;
    const lastIndex = length - 1;
    size = size === undefined ? length : size;

    while (++index < size) {
      const rand = index + Math.floor(Math.random() * (lastIndex - index + 1));
      const value = arr[rand];
      arr[rand] = arr[index];
      arr[index] = value;
    }
    arr.length = size;
    return arr;
  },
  async loadData() {
    // await this.actions.getAssetList();
    const ps = this.store.list.map((item: ItemObject, index) =>
      loadImg(item.thumbnail, item._id, item.name)
    );
    const rets = await Promise.all(ps);

    return rets;
  },
  async initLoadShowItems(rets: any[] = []) {
    const totalRow = this.store.totalRow;

    for (let i = 0; i < totalRow; i++) {
      //随机排序下
      this.actions.shuffleSelf(rets, rets.length);
      const offset = 0;
      rets.forEach((item, index) => {
        const it = { ...item };

        this.store.items.push(it);
      });
    }
    return rets;
  },

  async loadPack3d(item: ItemObject) {
    const { deviceCtrl } = useCtx();
    const meshId = item.meshId;
    if (!meshId) return;

    const ret:any = await this.https.loadLocal(deviceCtrl.httpServer + meshId);
    console.log("loadPack3d",ret);

    return ret;
  },
});
