import SelectListItemModal from "./components/SelectListItemModal";
import { MaterialController } from "../../../modules/resource/controllers/MaterialController";
import PreviewModal from "../components/PreviewModal";
import { queenApi } from "queenjs";

export default function createController(resource:any, isSelectModel:boolean, selectType :string) {
    const {controls, actions} = resource;
    const  showModal = async (type: string) => {
        const ctrl = resource.controls.matTempListCtrl;
        ctrl.state.query = type == "video" ? { hasVideo: true } : {}
        ctrl.loadPage(1);
        const record  = await resource.showModal(<SelectListItemModal ListCtrl={ctrl} onPreview={(record) => {
          showPreviewModal({
            url:record.thumbnail,
            fileType:type == "video" ? "video":'image'
          })
        }}  />, {
          title: `${type === "image" ? "图片" : "视频"}模板中心`,
          width: "1000px",
        });
        resource.actions.selectMaterial(record);
    };

    const  showPreviewModal = (data: {
      url: string;
      fileType: "image" | "video";
    }) => {
      resource.showModal(<PreviewModal data={data}  />, {
        title: "预览",
        width: "1000px",
        centered: true
      }); 
  };

    const ctrl = new MaterialController();
    ctrl.imageCtrl = controls.materialImageListCtrl;
    ctrl.vidoeCtrl = controls.materialVideoListCtrl;
    ctrl.taskCtrl = controls.renderTaskListCtrl;
    ctrl.state.isSelect = isSelectModel;
    if (selectType) ctrl.state.selectType = selectType;

    ctrl.onBtnClick = async function (name: string) {
      if (name == "upload") {
        const uploaded = await resource.actions.uploadMaterial();
        ctrl.switchTab(uploaded.fileType, false);

        if (uploaded && uploaded.file?.url) {
           if (ctrl.state.isSelect) {
            ctrl.onCloseDialog(uploaded.file?.url);
            return;
           }
        }

        ctrl.getCurrControl().loadPage(1);
        return;
      }
      queenApi.messageSuccess("功能开发中, 敬请期待!")
      //showModal(name);
    };
    ctrl.onItemClick = async function (name, record) {
      if (name == "delete") {
         await actions.deleteMaterial(record);
         this.getCurrControl().fresh();
         return;
      }
      else if (name == "preview") return showPreviewModal({
        url: record.file.url,
        fileType: record.fileType,
      });
      else if (name == "use") {
          console.log(name, record);
          ctrl.onCloseDialog(record.file.url);
          return;
      }

      return actions.downloadMaterial(record);
    };

    return ctrl
}