var P = Object.defineProperty;
var T = (l, d, e) => d in l ? P(l, d, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[d] = e;
var x = (l, d, e) => (T(l, typeof d != "symbol" ? d + "" : d, e), e);
import { defineComponent as I, getCurrentInstance as N, h as v } from "vue";
import { useControlController as z, useNamespace as D } from "@ibiz-template/vue-util";
import { ChartModel as M } from "@ibiz-template/model";
import { Neuron as j, ControlNerve as $, ControlController as R } from "@ibiz-template/controller";
import { createUUID as V } from "qx-util";
import { init as q } from "echarts";
import { mergeDeepRight as w } from "ramda";
import { ControlService as U } from "@ibiz-template/service";
class B extends j {
}
class X extends $ {
  createNeuron() {
    return new B(this.bindAbility());
  }
  bindAbility() {
    return {
      ...super.bindAbility(),
      load: this.controller.load.bind(this.controller)
    };
  }
}
function y(l) {
  const d = {};
  return l && Object.keys(l).forEach((e) => {
    const s = e.indexOf(".");
    if (s === -1)
      return;
    const r = e.slice(s + 1);
    r && l[e] !== void 0 && (d[r] = JSON.parse(l[e]));
  }), d;
}
function Y(l) {
  var e;
  const d = {};
  if (l) {
    d.show = l.showTitle, d.text = l.title, d.subtext = l.subTitle;
    const s = (e = l.titlePos) == null ? void 0 : e.toLowerCase();
    s === "left" || s === "right" ? d.left = s : (s === "bottom" || s === "top") && (d.left = "center", d.top = s);
  }
  return d;
}
function _(l) {
  var e;
  const d = {};
  if (l) {
    d.show = l.showLegend;
    const s = (e = l.legendPos) == null ? void 0 : e.toLowerCase();
    s === "left" || s === "right" ? (d.left = s, d.top = "middle", d.orient = "vertical") : s === "bottom" && (d.top = s);
  }
  return d;
}
function F(l) {
  return {
    axisLabel: {
      formatter: (e) => l === 1 ? e.length > 4 ? `${e.slice(0, 4).split("").join(`
`)}
...` : e.split("").join(`
`) : l === 2 && e.length > 4 ? `${e.slice(0, 4)}...` : e,
      rotate: l === 2 ? 45 : 0
    }
  };
}
function H(l) {
  const d = [];
  return l && l.length && l.forEach((e) => {
    const { caption: s, minValue: r, maxValue: o, eChartsType: t, position: n } = e, a = {
      name: s,
      min: r,
      max: o
    };
    Object.assign(a, {
      type: t,
      position: n,
      ...w(
        F(e.dataShowMode),
        y(e.userParams)
      )
    }), d.push(a);
  }), d;
}
function J(l) {
  const d = [];
  return l && l.length && l.forEach((e) => {
    const { caption: s, minValue: r, maxValue: o, eChartsType: t, position: n } = e, a = {
      name: s,
      min: r,
      max: o
    };
    Object.assign(a, {
      type: t,
      position: n,
      ...w(
        F(e.dataShowMode),
        y(e.userParams)
      )
    }), d.push(a);
  }), d;
}
class K extends U {
  constructor(e) {
    super(e);
    /**
     * 序列列表
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:38
     * @type {IPSDEChartSeries[]}
     */
    x(this, "seriesList", []);
    const s = e.source.getPSDEChartSerieses();
    if (!s || !s.length)
      throw new Error("图表序列集合不能为空");
    this.seriesList = s;
  }
  /**
   * 获取数据
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:11
   * @param {IContext} context
   * @param {IParams} [params={}]
   * @return {*}  {Promise<IHttpResponse>}
   */
  async fetch(e, s = {}) {
    return await this.exec(this.model.fetchAction, e, s);
  }
  /**
   * 获取所有代码表映射
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:21
   * @param {IContext} context
   * @param {IParams} params
   * @return {*}
   */
  async getAllCodeListMap(e, s) {
    const r = [];
    return await Promise.all(
      this.seriesList.map(async (o, t) => {
        var c, i, h, f;
        const n = {}, a = (i = (c = o.getCatalogPSCodeList) == null ? void 0 : c.call(o)) == null ? void 0 : i.codeName, C = (f = (h = o.getSeriesPSCodeList) == null ? void 0 : h.call(o)) == null ? void 0 : f.codeName;
        if (a) {
          const p = await ibiz.codeListService.get(
            a,
            e,
            s
          );
          if (p) {
            const g = /* @__PURE__ */ new Map();
            p.forEach((u) => {
              g.set(u.value, u.text);
            }), n.catalog = g;
          }
        }
        if (C) {
          const p = await ibiz.codeListService.get(
            C,
            e,
            s
          );
          if (p) {
            const g = /* @__PURE__ */ new Map();
            p.forEach((u) => {
              g.set(u.value, u.text);
            }), n.series = g;
          }
        }
        r[t] = n;
      })
    ), r;
  }
  /**
   * 生成数据集配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:37
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @return {*}
   */
  generateDatasetOption(e, s, r) {
    var c;
    const o = {}, t = [];
    o.source = t;
    const n = e.catalogField.toLowerCase(), a = e.valueField.toLowerCase(), C = (c = e.seriesField) == null ? void 0 : c.toLowerCase();
    if (C) {
      const i = /* @__PURE__ */ new Set();
      s.forEach((h) => {
        i.add(h[C]);
      }), t.push([n, ...i]);
    } else
      t.push([n, a]);
    t.push(
      ...s.map((i) => t[0].map((h, f) => f === 0 ? (r && r.catalog ? r.catalog.get(i[h]) : i[h]) || "未定义" : C ? h === i[C] && i[a] || 0 : i[a] || 0))
    ), r && r.series && (t[0] = t[0].map((i, h) => {
      var f;
      return h === 0 ? i : ((f = r.series) == null ? void 0 : f.get(i)) || i;
    }));
    for (let i = 1; i < t.length; i++)
      for (let h = i + 1; h < t.length; h++)
        t[h][0] === t[i][0] && (t[h].forEach((f, p) => {
          p !== 0 && (t[i][p] += f);
        }), t.splice(h, 1), h -= 1);
    return o;
  }
  /**
   * 生成图表配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:49
   * @param {IData[]} data
   * @param {IContext} context
   * @param {IParams} params
   * @return {*}
   */
  async generateChartOption(e, s, r) {
    const o = {};
    o.dataset = [], o.series = [];
    const t = await this.getAllCodeListMap(s, r);
    return this.seriesList.forEach((n, a) => {
      if (n.eChartsType === "radar") {
        const { series: c, radar: i } = this.generateRadarSeriesOption(
          n,
          e,
          t[a]
        );
        Array.isArray(o.series) && o.series.push(...c), o.radar = i;
        return;
      }
      const C = this.generateDatasetOption(n, e, t[a]);
      if (Array.isArray(o.dataset) && o.dataset.push(C), n.eChartsType === "bar") {
        const c = this.generateBarSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(o.series) && o.series.push(...c);
      } else if (n.eChartsType === "line") {
        const c = this.generateLineSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(o.series) && o.series.push(...c);
      } else if (n.eChartsType === "pie") {
        const c = this.generatePieSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(o.series) && o.series.push(...c);
      } else if (n.eChartsType === "funnel") {
        const c = this.generateFunnelSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(o.series) && o.series.push(...c);
      } else if (n.eChartsType === "scatter") {
        const c = this.generateScatterSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(o.series) && o.series.push(...c);
      } else
        throw new Error(`${n.eChartsType}类型的图表暂未实现`);
    }), o;
  }
  /**
   * 生成柱状图序列配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:13
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @param {number} index
   * @return {*}
   */
  generateBarSeriesOption(e, s, r, o) {
    var p, g, u, m, S, O, A;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), C = e.valueField.toLowerCase(), c = (p = e.seriesField) == null ? void 0 : p.toLowerCase(), i = +((m = (u = (g = e.M) == null ? void 0 : g.getPSChartSeriesEncode) == null ? void 0 : u.getPSChartXAxis) == null ? void 0 : m.id) || 0, h = +((A = (O = (S = e.M) == null ? void 0 : S.getPSChartSeriesEncode) == null ? void 0 : O.getPSChartYAxis) == null ? void 0 : A.id) || 0, f = {};
    if (c) {
      const E = /* @__PURE__ */ new Set();
      s.forEach((L) => {
        const b = L[c];
        E.add(r && r.series && r.series.get(b) || b);
      }), t.push(
        ...[...E].map((L) => ({
          type: n,
          xAxisIndex: i,
          yAxisIndex: h,
          name: L,
          datasetIndex: o,
          encode: {
            x: a,
            y: L
          },
          ...w(
            f,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        xAxisIndex: i,
        yAxisIndex: h,
        name: e.caption || e.id,
        datasetIndex: o,
        encode: {
          x: a,
          y: C
        },
        ...w(
          f,
          y(e.userParams)
        )
      });
    return t;
  }
  /**
   * 生成折线图序列配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:32
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @param {number} index
   * @return {*}
   */
  generateLineSeriesOption(e, s, r, o) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), C = e.valueField.toLowerCase(), c = (h = e.seriesField) == null ? void 0 : h.toLowerCase(), i = {
      emphasis: {
        label: {
          fontSize: 20,
          show: !0
        }
      },
      label: {
        position: "top",
        show: !0
      }
    };
    if (c) {
      const f = /* @__PURE__ */ new Set();
      s.forEach((p) => {
        const g = p[c];
        f.add(r && r.series && r.series.get(g) || g);
      }), t.push(
        ...[...f].map((p) => ({
          type: n,
          name: p,
          datasetIndex: o,
          encode: {
            x: a,
            y: p
          },
          stack: e.M.stack ? e.id : void 0,
          step: e.M.step ? "middle" : !1,
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: o,
        encode: {
          x: a,
          y: C
        },
        ...w(
          i,
          y(e.userParams)
        )
      });
    return t;
  }
  /**
   * 生成饼图序列配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:44
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @param {number} index
   * @return {*}
   */
  generatePieSeriesOption(e, s, r, o) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), C = e.valueField.toLowerCase(), c = (h = e.seriesField) == null ? void 0 : h.toLowerCase(), i = {
      emphasis: {
        label: {
          fontSize: 20,
          show: !0
        }
      },
      label: {
        formatter: "{b}: {d}%({@age})",
        position: "outside",
        show: !0
      }
    };
    if (c) {
      const f = /* @__PURE__ */ new Set();
      s.forEach((p) => {
        const g = p[c];
        f.add(r && r.series && r.series.get(g) || g);
      }), t.push(
        ...[...f].map((p) => ({
          type: n,
          name: p,
          datasetIndex: o,
          encode: {
            itemName: a,
            value: p
          },
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: o,
        encode: {
          itemName: a,
          value: C
        },
        ...w(
          i,
          y(e.userParams)
        )
      });
    return t;
  }
  /**
   * 生成漏斗图序列配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:03
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @param {number} index
   * @return {*}
   */
  generateFunnelSeriesOption(e, s, r, o) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), C = e.valueField.toLowerCase(), c = (h = e.seriesField) == null ? void 0 : h.toLowerCase(), i = {
      emphasis: {
        label: {
          fontSize: 20,
          show: !0
        }
      },
      label: {
        formatter: "{b}: {d}%({@age})",
        position: "outside",
        show: !0
      }
    };
    if (c) {
      const f = /* @__PURE__ */ new Set();
      s.forEach((p) => {
        const g = p[c];
        f.add(r && r.series && r.series.get(g) || g);
      }), t.push(
        ...[...f].map((p) => ({
          type: n,
          name: p,
          datasetIndex: o,
          encode: {
            itemName: a,
            value: p
          },
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: o,
        encode: {
          itemName: a,
          value: C
        },
        ...w(
          i,
          y(e.userParams)
        )
      });
    return t;
  }
  /**
   * 生成散点图序列配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:25
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @param {number} index
   * @return {*}
   */
  generateScatterSeriesOption(e, s, r, o) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), C = e.valueField.toLowerCase(), c = (h = e.seriesField) == null ? void 0 : h.toLowerCase(), i = {
      emphasis: {
        label: {
          fontSize: 20,
          show: !0
        }
      },
      label: {
        position: "top",
        show: !0
      }
    };
    if (c) {
      const f = /* @__PURE__ */ new Set();
      s.forEach((p) => {
        const g = p[c];
        f.add(r && r.series && r.series.get(g) || g);
      }), t.push(
        ...[...f].map((p) => ({
          type: n,
          name: p,
          datasetIndex: o,
          encode: {
            x: a,
            y: p
          },
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: o,
        encode: {
          x: a,
          y: C
        },
        ...w(
          i,
          y(e.userParams)
        )
      });
    return t;
  }
  /**
   * 生成雷达图序列配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:47
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @return {*}
   */
  generateRadarSeriesOption(e, s, r) {
    var g;
    const o = [], t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), C = e.valueField.toLowerCase(), c = (g = e.seriesField) == null ? void 0 : g.toLowerCase(), i = {
      emphasis: {
        label: {
          fontSize: 20,
          show: !0
        }
      },
      label: {
        position: "top",
        show: !0
      }
    };
    if (c) {
      const u = /* @__PURE__ */ new Set();
      s.forEach((m) => {
        u.add(m[c]);
      }), t.push([a, ...u]);
    } else
      t.push([a, C]);
    t.push(
      ...s.map((u) => t[0].map((m, S) => S === 0 ? (r && r.catalog ? r.catalog.get(u[m]) : u[m]) || "未定义" : c ? m === u[c] ? u[C] : 0 : u[C]))
    ), r && r.series && (t[0] = t[0].map((u, m) => {
      var S;
      return m === 0 ? u : ((S = r.series) == null ? void 0 : S.get(u)) || u;
    }));
    for (let u = 1; u < t.length; u++)
      for (let m = u + 1; m < t.length; m++)
        t[m][0] === t[u][0] && (t[m].forEach((S, O) => {
          O !== 0 && (t[u][O] += S);
        }), t.splice(m, 1), m -= 1);
    const h = t[0].slice(1).map((u, m) => t.slice(1).map((S) => S[m + 1]));
    o.push({
      type: n,
      name: e.caption || e.id,
      data: h,
      ...w(i, y(e.userParams))
    });
    let f = -1 / 0;
    h.forEach((u) => {
      u.forEach((m) => {
        +m > f && (f = +m);
      });
    });
    const p = t.slice(1).map((u) => ({
      name: u[0],
      max: f
    }));
    return {
      series: o,
      radar: {
        indicator: p
      }
    };
  }
}
class W extends R {
  constructor() {
    super(...arguments);
    /**
     * 图表实例
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:45
     * @type {(EChartsType | null)}
     */
    x(this, "chart", null);
    /**
     * 图表id
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:22
     * @type {string}
     */
    x(this, "chartId", `chart_${V()}`);
    /**
     * 图表静态配置
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:32
     * @type {EChartsOption}
     */
    x(this, "chartStaticOption", {});
  }
  /**
   * 创建图表神经系统
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:24
   * @protected
   * @return {*}  {ChartNerve}
   */
  createNerve() {
    return new X(this);
  }
  /**
   * 初始化配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:41
   * @protected
   * @return {*}  {Promise<void>}
   */
  async onInit() {
    await super.onInit(), this.service = new K(this.model), await this.service.init(this.context), this.initChartStaticOption(), this.resizeChart = this.resizeChart.bind(this), window.addEventListener("resize", this.resizeChart);
  }
  /**
   * 重新渲染图表
   *
   * @author zhanghengfeng
   * @date 2023-04-03 18:04:35
   */
  resizeChart() {
    var e;
    (e = this.chart) == null || e.resize();
  }
  /**
   * 初始化图表静态配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:52
   */
  initChartStaticOption() {
    const e = {}, s = this.model.source.getPSDEChartTitle();
    e.title = s ? Y(s) : {}, e.tooltip = {
      show: !0
    };
    const r = this.model.source.getPSDEChartSerieses();
    r && r.length && r[0].eChartsType === "bar" && (e.grid = {
      top: 41,
      bottom: 5,
      left: 13,
      right: 13,
      containLabel: !0
    }, e.tooltip = {
      show: !0,
      padding: 0,
      backgroundColor: "rgba(255, 255, 255, 0)",
      borderWidth: 0,
      className: "chart-tooltip",
      borderRadius: 6,
      extraCssText: "box-shadow: none;",
      formatter: (a) => {
        const { seriesName: C, dimensionNames: c, value: i } = a, h = document.createElement("div");
        return h.classList.add("chart-tooltip-container"), Array.isArray(c) && Array.isArray(i) && c.length >= 2 && c.length === i.length ? (h.innerHTML = `
              <div class='chart-tooltip-title'>${i[0]}</div>
              ${c.slice(1).map((f, p) => `
                    <div class='chart-tooltip-item'>
                      <div class='chart-tooltip-item-name'>${c.length === 2 ? C : f}</div>
                      <div class='chart-tooltip-item-number'>${i[p + 1]}</div>
                    </div>
                  `).join("")}
            `, h) : C;
      }
    });
    const o = this.model.source.getPSDEChartLegend();
    e.legend = o ? _(o) : {};
    const t = this.model.source.getPSChartXAxises();
    e.xAxis = t ? H(t) : [];
    const n = this.model.source.getPSChartYAxises();
    e.yAxis = n ? J(n) : [], Object.assign(
      this.chartStaticOption,
      w(e, y(this.model.source.userParams))
    );
  }
  /**
   * 加载数据
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:13
   * @param {IParams} params
   */
  async load() {
    await this.startLoading();
    try {
      const { data: e } = await this.service.fetch(this.context, this.params);
      if (Array.isArray(e) && e.length) {
        if (!this.chart) {
          const r = document.querySelector(`#${this.chartId}`);
          if (!r)
            throw new Error("未找到ECharts绘制容器元素");
          this.chart = q(r);
        }
        const s = await this.service.generateChartOption(
          e,
          this.context,
          this.params
        );
        this.chart.setOption({
          ...this.chartStaticOption,
          ...s
        });
      }
    } finally {
      await this.endLoading();
    }
  }
  destroy() {
    var e;
    super.destroy(), (e = this.chart) == null || e.dispose(), window.removeEventListener("resize", this.resizeChart);
  }
}
function G(l, d, e, s = {}) {
  return z(l, () => new W(d, e, s));
}
const ae = I({
  name: "ChartControl",
  props: {
    modelData: {
      type: M,
      required: !0
    },
    context: {
      type: Object,
      required: !0
    },
    params: {
      type: Object,
      default: () => ({})
    }
  },
  setup(l) {
    const {
      proxy: d
    } = N(), e = D("chart"), s = G(d, l.modelData, l.context, l.params);
    return s.initChartStaticOption(), {
      c: s,
      ns: e
    };
  },
  render() {
    if (this.c.complete)
      return v("control-layout", {
        attrs: {
          modelData: this.c.model
        }
      }, [v("div", {
        class: this.ns.b()
      }, [v("div", {
        attrs: {
          id: this.c.chartId
        },
        class: this.ns.b("content")
      })])]);
  }
});
export {
  ae as default
};
