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";
import { sendPromotion } from "./components/SendPromotion";
import { AuthModule } from "@queenjs-modules/auth";
import { SelectOneImage } from "../Material2/modal";

export function createPromotinController(
  auth: AuthModule,
  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) {
    resource.showModal(<ShareModal record={record} controller={ctrl} />, {
      title: "编辑分享",
      width: "1000px",
      destroyOnClose: true,
    });
  }
  let url = "";
  ctrl.onMenuClick = async (name, record) => {
    switch (name) {
      case "stat":
        window.open("https://show.3dqueen.cloud/stat/#/count?id=" + record._id);
        break;
      case "delete":
        await resource.actions.deletePromotion(record);
        ctrl.ListCtrl.fresh();
        break;
      case "rename":
        await resource.actions.renamePromotion(record);
        break;
      case "share":
        sharePromotion(record);
        break;
      case "send":
        sendPromotion(resource, record);
        break;
      case "publish":
        await resource.actions.publishPromotion(record, true);
        break;

      case "unpublish":
        await resource.actions.publishPromotion(record, false);
        break;

      case "thumbnail":
        url = (await SelectOneImage()) as string;
        if (!url) return;
        await resource.https.updatePromotion({
          _id: record._id,
          thumbnail: url,
        });
        record.thumbnail = url;
        queenApi.messageSuccess("替换成功");
        break;
    }
  };

  return ctrl;
}
