var G = Object.defineProperty;
var q = (o, a, i) => a in o ? G(o, a, { enumerable: !0, configurable: !0, writable: !0, value: i }) : o[a] = i;
var g = (o, a, i) => (q(o, typeof a != "symbol" ? a + "" : a, i), i);
import { EditFormModel as H, AppEntityModel as W } from "@ibiz-template/model";
import { useNamespace as L, useControlController as J, usePropsWatch as Q, getDatePickerProps as Z, getEditorEmits as ee } from "@ibiz-template/vue-util";
import { defineComponent as V, getCurrentInstance as te, ref as y, watch as U, h as e, onMounted as se } from "vue";
import { createUUID as $ } from "qx-util";
import { ViewMode as K, UIActionHandler as ae, PluginStaticResource as oe } from "@ibiz-template/runtime";
import { EditFormController as re, DatePickerEditorController as ie } from "@ibiz-template/controller";
import { ControlVO as ne, calcResPath as ce } from "@ibiz-template/service";
import R from "dayjs";
class le extends re {
  constructor() {
    super(...arguments);
    /**
     *   基础数据
     *
     * @author fangZhiHao
     * @date 2024-04-26 17:04:49
     * @type {IData}
     */
    g(this, "baseResData", []);
    /**
     *   对比数据
     *
     * @author fangZhiHao
     * @date 2024-04-26 17:04:49
     * @type {IData}
     */
    g(this, "compareResData", []);
    /**
     * 表单旧数据
     *
     * @author zk
     * @date 2023-12-20 11:12:43
     * @protected
     * @type {IData}
     * @memberof FormController
     */
    g(this, "oldData", new ne());
    /**
     * version数据
     *
     * @author fangZhiHao
     * @date 2024-04-26 16:04:37
     * @type {IData[]}
     */
    g(this, "versionData", []);
    /**
     *  对比数据
     *
     * @author fangZhiHao
     * @date 2024-04-26 16:04:37
     * @type {IData[]}
     */
    g(this, "comparisonArr", {});
    /**
     *  基础表格数据
     *
     * @author fangZhiHao
     * @date 2024-05-06 11:05:57
     * @type {IData[]}
     */
    g(this, "gridData", []);
    /**
     *  展示完全数据
     *
     * @author fangZhiHao
     * @date 2024-05-06 11:05:04
     * @type {IData[]}
     */
    g(this, "AllGridData", []);
    /**
     *  去除相同数据
     *
     * @author fangZhiHao
     * @date 2024-05-06 11:05:15
     * @type {IData[]}
     */
    g(this, "removeSameGridData", []);
    /**
     *  关系界面数据
     *
     * @author fangZhiHao
     * @date 2024-04-30 10:04:33
     * @type {IData}
     */
    g(this, "AlldruipartData", /* @__PURE__ */ new Map());
    /**
     *  关系界面数据长度
     *
     * @author fangZhiHao
     * @date 2024-05-06 11:05:56
     * @type {number}
     */
    g(this, "druipartDataSize", 0);
    /**
     *   关系界面实际数据
     *
     * @author fangZhiHao
     * @date 2024-05-06 11:05:13
     * @type {IData}
     */
    g(this, "newDruipartData", {});
  }
  /**
   * 加载数据
   *
   * @return {*}  {Promise<ControlVO>}
   * @memberof FormDataComparisonController
   */
  async loadGridData() {
    await this.startLoading();
    const i = this.model.source.M.getPSControlParam.ctrlParams, { BASEENTITY: r, COMPAREENTITY: c } = i, h = await ibiz.entityService.getService(r), f = await ibiz.entityService.getService(c), E = Object.assign({}, this.context.clone(), {
      [r.toLowerCase()]: this.params.base_version
    }), p = Object.assign({}, this.context.clone(), {
      [c.toLowerCase()]: this.params.compare_version
    }), C = await h.exec("Get", E, this.params), b = await f.exec(
      "Get",
      p,
      this.params
    );
    return this.isLoaded = !0, {
      baseData: C.data.data,
      compareData: b.data.data
    };
  }
  /**
   * 判断值是否为空
   *
   * @param {(string | IData[] | null | undefined)} value
   * @return {*}
   * @memberof FormDataComparisonController
   */
  isFalseyButNotEmpty(i) {
    return i == null || typeof i == "string" && i === "" || Array.isArray(i) && i.length === 0 || typeof i == "object" && Object.keys(i).length === 0;
  }
  /**
   * 比较两个值
   *
   * @param {IData} objA
   * @param {IData} objB
   * @return {*}
   * @memberof FormDataComparisonController
   */
  compareObjectValues(i, r) {
    return JSON.stringify(i) !== JSON.stringify(r);
  }
}
const de = V({
  name: "IBizFormDataComparison",
  props: {
    modelData: {
      type: H,
      required: !0
    },
    context: {
      type: Object,
      required: !0
    },
    params: {
      type: Object,
      default: () => ({})
    },
    enableAutoSave: {
      type: Boolean,
      required: !1
    }
  },
  setup(o) {
    const a = L("form-data-comparison"), {
      proxy: i
    } = te(), r = J(i, () => {
      const t = new le(o.modelData, o.context, o.params);
      return Q(i, "enableAutoSave", t.setEnableAutoSave.bind(t)), t;
    }), c = y(!0), h = y(!1), f = y({}), E = y({}), p = y([]), C = [], b = y([]), m = y([]), d = y([]), n = /* @__PURE__ */ new Map(), v = y(0), u = (t) => {
      const s = [];
      if (s.push(t), t && t.children) {
        const l = [];
        t.children.forEach((D) => {
          const F = u(D);
          l.push(...F);
        }), s.push(...l);
      }
      return s;
    }, w = u(o.modelData);
    C.push(...w);
    const N = (t) => {
      const s = r.details[t.source.name], l = e("not-supported-editor", {
        attrs: {
          modelData: t.editor
        }
      });
      return e("div", {
        class: [a.e("form-grid-item"), a.is("add", b.value.includes(t.source.name)), a.is("update", d.value.includes(t.source.name)), a.is("delete", m.value.includes(t.source.name))]
      }, [e("div", {
        class: a.em("form-grid-item", "name")
      }, [t.source.caption]), e("div", {
        class: a.em("form-grid-item", "left")
      }, [s.editorProvider ? e(s.editorProvider.formEditor, {
        props: {
          value: E.value[t.source.name],
          data: s.data,
          controller: s.editor,
          disabled: s.disabled,
          readonly: !0
        }
      }) : l]), e("div", {
        class: a.em("form-grid-item", "right")
      }, [s.editorProvider ? e(s.editorProvider.formEditor, {
        props: {
          value: f.value[t.source.name],
          data: s.data,
          controller: s.editor,
          disabled: s.disabled,
          readonly: !0
        }
      }) : l])]);
    }, A = (t, s) => {
      n.set(t.source.id, s), s.evt.on("mounted", () => {
        c.value && r.startLoading(), v.value += 1, s.call.refresh();
      }), s.evt.on("refreshed", () => {
        v.value -= 1, setTimeout(() => {
          c.value && r.endLoading();
        }, 500);
      });
    }, Y = (t) => {
      const s = C.find((M) => M.id === `${t.source.id}_srfcopy`), l = t.embedView.source.modelPath, D = s == null ? void 0 : s.embedView.source.modelPath, F = r.context.clone(), P = {
        base_version: o.params.base_version
      }, I = r.context.clone();
      Object.assign(I, {
        gysrlzy_info: o.params.compare_version,
        compare_version: o.params.compare_version
      });
      const B = {
        compare_version: o.params.compare_version
      }, O = f.value[t.source.userTag], k = E.value[s == null ? void 0 : s.source.userTag];
      let _ = !1, j = !1, z = !1;
      return r.isFalseyButNotEmpty(O) && !r.isFalseyButNotEmpty(k) ? _ = !0 : !r.isFalseyButNotEmpty(O) && r.isFalseyButNotEmpty(k) ? z = !0 : !r.isFalseyButNotEmpty(O) && !r.isFalseyButNotEmpty(k) && r.compareObjectValues(O, k) && (j = !0), e("div", {
        class: [a.e("druipart"), a.is("add", _), a.is("update", j), a.is("delete", z)]
      }, [e("div", {
        class: a.em("druipart", "caption")
      }, [t.source.caption]), e("div", {
        class: a.em("druipart", "left")
      }, [D && e("ViewShell", {
        attrs: {
          context: I,
          params: B,
          modal: {
            mode: K.EMBED
          },
          modelPath: D,
          noLoadDefault: !0,
          name: s == null ? void 0 : s.source.id
        },
        key: $(),
        on: {
          neuronInit: (M) => A(s, M)
        }
      })]), e("div", {
        class: a.em("druipart", "right")
      }, [l && e("ViewShell", {
        attrs: {
          context: F,
          params: P,
          modal: {
            mode: K.EMBED
          },
          modelPath: l,
          noLoadDefault: !0,
          name: t.source.id
        },
        key: $(),
        on: {
          neuronInit: (M) => A(t, M)
        }
      })])]);
    }, x = (t) => {
      const s = {
        modelData: t,
        controller: r.details[t.source.name]
      }, l = r.providers[t.source.name], D = e(l.component, {
        props: {
          ...s
        },
        key: t.id
      }), F = e(l.component, {
        props: {
          ...s
        },
        key: `compare_${t.id}`
      });
      return e("div", {
        class: a.e("mdctrl")
      }, [e("div", {
        class: a.em("mdctrl", "caption")
      }, [t.source.caption]), e("div", {
        class: a.em("mdctrl", "left")
      }, [D]), e("div", {
        class: a.em("mdctrl", "right")
      }, [F])]);
    }, T = (t) => {
      c.value = !1;
      const s = p.value.findIndex((l) => l === t.source.name);
      s > -1 ? p.value.splice(s, 1) : p.value.push(t.source.name);
    }, S = (t) => {
      if (!t.source.hidden) {
        if (t.source.detailType === "FORMPAGE")
          return e("div", {
            class: a.e("form-page")
          }, [t.children.map((s) => S(s))]);
        if (t.source.detailType === "FORMITEM") {
          const s = b.value.includes(t.source.name), l = m.value.includes(t.source.name), D = d.value.includes(t.source.name);
          return h.value && !s && !l && !D ? null : N(t);
        }
        if (t.source.detailType === "GROUPPANEL") {
          const s = p.value.includes(t.source.name);
          return e("div", {
            class: a.b("group")
          }, [e("div", {
            class: [a.be("group", "header"), a.is("hide-caption", !t.source.showCaption)]
          }, [e("div", {
            class: a.bem("group", "header", "name")
          }, [s ? e("i-icon", {
            class: a.bem("group", "header", "icon"),
            attrs: {
              type: "ios-arrow-forward",
              title: "展开"
            },
            on: {
              click: () => T(t)
            }
          }) : e("i-icon", {
            class: a.bem("group", "header", "icon"),
            attrs: {
              type: "ios-arrow-down",
              title: "收缩"
            },
            on: {
              click: () => T(t)
            }
          }), e("span", {
            class: a.bem("group", "header", "name-text")
          }, [t.source.caption || t.source.title])]), e("div", ["---"]), e("div", ["---"])]), e("div", {
            class: [a.be("group", "content"), a.is("collapse", s)]
          }, [t.children.map((l) => S(l))])]);
        }
        return t.source.detailType === "DRUIPART" && !t.source.name.endsWith("_srfcopy") ? Y(t) : t.source.detailType === "MDCTRL" ? x(t) : null;
      }
    }, X = (t, s) => {
      const l = [], D = [], F = [];
      return Object.keys(s).forEach((P) => {
        const I = t[P], B = s[P];
        r.isFalseyButNotEmpty(I) && !r.isFalseyButNotEmpty(B) && l.push(P), !r.isFalseyButNotEmpty(I) && !r.isFalseyButNotEmpty(B) && r.compareObjectValues(I, B) && D.push(P);
      }), Object.keys(t).forEach((P) => {
        if (!Object.prototype.hasOwnProperty.call(s, P) || r.isFalseyButNotEmpty(s[P])) {
          const I = t[P];
          r.isFalseyButNotEmpty(I) || F.push(P);
        }
      }), {
        added: l,
        modified: D,
        deleted: F
      };
    };
    return U(() => o.params, async () => {
      const t = await r.loadGridData();
      f.value = t.baseData, E.value = t.compareData;
      const {
        added: s,
        modified: l,
        deleted: D
      } = X(E.value, f.value);
      b.value = s, d.value = l, m.value = D;
    }, {
      immediate: !0
    }), {
      ns: a,
      c: r,
      switchValue: h,
      druipartNum: v,
      renderEditor: N,
      renderByDetailType: S
    };
  },
  render() {
    return this.c.complete ? e("control-layout", {
      attrs: {
        modelData: this.c.model
      }
    }, [e("div", {
      class: this.ns.b()
    }, [e("div", {
      class: this.ns.e("top")
    }, [e("div", {
      class: this.ns.e("top-hidesame-content")
    }, [e("div", {
      class: this.ns.e("top-hidesame-content-left")
    }, ["隐藏相同项 ", e("i-switch", {
      model: {
        value: this.switchValue,
        callback: (o) => {
          this.switchValue = o;
        }
      }
    })]), e("div", {
      class: this.ns.e("top-hidesame-content-right")
    }, [e("div", {
      class: this.ns.e("top-hidesame-content-right-item")
    }, ["新增", e("div", {
      class: this.ns.e("top-hidesame-content-right-item-add")
    })]), e("div", {
      class: this.ns.e("top-hidesame-content-right-item")
    }, ["修改", e("div", {
      class: this.ns.e("top-hidesame-content-right-item-change")
    })]), e("div", {
      class: this.ns.e("top-hidesame-content-right-item")
    }, ["删除", e("div", {
      class: this.ns.e("top-hidesame-content-right-item-delete")
    })])])]), e("div", {
      class: this.ns.e("top-content")
    }, [e("div", {
      class: this.ns.em("top-content", "attr")
    }, ["信息项"]), e("div", {
      class: [this.ns.em("top-content", "left")]
    }, ["更新前内容"]), e("div", {
      class: [this.ns.em("top-content", "right")]
    }, ["更新后内容"])])]), e("div", {
      class: this.ns.e("content")
    }, [this.modelData.children.map((o) => this.renderByDetailType(o))])])]) : null;
  }
});
const ue = V({
  name: "CustomDataImport",
  props: {
    templateUrl: {
      type: String,
      required: !0
    },
    importUrl: {
      type: String,
      required: !0
    },
    dismiss: {
      type: Function
    }
  },
  setup(o, {
    emit: a
  }) {
    const i = L("data-import"), r = y(), c = y({
      state: "ready",
      message: "",
      rowError: []
    }), h = y(""), f = async (m) => {
      const d = new FormData(), n = R(h.value).format("YYYY-MM");
      d.append("file", m), d.append("ny", n);
      try {
        const v = await ibiz.net.request(o.importUrl, {
          method: "post",
          data: d,
          headers: {
            "Content-Type": "multipart/form-data"
          }
        });
        c.value.state = "success", c.value.message = "导入成功";
        const {
          errorinfo: u,
          success: w,
          total: N
        } = v.data, A = N ? Number(N) : 0, Y = w ? Number(w) : 0, x = N - w;
        c.value.message = `共计导入数据 ${A} 条，错误[${x}]，成功[${Y}]`, u && Object.keys(u).length > 0 && (c.value.rowError = [], Object.keys(u).forEach((T) => {
          c.value.rowError.push({
            index: Number(T) + 1,
            info: u[T].errorInfo
          });
        }));
      } catch (v) {
        c.value.state = "fail", c.value.message = `导入失败！${v.message}`;
      }
    }, E = (m) => {
      const d = m.target;
      if (!d.files)
        return;
      const n = d.files[0];
      d.value = null, f(n);
    }, p = async () => {
      var d;
      const m = await ibiz.net.request(o.templateUrl, {
        responseType: "blob"
      });
      if (m.status === 200) {
        let n = ((d = m.headers["content-disposition"].split(";").find((w) => w.indexOf("filename=") !== -1)) == null ? void 0 : d.slice(9)) || "";
        n = decodeURIComponent(n);
        const v = new Blob([m.data], {
          type: "application/vnd.ms-excel"
        }), u = document.createElement("a");
        u.download = n, u.style.display = "none", u.href = URL.createObjectURL(v), document.body.appendChild(u), u.click(), URL.revokeObjectURL(u.href), document.body.removeChild(u);
      }
    }, C = () => {
      r.value.click();
    }, b = () => {
      var m;
      a("close", {
        ok: !1,
        data: {}
      }), (m = o.dismiss) == null || m.call(o, {
        ok: !1,
        data: {}
      });
    };
    return se(() => {
      h.value = R().format("YYYY年MM月");
    }), {
      ns: i,
      curDate: h,
      onLinkClick: p,
      selectFile: C,
      onCancelButtonClick: b,
      onFileChange: E,
      inputUpLoad: r,
      message: c
    };
  },
  render() {
    return e("div", {
      class: [this.ns.b(), this.ns.is("custom", !0)]
    }, [e("input", {
      ref: "inputUpLoad",
      attrs: {
        type: "file",
        accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      },
      style: "display: none",
      on: {
        change: this.onFileChange
      }
    }), e("div", {
      class: this.ns.e("caption")
    }, ["导入数据"]), e("div", {
      class: this.ns.e("date")
    }, [e("span", ["导入数据所属月份"]), e("i-datePicker", {
      attrs: {
        format: "yyyy年MM月",
        type: "month",
        clearable: !1
      },
      model: {
        value: this.curDate,
        callback: (o) => {
          this.curDate = o;
        }
      }
    })]), this.message.state === "ready" ? e("div", {
      class: this.ns.b("upload"),
      on: {
        click: this.selectFile
      }
    }, [e("img", {
      class: this.ns.be("upload", "img"),
      attrs: {
        src: "./assets/img/icon-import.svg"
      }
    }), e("span", {
      class: this.ns.be("upload", "text")
    }, ["单击此区域进行上传"])]) : e("div", {
      class: this.ns.b("message")
    }, [e("div", {
      class: this.ns.be("message", "title")
    }, ["导入结果"]), e("div", {
      class: this.ns.be("message", "content")
    }, [this.message.message]), this.message.rowError.length > 0 && [e("div", {
      class: this.ns.be("message", "title")
    }, ["错误信息"]), e("div", {
      class: this.ns.be("message", "content")
    }, [this.message.rowError.map((o) => e("div", [`第 ${o.index} 行：${o.info}`]))])]]), e("div", {
      class: this.ns.e("template-container")
    }, [e("div", {
      class: this.ns.e("template-description")
    }, ["下载导入模版，并按要求填写："]), e("div", {
      class: this.ns.e("template-link"),
      on: {
        click: this.onLinkClick
      }
    }, [e("i-icon", {
      attrs: {
        type: "ios-link"
      }
    }), "数据导入模板文件"])]), e("div", {
      class: this.ns.e("button-bar")
    }, [this.message.state !== "ready" && e("i-button", {
      on: {
        click: this.selectFile
      }
    }, ["重新上传"])])]);
  }
});
class me {
  constructor() {
    g(this, "component", "IBizFormDataComparison");
  }
}
class pe extends ae {
  async execAction(a, i, r, c) {
    const h = {}, f = a.getPSAppDataEntity();
    if (f) {
      f.isFill === !1 && await f.fill(!0);
      const E = new W(f);
      await E.init();
      const { resultContext: p } = await this.handleParams(
        a,
        i,
        r,
        c
      ), C = ibiz.resourcePathUtil.calcPaths(
        p,
        E.codeName
      ), b = ce(p, C);
      let m = `${b}/${E.deNamePlural}/importtemplate`, d = `${b}/${E.deNamePlural}/importdata2`;
      const n = a.getPSAppDEDataImport();
      n && (m += `?srfimporttag=${n.codeName}`, d += `?srfimporttag=${n.codeName}`);
      const v = ibiz.overlay.createModal(
        "CustomDataImport",
        {
          templateUrl: m,
          importUrl: d,
          dismiss: (u) => {
            v.dismiss(u);
          }
        },
        {
          width: "auto",
          placement: "center"
        }
      );
      return v.present(), await v.onWillDismiss(), {
        refresh: !0
      };
    }
    return h;
  }
}
class he {
  constructor() {
    g(this, "handler");
  }
  async getHandler() {
    return this.handler || (this.handler = new pe()), this.handler;
  }
}
const fe = new oe(import.meta.url);
const ve = V({
  name: "YearMonthPicker",
  props: Z(),
  emits: ee(),
  setup(o, {
    emit: a
  }) {
    const i = L("date-picker"), r = o.controller, c = r.model, h = y("date"), f = y("yyyy-MM-dd"), E = y(!1);
    switch (c.editorType) {
      case "DATEPICKEREX":
      case "DATEPICKEREX_NOTIME":
        h.value = "date";
        break;
      case "DATEPICKEREX_NODAY":
      case "DATEPICKEREX_NODAY_NOSECOND":
        E.value = !0, h.value = "time";
        break;
      case "DATEPICKEREX_HOUR":
      case "DATEPICKEREX_MINUTE":
      case "DATEPICKEREX_SECOND":
      case "DATEPICKEREX_NOSECOND":
      case "DATEPICKER":
      default:
        h.value = "datetime";
    }
    const p = r.valueFormat;
    if (p) {
      p === "YYYY-MM" ? h.value = "month" : p === "YYYY" && (h.value = "year");
      const n = p.replace("YYYY", "yyyy").replace("DD", "dd");
      f.value = n;
    }
    c.editorParams.formatText && (f.value = c.editorParams.formatText.replace("YYYY", "yyyy").replace("DD", "dd"));
    const C = y();
    U(() => o.value, (n, v) => {
      n && n !== v && (C.value = R(n).format(p));
    }, {
      immediate: !0
    });
    const b = (n, v) => {
      const u = R(n.replace(/[年月]/g, "-")).format(p);
      console.log(u), a("change", u);
    }, m = (n) => {
      a("operate", n);
    }, d = y();
    return o.autoFocus && U(d, (n) => {
      n && n.$el.getElementsByTagName("input")[0].click();
    }), {
      ns: i,
      c: r,
      editorModel: c,
      type: h,
      format: f,
      formatValue: C,
      handleChange: b,
      onOpenChange: m,
      inputRef: d,
      isTimePicker: E
    };
  },
  render(o) {
    return o("div", {
      class: [this.ns.b(), this.disabled ? this.ns.m("disabled") : "", this.readonly ? this.ns.m("readonly") : ""]
    }, [[this.readonly && this.formatValue, !this.readonly && this.isTimePicker && o("ITimePicker", {
      ref: "inputRef",
      props: {
        ...this.c.customProps,
        value: this.value,
        type: this.type,
        format: this.format,
        placeholder: this.c.placeHolder,
        disabled: this.disabled,
        transfer: !0
      },
      on: {
        "on-change": this.handleChange,
        "on-open-change": this.onOpenChange
      }
    }), !this.readonly && !this.isTimePicker && o("ICalendarPicker", {
      ref: "inputRef",
      props: {
        ...this.c.customProps,
        value: this.value,
        type: this.type,
        format: this.format,
        placeholder: this.c.placeHolder,
        disabled: this.disabled,
        transfer: !0
      },
      on: {
        "on-change": this.handleChange,
        "on-open-change": this.onOpenChange
      }
    })]]);
  }
});
class ye {
  constructor() {
    g(this, "gridEditor", "YearMonthPicker");
    g(this, "formEditor", "YearMonthPicker");
  }
  async createController(a, i) {
    const r = new ie(a, i);
    return await r.init(), r;
  }
}
const Ne = {
  mateUrl: import.meta.url,
  install(o) {
    fe.loadStyle(["/style.css"]), o.component("IBizFormDataComparison", de), o.component("CustomDataImport", ue), o.component("YearMonthPicker", ve), ibiz.register.control.register(
      "EDITFORM_RENDER_FORM_DATA_COMPARISON",
      new me()
    ), ibiz.register.uiAction.register(
      "DEUIACTION_CUSTOM_IMPORT",
      new he()
    ), ibiz.register.editor.register(
      "DATEPICKEREX_NOTIME_YEAR_MONTH_PICKER",
      new ye()
    );
  }
};
export {
  Ne as default
};
