/**
 *
 * 当前应用queen5接受的消息处理。
 *   目前文件依赖 设计为 当前文件 依赖于modules/ediotor/controllers下的文件，这样避免share页面打包
 *   当前模块，导致nats.ws文件被引用，引发 部分手机 share页面打不开的bug
 */

import { cloneDeep } from "lodash";
import { queenApi } from "queenjs";
import { Controller } from "../core/controller";
import { useCtx } from "../ctx";
export class AppScreenMsgController extends Controller {
  screenModule: any;
  constructor() {
    super();
  }

  onReady() {
    // this.initScreen();
  }

  initScreen() {
    const { recvCtrl } = useCtx();

    recvCtrl.clearListeners();
    recvCtrl.addAssetsListener("发送模型", async (packUrl: string) => {
      const urlReg = /[a-zA-z]+:\/\/[^\s]*/;
      let packId = packUrl;
      if (urlReg.test(packUrl)) {
        const urlArr = packUrl.split("?");
        const params = urlArr[1].split("&");
        let obj: any = {};
        for (let i = 0; i < params.length; i++) {
          let param = params[i].split("=");
          obj[param[0]] = param[1];
        }
        packId = obj.id;
      }
      if (!packId) {
        return false;
      }
      this.downloadLocalPack(packId);
      return true;
    });
    recvCtrl.emitChange();
  }
  async downloadLocalPack(packId: string) {
    const { actions } = this.screenModule;
    const assetDtl = await actions.getAssetDetail(packId);
    if (assetDtl) {
      this.exportLocalWebPack(assetDtl);
    }
  }
  // loadHttp(url: string) {
  //   const req = new XMLHttpRequest();
  //   return new Promise((resolve, reject) => {
  //     req.onload = function () {
  //       if (req.status == 200) {
  //         resolve(req.response);
  //       }
  //     };
  //     // req.onreadystatechange = function() {
  //     //   if (req.readyState == 4 && req.status == 200) {
  //     //     resolve(req.response);
  //     //   }
  //     // }
  //     req.timeout = 1000 * 60 * 3;
  //     req.responseType = "blob";
  //     req.open("GET", url, true);
  //     req.send(null);
  //   });
  // }

  loadfile(dir: string, url: string) {
    if (!url) return;
    const { deviceCtrl } = useCtx();
    let names = url.split("/");
    let name = names[names.length - 1];

    const screenDir = deviceCtrl.appDataDir + "/screen";
    const filepath = screenDir + dir + name;
    deviceCtrl.DownloadFile(url, filepath);
    return {
      file: dir + name,
      // promise: new Promise((resolve, reject) => {
      //   // scope.assetCtroller.db.ctx.http.request(url, {method:"GET",baseURL:"", noAuth:true, responseType:"blob", originBody:true})
      //   this.loadHttp(url).then((blob: any) => {
      //     resolve({ file: dir.substring(2) + name, blob: blob });
      //   });
      // }),
    };
  }
  async exportLocalWebPack(asset: any) {
    // this.exportLocalEnv3ds();
    // return;
    queenApi.showLoading("资源下载中");
    const { deviceCtrl } = useCtx();

    let files: any = [];
    let pack = cloneDeep(asset);
    let source = pack.source;
    let wk = `/assets/packs/${pack._id}/`;
    let scope = this;

    function getFileName(url: string) {
      if (!url) return;

      let names = url.split("/");
      let name = names[names.length - 1];
      return name;
    }

    //模型处理
    let geom = source.geoms[0];
    let osgbinUrl = geom.osgjs.url;
    source.geoms = [geom];
    let f = this.loadfile(wk, geom.osgjs.url);
    // files.push(f?.promise);
    geom.osgjs.url = f?.file;

    osgbinUrl = osgbinUrl.substring(0, osgbinUrl.length - 5) + "bin";
    f = this.loadfile(wk, osgbinUrl);
    // files.push(f?.promise);

    f = this.loadfile(wk, geom.shadow.url);
    if (f) {
      geom.shadow.url = f.file;
      // files.push(f.promise);
    }
    delete geom.file;
    delete geom.glb;

    //材质处理
    source.mats.forEach((m: any) => {
      //base map
      let f = scope.loadfile(wk, m.albedo.texture?.url);
      if (f) {
        // files.push(f.promise);
        m.albedo.texture.url = f.file;
      }

      //法线
      if (m.normal?.texture) {
        f = scope.loadfile(wk, m.normal.texture?.url);
        if (f) {
          // files.push(f.promise);
          m.normal.texture.url = f.file;
        }
      }

      //粗糙度
      if (m.roughness.texture) {
        f = scope.loadfile(wk, m.roughness.texture.url);
        if (f) {
          // files.push(f.promise);
          m.roughness.texture.url = f.file;
        }
      }

      //金属度
      if (m.metalness.texture) {
        f = scope.loadfile(wk, m.metalness.texture.url);
        if (f) {
          // files.push(f.promise);
          m.metalness.texture.url = f.file;
        }
      }

      //透明度
      if (m.opacity.texture) {
        f = scope.loadfile(wk, m.opacity.texture.url);
        if (f) {
          // files.push(f.promise);
          m.opacity.texture.url = f.file;
        }
      }
    });
    //封面图
    let thumbnail = pack.thumbnail;
    const thumb = this.loadfile(wk, thumbnail.url);
    pack.thumbnail.url = thumb?.file;
    //环境球
    const wkenv3d = "/assets/env3d/";
    source.env3ds.forEach((item: any) => {
      const id = item.userData.assetId || item.id;

      const wk = wkenv3d + id + "/bg/";
      if (item.background?.image?.url) {
        item.background.image.url = wk + getFileName(item.background.image.url);
      }
      const twk = wkenv3d + id + "/t/";
      item.config.textures.forEach((t: any) => {
        t.images.forEach((im: any) => {
          im.file = twk + getFileName(im.file);
        });
      });
    });

    const wk3 = wkenv3d + "bg/";
    source.scenes.forEach((c: any) => {
      //@ts-ignore
      const url = c.background?.image?.url;
      if (url) {
        //@ts-ignore
        c.background.image.url = wk3 + getFileName(url);
      }
    });

    const configFile = JSON.stringify(pack);

    const res = await deviceCtrl.WriteFileText(
      `${deviceCtrl.appDataDir}/screen/assets/packs/${pack._id}.json`,
      configFile
    );
    const currentCategory = localStorage.getItem("category") || "default";
    const assetsJson = await deviceCtrl.ReadFileText(
      `${deviceCtrl.appDataDir}/screen/assets_${currentCategory}.json`
    );
    if (assetsJson.text) {
      const assets = JSON.parse(assetsJson.text);
      const assetItem = {
        _id: pack._id,
        name: pack.name,
        thumbnail: pack.thumbnail.url,
        type: "3D",
        meshId: `/assets/packs/${pack._id}.json`,
      };
      assets.push(assetItem);
      await deviceCtrl.WriteFileText(
        `${deviceCtrl.appDataDir}/screen/assets_${currentCategory}.json`,
        JSON.stringify(assets)
      );
    }
    queenApi.hideLoading();
    this.screenModule.actions.getAssetList();
    // Promise.all(files).then((blobs) => {
    //   let zip = new JSZip();
    //   blobs.forEach((blob: any, i) => {
    //     zip.file(`${blob.file}`, blob.blob, { binary: true });
    //   });
    //   zip.file(
    //     `${pack._id}.json`,
    //     new Blob([configFile], {
    //       type: "text/plain",
    //     })
    //   );
    //   const appDataDir = deviceCtrl.appDataDir;
    //   const zipDir = `${appDataDir}/screen/${pack._id}.zip`;
    //   zip.generateAsync({ type: "blob" }).then((content: any) => {
    //     // deviceCtrl.DownloadFile(content, zipDir);
    //     console.log(zipDir);
    //     FileSaver.saveAs(content, zipDir);
    //     queenApi.hideLoading();
    //     // const ok=deviceCtrl.Unzip(zipDir,)
    //   });
    // });
  }
}
