import { propertyRegistered } from "./propertyRegister";

let propertyDialogSeed = 0;

function nextPropertyDialogId() {
  propertyDialogSeed += 1;
  return `widget-property-dialog-${Date.now()}-${propertyDialogSeed}`;
}

export default {
  data() {
    return {
      widgetPropertyDialogs: [],
      activePropertyDialogId: null,
    };
  },
  methods: {
    getActivePropertyDialog() {
      if (!this.widgetPropertyDialogs.length) {
        return null;
      }
      if (this.activePropertyDialogId) {
        const active = this.widgetPropertyDialogs.find(
          (dlg) => dlg.id === this.activePropertyDialogId
        );
        if (active) {
          return active;
        }
      }
      return this.widgetPropertyDialogs[this.widgetPropertyDialogs.length - 1];
    },
    setActivePropertyDialog(id) {
      this.activePropertyDialogId = id;
      this.syncLegacyPropertyDialogState();
    },
    syncLegacyPropertyDialogState() {
      const active = this.getActivePropertyDialog();
      this.showDateConfigDialog = !!active;
      this.columnSelectedWidget = active ? active.columnSelectedWidget : {};
      this.columnEditFields = active ? active.columnEditFields : [];
      this.formatConfig = active ? active.formatConfig : {};
      this.tableColumns = active ? active.tableColumns : null;
    },
    openWidgetPropertyDialog(config) {
      const id = nextPropertyDialogId();
      const dialog = {
        id,
        visible: true,
        title: config.title,
        columnSelectedWidget: config.columnSelectedWidget || {},
        columnEditFields: config.columnEditFields || null,
        tableColumns: config.tableColumns,
        formatConfig: config,
        widgetActiveCollapseName1s: ["1", "3"],
      };
      this.widgetPropertyDialogs.push(dialog);
      this.setActivePropertyDialog(id);
    },
    closeWidgetPropertyDialog(id, invokeCallback = false) {
      const index = this.widgetPropertyDialogs.findIndex(
        (dlg) => dlg.id === id
      );
      if (index === -1) {
        return;
      }
      const dialog = this.widgetPropertyDialogs[index];
      if (
        invokeCallback &&
        dialog.formatConfig &&
        dialog.formatConfig.callback
      ) {
        const columnSelectedWidget = this.$baseLodash.cloneDeep(
          dialog.columnSelectedWidget
        );
        dialog.formatConfig.callback(columnSelectedWidget);
      }
      this.widgetPropertyDialogs.splice(index, 1);
      if (this.activePropertyDialogId === id) {
        const last =
          this.widgetPropertyDialogs[this.widgetPropertyDialogs.length - 1];
        this.activePropertyDialogId = last ? last.id : null;
      }
      this.syncLegacyPropertyDialogState();
    },
    handleWidgetPropertyDialogBeforeClose(dialog, done) {
      this.closeWidgetPropertyDialog(dialog.id);
      done();
    },
    confirmWidgetPropertyDialog(dialog) {
      this.closeWidgetPropertyDialog(dialog.id, true);
    },
    hasPropEditorForDialog(dialog, propName, editorName) {
      if (!editorName) {
        return false;
      }
      if (
        dialog.columnEditFields &&
        !dialog.columnEditFields.includes(propName)
      ) {
        return false;
      }
      const widget = dialog.columnSelectedWidget;
      if (propName.indexOf("-") <= -1) {
        const originalPropName = `${widget.type}-${propName}`;
        if (propertyRegistered(originalPropName)) {
          return false;
        }
      }
      const propKey = propName.replace(`${widget.type}-`, "");
      return this.designer.hasConfig(widget, propKey);
    },
    getPropEditorForDialog(dialog, propName, editorName) {
      const widget = dialog.columnSelectedWidget;
      const propKey = propName.replace(`${widget.type}-`, "");
      const uniquePropName = `${widget.type}-${propKey}-editor`;
      if (this.$options.components[uniquePropName]) {
        return uniquePropName;
      }
      if (this.$root.$options.components[uniquePropName]) {
        return uniquePropName;
      }
      return editorName;
    },
    showCollapseForDialog(dialog, props) {
      for (const propName in props) {
        if (!props.hasOwnProperty(propName)) {
          continue;
        }
        if (this.hasPropEditorForDialog(dialog, propName, props[propName])) {
          return true;
        }
      }
      return false;
    },
    editEventHandler(eventName, eventParams, eventOptions) {
      eventOptions = eventOptions || {};
      const activeDialog = this.getActivePropertyDialog();
      const eventWidget = activeDialog
        ? activeDialog.columnSelectedWidget
        : this.selectedWidget;
      this.curEventName = eventName;
      this.eventHeader = `${
        this.optionModel.name
      }.${eventName}(${eventParams.join(", ")}) {`;
      if (eventOptions.customCode) {
        this.eventHandlerCode = eventOptions.customCode() || "";
      } else {
        this.eventHandlerCode =
          (eventWidget && eventWidget.options[eventName]) || "";
      }
      this.eventOption = eventOptions;
      /* if (eventName === 'onCreated' && !this.optionModel.onCreated) {
        this.eventHandlerCode = '  //组件创建生命周期\n  onsole.logc(\'test onCreated()\')\n';
      } */
      this.showWidgetEventDialogFlag = true;
    },
    saveEventHandler() {
      const editorAnnotations = this.$refs.ecEditor.getEditorAnnotations();
      let hasError = false;
      if (editorAnnotations && editorAnnotations.length > 0) {
        editorAnnotations.forEach((item) => {
          if (item.type === "error") {
            hasError = true;
          }
        });
        if (hasError) {
          this.$message.error(this.i18nt("designer.hint.syntaxCheckWarning"));
          return;
        }
      }
      const eventOptions = this.eventOption || {};
      if (!eventOptions.callback) {
        const activeDialog = this.getActivePropertyDialog();
        const eventWidget = activeDialog
          ? activeDialog.columnSelectedWidget
          : this.selectedWidget;
        if (eventWidget) {
          eventWidget.options[this.curEventName] = this.eventHandlerCode;
        }
      } else {
        eventOptions.callback(this.eventHandlerCode);
      }
      this.showWidgetEventDialogFlag = false;
    },
  },
};
