import React from "react";
import ReactDOM from "react-dom";
import { List, Card } from "antd";
import { MinusCircleFilled, CheckCircleFilled } from "@ant-design/icons";

export default class PageManager {
  constructor(editor, opts) {
    _.bindAll(this, [
      "destroy",
      "getPages",
      "onLoad",
      "handleAddPage",
      "handlePageChange",
      "handleRemove",
      "load",
      "loadPageData",
      "renderList",
    ]);

    this.name = "PageManager";

    this.editor = editor;
    this.c = opts;

    this.em = editor.getModel();
    this.selector = this.em
      .get("modules")
      .find((module) => module.name === "MultiSelector");
    this.resizer = this.em
      .get("modules")
      .find((module) => module.name === "CanvasResizer");
    this.zoomer = this.em
      .get("modules")
      .find((module) => module.name === "CanvasZoomer");

    editor.on("storage:start:store", (data) => {
      // 获取当前页面的 group 信息
      const { groups, compIdToGroupMap } = this.selector.getGroups();

      const pageList = this.getPages();

      if (!_.isEmpty(pageList)) {
        // 记录在 pageList 中
        const toStore = {};

        editor.editor.get("storables").forEach((m) => {
          var obj = m.store(1);
          for (var el in obj) toStore[el] = obj[el];
        });

        delete data['assets'];
        delete toStore['assets'];

        Object.assign(pageList[editor.PageManager.current], {
          groups: JSON.stringify({ groups, compIdToGroupMap }),
          pmComponents: editor.getComponents().models.slice(0),
          pmStyle: editor.getStyle().models.slice(0),
          ...toStore,
        });

        Object.assign(data, { pageList: JSON.stringify(pageList) });
      }
    });

    editor.on("storage:end:load", (data) => {
      if (!_.isEmpty(data) && !_.isEmpty(data.pageList)) {
        const pageList = JSON.parse(data.pageList);
        // load pages
        this.load(pageList);

        // 获取 pageList 中第一个page信息
        const currentPage = pageList[0];

        const groups = JSON.parse(currentPage.groups);

        // 设置 group 信息
        this.selector.loadGroups(groups);

        // 设置页面编辑信息
        editor.DomComponents.clear();
        editor.DomComponents.componentsById = {};
        editor.setComponents(currentPage.pmComponents);
        editor.setStyle(currentPage.pmStyle);

        // resizer
        this.resizer.render();

        // 加载 css
        editor.CssComposer.load({ ...currentPage });
      }
    });
  }

  destroy() {}

  getPages() {
    return _.get(this, "pageListData.pages".split('.'), []);
  }

  handleAddPage() {
    this.pageListData.pages.push({
      components: [],
      styles: [],
      css: "",
      assets: [],
      groups: { groups: [], compIdToGroupMap: {} },
      pmComponents: [],
      pmStyle: [],
    });

    this.handlePageChange(this.pageListData.pages.length - 1);
  }

  handlePageChange(currentIndex) {
    const { editor } = this;
    const { current } = this.pageListData;

    currentIndex = Math.max(
      0,
      Math.min(currentIndex, this.pageListData.pages.length - 1)
    );

    if (current === currentIndex) {
      return;
    }

    if (0 <= current && current <= this.pageListData.pages.length - 1) {
      this.pageListData.pages[current] = {
        ...this.pageListData.pages[current],
        pmComponents: editor.getComponents().models.slice(0),
        pmStyle: editor.getStyle().models.slice(0),
      };
    }

    this.loadPageData(currentIndex);

    this.pageListData.current = currentIndex;
    this.renderList();
  }

  handleRemove(event, index) {
    event.stopPropagation();

    if (this.pageListData.pages.length === 1) {
      return;
    }

    this.pageListData.pages.splice(index, 1);

    if (this.pageListData.current === index) {
      this.pageListData.current = index - 1 >= 0 ? index - 1 : index;
    }

    this.renderList();
    this.loadPageData(this.pageListData.current);
  }

  load(pages) {
    this.pageListData = {
      current: 0,
      pages,
    };

    this.onLoad();
  }

  loadPageData(currentIndex) {
    const { editor } = this;
    const { pages = [] } = this.pageListData;

    const em = editor.getModel();
    const selector = em
      .get("modules")
      .find((module) => module.name === "MultiSelector");
    const resizer = em
      .get("modules")
      .find((module) => module.name === "CanvasResizer");
    const zoomer = em
      .get("modules")
      .find((module) => module.name === "CanvasZoomer");
    const nextPage = pages[currentIndex];

    editor.DomComponents.clear();
    editor.DomComponents.componentsById = {};
    editor.setComponents(nextPage.pmComponents || []);
    editor.setStyle(nextPage.pmStyle || []);

    selector.loadGroups(nextPage.groups);
    resizer.render();

    // 加载 css
    editor.CssComposer.load({ ...nextPage });
  }

  onLoad() {
    if (_.isEmpty(this.pageListData)) {
      this.pageListData = {
        current: 0,
        pages: [
          {
            components: [],
            styles: [],
            css: "",
            groups: { groups: [], compIdToGroupMap: {} },
            pmComponents: [],
            pmStyle: [],
          },
        ],
      };

      Object.assign(this.pageListData.pages[0], {
        pmComponents: this.editor.getComponents().models.slice(0),
        pmStyle: this.editor.getStyle().models.slice(0),
      });
    }

    this.editor.PageManager = this.pageListData;
  }

  renderList() {
    let $pageListContainer = document.querySelector(".page-manager-container");

    if ($pageListContainer) {
      $pageListContainer = $($pageListContainer);
    } else {
      $pageListContainer = $(
        '<div class="page-manager-container" style="position: absolute; z-index: 99; right: 0; bottom: 0; left: 0; height: 150px; overflow-x: auto;padding-top: 16px;"></div>'
      );
    }

    const { current } = this.pageListData;

    ReactDOM.render(
      <div>
        <List
          style={{
            maxWidth: "calc(100% - 200px)",
            height: 130,
            overflowX: "auto",
            overflowY: "hidden",
            display: "inline-block",
            whiteSpace: "nowrap",
          }}
          dataSource={this.getPages()}
          renderItem={(item, index) => (
            <List.Item
              style={{
                width: 180,
                height: 100,
                display: "inline-block",
                marginRight: 6,
                verticalAlign: "top",
              }}
              onClick={() => {
                this.handlePageChange(index);
              }}
            >
              <Card
                style={{
                  position: "relative",
                  width: "100%",
                  height: "100%",
                  border: "none",
                  backgroundColor: "#000",
                  color: "#90a0af",
                }}
                bodyStyle={{padding: 8}}
              >
                <MinusCircleFilled
                  style={{ position: "absolute", top: 10, right: 10 }}
                  onClick={(event) => {
                    this.handleRemove(event, index);
                  }}
                />
                <p style={{ textAlign: "center" }}>页面{index + 1}</p>
                {current === index && (
                  <CheckCircleFilled
                    style={{ position: "absolute", bottom: 10, right: 10 }}
                  />
                )}
              </Card>
            </List.Item>
          )}
        />
        <List.Item
          style={{
            width: 180,
            height: 100,
            display: "inline-block",
            paddingLeft: 6,
            paddingRight: 6,
            verticalAlign: "top",
          }}
          onClick={this.handleAddPage}
        >
          <Card
            style={{
              width: "100%",
              height: "100%",
              border: "none",
              backgroundColor: "#000",
              color: "#90a0af",
              textAlign: "center",
            }}
          >
            <p>
              +<br />
              添加新页面
            </p>
          </Card>
        </List.Item>
      </div>,
      $pageListContainer[0]
    );

    return $pageListContainer[0];
  }
}
