import { EditorModule } from "@/modules/editor/module";
import { ResourceModule } from "@/modules/resource";
import { PromotionController } from "@/modules/resource/controllers/PromotionController";
import { PageListController } from "@queenjs/controllers";
import { queenApi } from "queenjs";
import ShareModal from "./components/ShareModal";

export function createPromotinController(
  resource: ResourceModule,
  editor: EditorModule
) {
  const ctrl = new PromotionController();

  ctrl.ListCtrl = new PageListController(resource.config?.httpConfig);
  ctrl.ListCtrl.setCrudPrefix("/h5");
  ctrl.createPromotion = resource.actions.createPromotion;
  ctrl.changeThumbnail = resource.helper.uploadResource;

  ctrl.updateDesign = (record: any, data: any) => {
    if (data.title == "") {
      queenApi.messageError("标题不能为空！");
      return;
    }
    if (record.desc && data.desc == "") {
      queenApi.messageError("描述不能为空！");
      return;
    }

    for (const [key, value] of Object.entries(data)) {
      record[key] = value;
    }
    editor.https.saveDesign(data);
    queenApi.messageSuccess("保存成功！");
  };

  async function sharePromotion(record: any) {
    editor.actions.initDesign(record._id);
    editor.actions.switchMode("preview");
    resource.showModal(
      <ShareModal record={record} controller={ctrl}>
        {{
          preview: () => (
            <editor.components.Preview class="pointer-events-none" />
          ),
        }}
      </ShareModal>,
      {
        title: "编辑分享",
        width: "1000px",
      }
    );
  }

  ctrl.onMenuClick = async (name, record) => {
    switch (name) {
      case "delete":
        await resource.actions.deletePromotion(record);
        ctrl.ListCtrl.fresh();
        break;
      case "rename":
        await resource.actions.renamePromotion(record);
        break;
      case "share":
        sharePromotion(record);
        break;
    }
  };

  return ctrl;
}
