var F = Object.defineProperty;
var T = (l, d, e) => d in l ? F(l, d, { enumerable: !0, configurable: !0, writable: !0, value: e }) : l[d] = e;
var O = (l, d, e) => (T(l, typeof d != "symbol" ? d + "" : d, e), e);
import { defineComponent as I, getCurrentInstance as N, h as b } 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 q } from "@ibiz-template/controller";
import { createUUID as R } from "qx-util";
import { init as V } 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 o = e.slice(s + 1);
    o && l[e] !== void 0 && (d[o] = 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 P(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: o, maxValue: r, eChartsType: t, position: n } = e, a = {
      name: s,
      min: o,
      max: r
    };
    Object.assign(a, {
      type: t,
      position: n,
      ...w(
        P(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: o, maxValue: r, eChartsType: t, position: n } = e, a = {
      name: s,
      min: o,
      max: r
    };
    Object.assign(a, {
      type: t,
      position: n,
      ...w(
        P(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[]}
     */
    O(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 o = [];
    return await Promise.all(
      this.seriesList.map(async (r, t) => {
        var c, i, h, f;
        const n = {}, a = (i = (c = r.getCatalogPSCodeList) == null ? void 0 : c.call(r)) == null ? void 0 : i.codeName, m = (f = (h = r.getSeriesPSCodeList) == null ? void 0 : h.call(r)) == null ? void 0 : f.codeName;
        if (a) {
          const u = await ibiz.codeListService.get(
            a,
            e,
            s
          );
          if (u) {
            const g = /* @__PURE__ */ new Map();
            u.forEach((p) => {
              g.set(p.value, p.text);
            }), n.catalog = g;
          }
        }
        if (m) {
          const u = await ibiz.codeListService.get(
            m,
            e,
            s
          );
          if (u) {
            const g = /* @__PURE__ */ new Map();
            u.forEach((p) => {
              g.set(p.value, p.text);
            }), n.series = g;
          }
        }
        o[t] = n;
      })
    ), o;
  }
  /**
   * 生成数据集配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:37
   * @param {IPSDEChartSeries} series
   * @param {IData[]} data
   * @param {CodeListMap} map
   * @return {*}
   */
  generateDatasetOption(e, s, o) {
    var c;
    const r = {}, t = [];
    r.source = t;
    const n = e.catalogField.toLowerCase(), a = e.valueField.toLowerCase(), m = (c = e.seriesField) == null ? void 0 : c.toLowerCase();
    if (m) {
      const i = /* @__PURE__ */ new Set();
      s.forEach((h) => {
        i.add(h[m]);
      }), t.push([n, ...i]);
    } else
      t.push([n, a]);
    t.push(
      ...s.map((i) => t[0].map((h, f) => f === 0 ? (o && o.catalog ? o.catalog.get(i[h]) : i[h]) || "未定义" : m ? h === i[m] && i[a] || 0 : i[a] || 0))
    ), o && o.series && (t[0] = t[0].map((i, h) => {
      var f;
      return h === 0 ? i : ((f = o.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, u) => {
          u !== 0 && (t[i][u] += f);
        }), t.splice(h, 1), h -= 1);
    return r;
  }
  /**
   * 生成图表配置
   *
   * @author zhanghengfeng
   * @date 2023-04-03 16:04:49
   * @param {IData[]} data
   * @param {IContext} context
   * @param {IParams} params
   * @return {*}
   */
  async generateChartOption(e, s, o) {
    const r = {};
    r.dataset = [], r.series = [];
    const t = await this.getAllCodeListMap(s, o);
    return this.seriesList.forEach((n, a) => {
      if (n.eChartsType === "radar") {
        const { series: c, radar: i } = this.generateRadarSeriesOption(
          n,
          e,
          t[a]
        );
        Array.isArray(r.series) && r.series.push(...c), r.radar = i;
        return;
      }
      const m = this.generateDatasetOption(n, e, t[a]);
      if (Array.isArray(r.dataset) && r.dataset.push(m), n.eChartsType === "bar") {
        const c = this.generateBarSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(r.series) && r.series.push(...c);
      } else if (n.eChartsType === "line") {
        const c = this.generateLineSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(r.series) && r.series.push(...c);
      } else if (n.eChartsType === "pie") {
        const c = this.generatePieSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(r.series) && r.series.push(...c);
      } else if (n.eChartsType === "funnel") {
        const c = this.generateFunnelSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(r.series) && r.series.push(...c);
      } else if (n.eChartsType === "scatter") {
        const c = this.generateScatterSeriesOption(
          n,
          e,
          t[a],
          a
        );
        Array.isArray(r.series) && r.series.push(...c);
      } else
        throw new Error(`${n.eChartsType}类型的图表暂未实现`);
    }), r;
  }
  /**
   * 生成柱状图序列配置
   *
   * @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, o, r) {
    var u, g, p, C, S, x, A;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), m = e.valueField.toLowerCase(), c = (u = e.seriesField) == null ? void 0 : u.toLowerCase(), i = +((C = (p = (g = e.M) == null ? void 0 : g.getPSChartSeriesEncode) == null ? void 0 : p.getPSChartXAxis) == null ? void 0 : C.id) || 0, h = +((A = (x = (S = e.M) == null ? void 0 : S.getPSChartSeriesEncode) == null ? void 0 : x.getPSChartYAxis) == null ? void 0 : A.id) || 0, f = {};
    if (c) {
      const E = /* @__PURE__ */ new Set();
      s.forEach((L) => {
        const v = L[c];
        E.add(o && o.series && o.series.get(v) || v);
      }), t.push(
        ...[...E].map((L) => ({
          type: n,
          xAxisIndex: i,
          yAxisIndex: h,
          name: L,
          datasetIndex: r,
          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: r,
        encode: {
          x: a,
          y: m
        },
        ...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, o, r) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), m = 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((u) => {
        const g = u[c];
        f.add(o && o.series && o.series.get(g) || g);
      }), t.push(
        ...[...f].map((u) => ({
          type: n,
          name: u,
          datasetIndex: r,
          encode: {
            x: a,
            y: u
          },
          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: r,
        encode: {
          x: a,
          y: m
        },
        ...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, o, r) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), m = 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((u) => {
        const g = u[c];
        f.add(o && o.series && o.series.get(g) || g);
      }), t.push(
        ...[...f].map((u) => ({
          type: n,
          name: u,
          datasetIndex: r,
          encode: {
            itemName: a,
            value: u
          },
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: r,
        encode: {
          itemName: a,
          value: m
        },
        ...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, o, r) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), m = 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((u) => {
        const g = u[c];
        f.add(o && o.series && o.series.get(g) || g);
      }), t.push(
        ...[...f].map((u) => ({
          type: n,
          name: u,
          datasetIndex: r,
          encode: {
            itemName: a,
            value: u
          },
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: r,
        encode: {
          itemName: a,
          value: m
        },
        ...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, o, r) {
    var h;
    const t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), m = 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((u) => {
        const g = u[c];
        f.add(o && o.series && o.series.get(g) || g);
      }), t.push(
        ...[...f].map((u) => ({
          type: n,
          name: u,
          datasetIndex: r,
          encode: {
            x: a,
            y: u
          },
          ...w(
            i,
            y(e.userParams)
          )
        }))
      );
    } else
      t.push({
        type: n,
        name: e.caption || e.id,
        datasetIndex: r,
        encode: {
          x: a,
          y: m
        },
        ...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, o) {
    var g;
    const r = [], t = [], n = e.eChartsType, a = e.catalogField.toLowerCase(), m = 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 p = /* @__PURE__ */ new Set();
      s.forEach((C) => {
        p.add(C[c]);
      }), t.push([a, ...p]);
    } else
      t.push([a, m]);
    t.push(
      ...s.map((p) => t[0].map((C, S) => S === 0 ? (o && o.catalog ? o.catalog.get(p[C]) : p[C]) || "未定义" : c ? C === p[c] ? p[m] : 0 : p[m]))
    ), o && o.series && (t[0] = t[0].map((p, C) => {
      var S;
      return C === 0 ? p : ((S = o.series) == null ? void 0 : S.get(p)) || p;
    }));
    for (let p = 1; p < t.length; p++)
      for (let C = p + 1; C < t.length; C++)
        t[C][0] === t[p][0] && (t[C].forEach((S, x) => {
          x !== 0 && (t[p][x] += S);
        }), t.splice(C, 1), C -= 1);
    const h = t[0].slice(1).map((p, C) => t.slice(1).map((S) => S[C + 1]));
    r.push({
      type: n,
      name: e.caption || e.id,
      data: h,
      ...w(i, y(e.userParams))
    });
    let f = -1 / 0;
    h.forEach((p) => {
      p.forEach((C) => {
        +C > f && (f = +C);
      });
    });
    const u = t.slice(1).map((p) => ({
      name: p[0],
      max: f
    }));
    return {
      series: r,
      radar: {
        indicator: u
      }
    };
  }
}
class W extends q {
  constructor() {
    super(...arguments);
    /**
     * 图表实例
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:45
     * @type {(EChartsType | null)}
     */
    O(this, "chart", null);
    /**
     * 图表id
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:22
     * @type {string}
     */
    O(this, "chartId", `chart_${R()}`);
    /**
     * 图表静态配置
     *
     * @author zhanghengfeng
     * @date 2023-04-03 16:04:32
     * @type {EChartsOption}
     */
    O(this, "chartStaticOption", {});
    /**
     * 数据集合
     *
     * @author zhanghengfeng
     * @date 2023-04-07 16:04:34
     * @type {IData[]}
     */
    O(this, "items", []);
    /**
     * 请求参数
     *
     * @author zhanghengfeng
     * @date 2023-04-07 16:04:28
     */
    O(this, "queryParams", {
      page: 0,
      size: 1e3,
      query: ""
    });
  }
  /**
   * 创建图表神经系统
   *
   * @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 o = this.model.source.getPSDEChartSerieses();
    o && o.length && o[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: m, 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, u) => `
                    <div class='chart-tooltip-item'>
                      <div class='chart-tooltip-item-name'>${c.length === 2 ? m : f}</div>
                      <div class='chart-tooltip-item-number'>${i[u + 1]}</div>
                    </div>
                  `).join("")}
            `, h) : m;
      }
    });
    const r = this.model.source.getPSDEChartLegend();
    e.legend = r ? _(r) : {};
    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() {
    var e;
    await this.startLoading();
    try {
      const { data: s } = await this.service.fetch(this.context, {
        ...this.params,
        ...this.queryParams
      });
      if (Array.isArray(s) && s.length) {
        if (this.items = s, !this.chart) {
          const r = document.querySelector(`#${this.chartId}`);
          if (!r)
            throw new Error("未找到ECharts绘制容器元素");
          this.chart = V(r);
        }
        const o = await this.service.generateChartOption(
          s,
          this.context,
          this.params
        );
        this.chart.setOption({
          ...this.chartStaticOption,
          ...o
        });
      } else
        this.items = [], (e = this.chart) == null || e.clear();
    } 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 b("control-layout", {
        attrs: {
          modelData: this.c.model
        }
      }, [b("div", {
        class: this.ns.b()
      }, [b("div", {
        attrs: {
          id: this.c.chartId
        },
        class: this.ns.b("content")
      }), this.c.items.length ? null : b("div", {
        class: this.ns.b("empty-content")
      }, ["暂无数据"])])]);
  }
});
export {
  ae as default
};
