import React, { useCallback, useEffect, useRef, useState } from "react";
import { message } from "antd";
import MybricksDesigner from "@mybricks/designer-spa";
import toolsPlugin from "@mybricks/plugin-tools";
import servicePlugin from '@mybricks/plugin-connector-http'
import { useComputed } from "rxui-t";
import { View, Toolbar } from "@mybricks/sdk-for-app/src/ui";
import { pageModel, userModel } from "@/stores";
import API from '@mybricks/sdk-for-app/src/api'
import styles from "./index.less";

const Designer = () => {
  const [beforeunload, setBeforeunload] = useState(false);
  const designerRef = useRef<{ switchActivity; dump; toJSON }>();

  const config = useCallback((context) => {
    const { pageConfig, fileContent, fileId } = context;

    console.warn("fileContent", fileContent);

    return {
      plugins: [
        servicePlugin(),
        toolsPlugin(),
      ],
      comLibLoader() {
        //加载组件库
        return new Promise((resolve) => {
          resolve([`${location.origin}/libEdt.js`]);
        });
      },
      pageContentLoader() {
        //加载内容
        return new Promise((resolve) => {
          console.log("fileContent", fileContent);
          resolve(fileContent || null);
        });
      },
      editView: {
        // eslint-disable-next-line no-empty-pattern
        items({ }, cate0) {
          cate0.title = "页面配置";
          cate0.items = [
            {
              title: "自定义顶部栏",
              type: "Text",
              value: {
                get: () => {
                  return pageConfig.host;
                },
                set: (context, v: string) => {
                  pageModel.pageConfig.host = v;
                },
              },
            },
          ];
        },
      },
      geoView: {
        type: "mobile",
        width: 375,
        height: 667,
      },
    };
  }, []);

  useEffect(() => {
    if (beforeunload) {
      window.onbeforeunload = () => {
        return true;
      };
    } else {
      window.onbeforeunload = null;
    }
  }, [beforeunload]);

  const save = useCallback(() => {
    const json = designerRef.current?.dump();

    API.File.save({
      userId: userModel.user?.email,
      fileId: pageModel.fileId,
      content: JSON.stringify({ ...json, pageConfig: pageModel.pageConfig }),
    }).then(res => {
      message.success('保存完成');
    }).catch(e => {
      message.error(`保存失败：${e.message}`);
    });

    setBeforeunload(false);

    //出码
  }, []);

  const publish = useCallback(async () => {
    const json = designerRef.current?.toJSON();

    /** 保存 */
    pageModel.sdk.save?.(
      {
        userId: userModel.user?.email,
        fileId: pageModel.fileId,
        content: JSON.stringify({
          ...designerRef.current?.dump(),
          pageConfig: pageModel.pageConfig,
        }),
      },
      { skipMessage: true }
    );

    message.success("发布完成");
    setBeforeunload(false);

    designerRef.current?.switchActivity?.("@mybricks/plugins/version");
    setTimeout(() => {
      pageModel?.versionApi?.switchAciveTab?.("publish", "");
    }, 0);
  }, [save]);

  const onEdit = useCallback(() => {
    setBeforeunload(true);
  }, []);

  const handleSwitch2SaveVersion = useCallback(() => {
    designerRef.current?.switchActivity?.("@mybricks/plugins/version");
    setTimeout(() => {
      pageModel?.versionApi?.switchAciveTab?.("save");
    }, 0);
  }, []);

  const storeAppData = useCallback(ref => {
    console.error("ref", ref);

    userModel.setUser(ref.user);

    pageModel.file = ref.fileContent;
    pageModel.fileContent = ref.fileContent.content || {};
    pageModel.pageConfig = ref.fileContent.content?.pageConfig || {};
    pageModel.sdk = ref;
    pageModel.fileId = ref.fileId;
  }, []);

  return (
    <View onLoad={(appData) => {

      storeAppData(appData);

      return (
        <div className={styles.show}>
          <Toolbar
            title={pageModel.file?.name}
            updateInfo={<Toolbar.LastUpdate onClick={handleSwitch2SaveVersion} />}
          >
            <Toolbar.Save
              onClick={save}
              dotTip={beforeunload}
            />
            {/* <button className={styles.publishBtn} onClick={publish}>
              发布
            </button> */}
          </Toolbar>
          <div className={styles.designer}>
            <MybricksDesigner config={config(pageModel)} ref={designerRef} onEdit={onEdit} />
          </div>
        </div>
      )
    }}>
    </View>
  );
};

export default Designer;
