import { PageListController } from "@queenjs/controllers";
import { ResourceModule } from ".";
import { ComponentController } from "./controllers/ComponentController";
import { MaterialController } from "./controllers/MaterialController";
import { queenApi } from "queenjs";

export const helper = ResourceModule.helper({
  createFileName(fileName: string, dir: string) {
    const suffix = fileName.substring(fileName.lastIndexOf("."));
    if (/[\u4e00-\u9fa5]/.test(fileName) || fileName.length > 10) {
      fileName = `${this.controls.uploader.randomName(4)}${suffix}`;
    }
    return `${dir}/${Date.now()}_${this.controls.uploader.randomName(
      6
    )}_${fileName}`;
  },

  createCompController() {
    const ctrl = new ComponentController();
    ctrl.ListCtrl = new PageListController(this.config?.httpConfig);
    ctrl.ListCtrl.setCrudPrefix("/frame");
    ctrl.createComp = this.actions.createComp;
    ctrl.onMenuClick = async (name, record) => {
      if (name == "delete") {
        await this.actions.deleteComp(record);
        ctrl.ListCtrl.fresh();
      } else if (name == "rename") {
        await this.actions.renameComp(record);
      }
    };

    return ctrl;
  },

  // createSourceController() {
  //   const { controls, actions } = this;

  //   const ctrl = new MaterialController();
  //   ctrl.imageCtrl = controls.materialImageListCtrl;
  //   ctrl.vidoeCtrl = controls.materialVideoListCtrl;
  //   ctrl.taskCtrl = controls.renderTaskListCtrl;
  //   ctrl.tplCtrl = controls.matTempListCtrl;

  //   ctrl.onBtnClick = async function (name: string) {
  //     if (name == "upload") {
  //       const uploaded = await actions.uploadMaterial();
  //       ctrl.switchTab(uploaded.fileType, false);
  //       ctrl.getCurrControl().loadPage(1);
  //       return;
  //     }
  //     ctrl.showDialog(name);
  //   };
  //   ctrl.onItemClick = function (name, record) {
  //     if (name == "delete") return actions.deleteMaterial(record);
  //     return actions.downloadMaterial(record);
  //   };
  //   return ctrl;
  // },

  async uploadResource(opts?: { accept?: string; multiple?: boolean }) {
    const result = [];
    const blobs = await queenApi.selectFile(opts);

    queenApi.showLoading("上传中……");

    for (const key in blobs) {
      const blob = blobs[key];
      const file = await this.controls.uploader.uploadFile(blob, "queenshow");
      const souceObj = {
        file,
        fileType: blob.type.split("/")[0],
        from: "upload",
      };
      result.push(souceObj);
    }
    
    queenApi.hideLoading();
    return result;
  },
});
