var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
  for (var prop in b || (b = {}))
    if (__hasOwnProp.call(b, prop))
      __defNormalProp(a, prop, b[prop]);
  if (__getOwnPropSymbols)
    for (var prop of __getOwnPropSymbols(b)) {
      if (__propIsEnum.call(b, prop))
        __defNormalProp(a, prop, b[prop]);
    }
  return a;
};
import { E as ElementModel } from "./background.js";
import { i as inherit, P as Promise$1, B as BaseElement } from "./base-element.js";
import { l as lodash } from "./index.js";
import "./watermark.js";
import "./v4.js";
import "vue";
class ChartModel extends ElementModel {
  constructor(data) {
    super(data);
    this.$loaded = false;
    this.colorType = this.colorType || 0;
    this.scales = this.scales || {};
  }
}
var ChartElement$1 = `<div
    class="editor-element"
    :class="[
        'editor-element-' + model.type,
        model.lock ? 'editor-element-lock' : '',
        model.hidden ? 'editor-element-hidden' : '',
        model.frozen ? 'editor-element-frozen' : '',
        model.$loaded ? '' : 'editor-element-loading',
        model.$selected ? 'editor-element-selected' : '',
        errorMessage ? 'editor-element-error' : ''
    ]"
    :style="[baseStyle, cssStyle]"
>
    <div
        class="element-main"
        :style="{
        width: model.width + 'px',
        height: model.height + 'px',
        transform: 'scale(' + global.zoom + ')',
        transformOrigin: 'left top'
    }"
    >
        <div
            class="chart-content"
            ref="chart"
            :style="{
                width: '100%',
                height: '100%'
            }"
        ></div>
    </div>

    <ElementCommon
        :element="model"
        :options="options"
        :global="global"
        :editor="editor"
        :layout="editor.currentLayout"
        :hideBlink="hideBlink"
        :isShowBlink="isShowBlink"
        :bgNinePatch="bgNinePatch"
    />
</div>
`;
const CHART_MODEL_MAIN_PROP = [
  "type",
  "chartType",
  "chartData",
  "metrics",
  "scales",
  "padding",
  "width",
  "height",
  "colorType",
  "colors",
  "shapeOpacity",
  "title",
  "legend",
  "label",
  "xAxis",
  "yAxis",
  "y2Axis",
  "settings",
  "dynamicContext"
];
const axisProps = [
  "enbale",
  "title.enable",
  "title.text",
  "title.fontSize",
  "title.color",
  "label.enable",
  "label.fontSize",
  "label.color",
  "label.textAlign"
];
const createProps = (prefix, props) => {
  if (props.length === 0)
    return prefix;
  return props.map((i) => prefix + i);
};
const SWITCH_PROP = [
  "title.enable",
  "title.text",
  "title.position",
  "title.fontSize",
  "title.color",
  "legend.enable",
  "legend.position",
  "legend.fontSize",
  "legend.color",
  "label.enable",
  "label.fontSize",
  "label.color",
  ...createProps("xAxis", axisProps),
  ...createProps("yAxis", axisProps),
  ...createProps("y2Axis", axisProps),
  "colorType",
  "colors",
  "shapeOpacity",
  "lockData",
  "chartData",
  "scales",
  "metrics",
  "animations"
];
function differenceDeep(object, base) {
  return lodash.exports.transform(object, function(result, value, key) {
    if (!lodash.exports.isEqual(value, base[key])) {
      result[key] = lodash.exports.isPlainObject(value) && lodash.exports.isPlainObject(base[key]) ? differenceDeep(value, base[key]) : value;
    }
  }, {});
}
function toPathsDeep(object) {
  return lodash.exports.transform(object, (paths, source, key) => {
    if (lodash.exports.isPlainObject(source)) {
      paths.push.apply(paths, toPathsDeep(source).map((i) => key + "." + i));
    } else {
      paths.push(key);
    }
    return paths;
  }, []);
}
function createDbClickEvent(type) {
  return {
    "base.click": function click(event) {
      const { editor } = this;
      if (!editor || !editor.pointFromEvent || !editor.getElementByPoint) {
        return;
      }
      if (this.elementClickQueue == null) {
        this.elementClickQueue = [];
      }
      const point = editor.pointFromEvent(event);
      const element = editor.getElementByPoint(point.x, point.y);
      if (!element || element.type !== type) {
        this.elementClickQueue = [];
        return;
      }
      if (this.elementClickTimer) {
        clearTimeout(this.elementClickTimer);
        this.elementClickQueue.push(element);
        if (this.elementClickQueue.length > 1) {
          this.editor.$emit(`editor.${type}.dblclick`, element);
          this.elementClickQueue = [];
        }
      } else {
        this.elementClickQueue.push(element);
      }
      this.elementClickTimer = setTimeout(() => {
        this.elementClickQueue = [];
      }, 300);
    }
  };
}
function initChartModel(model) {
  return lodash.exports.cloneDeep(lodash.exports.pick(model, CHART_MODEL_MAIN_PROP));
}
const mustChangeKeyWeakMap = /* @__PURE__ */ new WeakMap();
function substituteModelKey(currentModel, subModel) {
  if (!mustChangeKeyWeakMap.has(currentModel))
    return;
  const mustChangeKeyMap = mustChangeKeyWeakMap.get(currentModel);
  mustChangeKeyWeakMap.delete(currentModel);
  mustChangeKeyWeakMap.set(subModel, mustChangeKeyMap);
}
function deleteModelKey(modelKey) {
  mustChangeKeyWeakMap.delete(modelKey);
}
function pickByPropPath(model, keyList) {
  const obj = {};
  keyList.forEach((path) => {
    const value = lodash.exports.get(model, path);
    if (value !== void 0) {
      lodash.exports.set(obj, path, value);
    }
  });
  return obj;
}
function diffAndSwitchModel({ currentModel, initialModel, changeModel }) {
  let mustChangeKeyMap = mustChangeKeyWeakMap.get(currentModel);
  if (!mustChangeKeyMap) {
    mustChangeKeyMap = /* @__PURE__ */ new Map();
    mustChangeKeyWeakMap.set(currentModel, mustChangeKeyMap);
  }
  const simpleModel = differenceDeep(pickByPropPath(currentModel, SWITCH_PROP), pickByPropPath(initialModel, SWITCH_PROP));
  const mustChangeKeyProp = new Set(mustChangeKeyMap.keys());
  mustChangeKeyProp.forEach((keyPath) => {
    if (!lodash.exports.has(simpleModel, keyPath)) {
      const value = lodash.exports.has(currentModel, keyPath) ? lodash.exports.get(currentModel, keyPath) : mustChangeKeyMap.get(keyPath);
      lodash.exports.set(simpleModel, keyPath, value);
    }
  });
  if (simpleModel.chartData || mustChangeKeyProp.has("chartData")) {
    simpleModel.metrics = currentModel.metrics;
    simpleModel.scales = currentModel.scales;
  }
  const COLOR_TYPE_KEY = "colorType";
  const COLOR_TYPE_DEFAYLT = 0;
  const currentColorType = lodash.exports.get(simpleModel, COLOR_TYPE_KEY, lodash.exports.get(currentModel, COLOR_TYPE_KEY, COLOR_TYPE_DEFAYLT));
  if (currentColorType !== lodash.exports.get(changeModel, COLOR_TYPE_KEY, COLOR_TYPE_DEFAYLT)) {
    delete simpleModel.colorType;
    delete simpleModel.colors;
  }
  const simpleChangeKeyProp = toPathsDeep(simpleModel);
  simpleChangeKeyProp.forEach((keyPath) => {
    if (!keyPath)
      return;
    mustChangeKeyMap.set(keyPath, lodash.exports.get(simpleModel, keyPath));
  });
  return lodash.exports.mergeWith({}, changeModel, simpleModel, function(objValue, srcValue, key) {
    if (lodash.exports.isArray(srcValue)) {
      return srcValue;
    }
    if (key === "metrics") {
      return srcValue;
    }
    if (objValue === null && lodash.exports.isObject(srcValue)) {
      return null;
    }
  });
}
var ChartElement = inherit(BaseElement, {
  name: "chart-element",
  template: ChartElement$1,
  props: ["editor", "global", "model", "options"],
  computed: {
    cssStyle() {
      const { rect } = this;
      const { padding, height, width } = rect;
      const [paddingT, paddingR, paddingB, paddingL] = padding;
      return {
        height: height + paddingT + paddingB + "px",
        width: width + paddingR + paddingL + "px"
      };
    },
    isShowAnimateControt() {
      const isSelected = this.editor.currentElement && this.editor.currentElement === this.model;
      const isDynamicChart = ["dynamicline", "dynamicbar"].includes(this.model.chartType);
      return isDynamicChart && isSelected;
    },
    isDynamicPaused() {
      const dynamicContext = this.model.dynamicContext;
      console.log(dynamicContext.dynamicPaused);
      return dynamicContext && dynamicContext.dynamicPaused !== void 0 ? dynamicContext.dynamicPaused : true;
    }
  },
  events: __spreadValues({}, createDbClickEvent("chart")),
  methods: {
    playAnimate() {
      this.callChartRenderFn("playAnimate");
    },
    pauseAnimate() {
      this.callChartRenderFn("pauseAnimate");
    },
    replayAnimate() {
      this.callChartRenderFn("replayAnimate");
    },
    initChartRender() {
      const container = this.$refs.chart;
      if (!this._isMounted && !container)
        return;
      this.destoryChart();
      return this.loadChartRenderSource().then((createChartRender) => {
        const chartModel = initChartModel(this.model);
        return createChartRender(container, chartModel);
      }).then((chart) => {
        this.$chartRender = chart;
        this.setColorScalesLenght();
        this.initWatchers();
        this.initEvents();
        return chart;
      }).catch((error) => {
        this.errorMessage = "\u6682\u4E0D\u652F\u6301\u8BE5\u7C7B\u578B\uFF0C\u8BF7\u8054\u7CFB\u5BA2\u670D";
        throw error;
      });
    },
    setColorScalesLenght() {
      const getColorScalesLenght_FnName = "getColorScalesLenght";
      const scalesLenght = this.callChartRenderFn(getColorScalesLenght_FnName);
      if (typeof scalesLenght === "number") {
        this.$set(this.model, "colorScalesLenght", scalesLenght);
      }
    },
    initWatchers() {
      this.unWatchers();
      const changeSizeThrottle = lodash.exports.throttle(() => this.callChartRenderFn("changeSize", this.model.width, this.model.height), 200);
      const normalDebounceTime = 200;
      const { changeChartData, changeScales, changeMetrics } = this.createDimChangeWatcher();
      const watcherCfgList = [
        {
          key: "model.colorType",
          watcherName: "changeColorType"
        },
        {
          key: "model.colors",
          watcherName: "changeColors"
        },
        {
          key: "model.title",
          watcherName: "changeTitle"
        },
        {
          key: "model.legend",
          watcherName: "changeLegend"
        },
        {
          key: "model.label",
          watcherName: "changeLabel"
        },
        {
          key: "model.settings",
          watcherName: "changeSettings"
        },
        {
          key: "model.xAxis",
          watcherName: "changexAxis"
        },
        {
          key: "model.yAxis",
          watcherName: "changeyAxis"
        },
        {
          key: "model.y2Axis",
          watcherName: "changey2Axis"
        },
        {
          key: "model.shapeOpacity",
          watcherName: "changeShapeOpacity"
        },
        {
          key: "model.chartData",
          watcher: changeChartData
        },
        {
          key: "model.scales",
          watcher: changeScales
        },
        {
          key: "model.metrics",
          watcher: changeMetrics
        },
        {
          key: "model.width",
          watcher: changeSizeThrottle
        },
        {
          key: "model.height",
          watcher: changeSizeThrottle
        }
      ];
      this.unWatcherList = watcherCfgList.map(({ key, watcher, watcherName }) => {
        if (typeof watcher !== "function" && watcherName) {
          watcher = lodash.exports.debounce((...agrs) => this.callChartRenderFn(watcherName, ...agrs), normalDebounceTime);
        }
        return this.$watch(key, watcher, {
          deep: true,
          immediate: false
        });
      });
    },
    initEvents() {
      if (this.__removeEvents) {
        this.__removeEvents();
      }
      const updateCurrentKey = ({ currentKey }) => {
        this.model.dynamicContext.dynamicPaused = false;
        this.model.dynamicContext.currentKey = currentKey;
      };
      const updateDynamicPaused = () => {
        this.model.dynamicContext.dynamicPaused = true;
      };
      this.$chartRender.on("dynamic:play", updateCurrentKey);
      this.$chartRender.on("dynamic:pause", updateDynamicPaused);
      this.__removeEvents = () => {
        this.$chartRender.off("dynamic:play", updateCurrentKey);
        this.$chartRender.off("dynamic:pause", updateCurrentKey);
        this.__removeEvents = null;
      };
    },
    createDimChangeWatcher() {
      const self = this;
      let _metricsChanged = false;
      const changeChartData = lodash.exports.debounce((chartData) => {
        if (!_metricsChanged) {
          self.callChartRenderFn("changeData", chartData, self.model.scales);
          self.setColorScalesLenght();
        }
      }, 100);
      const changeScales = lodash.exports.debounce((scales) => {
        if (!_metricsChanged) {
          self.callChartRenderFn("changeScales", scales);
        }
      }, 100);
      const changeMetrics = () => {
        _metricsChanged = true;
        setTimeout(() => {
          self.initChartRender();
          _metricsChanged = false;
        }, 200);
      };
      return {
        changeChartData,
        changeScales,
        changeMetrics
      };
    },
    unWatchers() {
      const unWatcherList = this.unWatcherList;
      if (Array.isArray(unWatcherList)) {
        unWatcherList.forEach((unWatcher) => {
          if (typeof unWatcher === "function") {
            unWatcher();
          }
        });
        this.unWatcherList = null;
      }
    },
    removeEvents() {
      if (this.__removeEvents) {
        this.__removeEvents();
        this.__removeEvents = null;
      }
    },
    getCanvas() {
      const dynamicContext = this.model.dynamicContext;
      if (dynamicContext && dynamicContext.dynamicPaused === false) {
        this.pauseAnimate();
      }
      return this.callChartRenderFn("getCanvas");
    },
    callChartRenderFn(fn, ...args) {
      const $chartRender = this.$chartRender;
      if ($chartRender && typeof $chartRender[fn] === "function") {
        return $chartRender[fn](...args);
      }
    },
    destoryChart() {
      this.callChartRenderFn("destroy");
      this.$chartRender = null;
    },
    loadChartRenderSource() {
      return import(
        /* webpackChunkName: "chart-render" */
        "./chart-render.js"
      ).then(function(n) {
        return n.c;
      }).then((m) => m.default);
    },
    load() {
      return this.loadChartRenderSource().then(() => Promise$1.delay(500));
    }
  },
  mounted() {
    this.initChartRender();
  },
  beforeDestroy() {
    this.unWatchers();
    this.removeEvents();
    this.destoryChart();
    deleteModelKey(this.model);
  }
});
var methods = {
  playAnimateChart(element) {
    const vm = this.getComponentById(element.$id);
    vm && vm.playAnimate();
  },
  pauseAnimateChart(element) {
    const vm = this.getComponentById(element.$id);
    vm && vm.pauseAnimate();
  },
  replayAnimateChart(element) {
    const vm = this.getComponentById(element.$id);
    vm && vm.replayAnimate();
  },
  changeChartEffect(element, {
    metrics,
    chartData,
    scales
  }) {
    element.metrics = metrics;
    element.scales = scales;
    element.chartData = chartData;
  },
  switchChart(chartElement, initialModel, changeModel, layout = this.currentLayout) {
    const editor = this;
    const elemData = diffAndSwitchModel({
      currentModel: chartElement,
      initialModel,
      changeModel
    });
    ["left", "top", "width", "height", "sceneId"].forEach((key) => {
      chartElement[key] && (elemData[key] = chartElement[key]);
    });
    const elem = editor.createElement(elemData);
    elem.metaInfo = chartElement.metaInfo;
    substituteModelKey(chartElement, elem);
    editor.removeElement(chartElement, layout);
    editor.addElement(elem, layout);
    editor.focusElement(elem, layout);
    editor.makeSnapshot("add_element", null, true);
    return elem;
  }
};
var index = {
  model: ChartModel,
  layoutComponent: ChartElement,
  methods
};
export { index as default };
