"use strict";
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
require("../../../../../node_modules/element-plus/es/index.js");
;/* empty css                                                             */
;/* empty css                                                                   */
;/* empty css                                                                  */
;/* empty css                                                                  */
const Vue = require("vue");
const parseRouteParams = require("../../utils/parseRouteParams.js");
const calculate = require("../../utils/formulajs/calculate.js");
const eventFlowHandler = require("../../utils/eventFlow/eventFlowHandler.js");
;/* empty css                                                                 */
;/* empty css                                                                   */
;/* empty css                                                                   */
const common = require("../../utils/common.js");
;/* empty css                    */
const _pluginVue_exportHelper = require("../../../../../_virtual/_plugin-vue_export-helper.js");
;/* empty css                                                  */
;/* empty css                                                        */
;/* empty css                                                   */
;/* empty css                                                  */
;/* empty css                                                     */
;/* empty css                                                    */
;/* empty css                                                               */
;/* empty css                                                     */
;/* empty css                                                   */
;/* empty css                                                    */
;/* empty css                                                                 */
;/* empty css                                                                       */
const index = require("../../../../../node_modules/element-plus/es/components/dialog/index.js");
const index$1 = require("../../../../../node_modules/element-plus/es/components/button/index.js");
const index$2 = require("../../../../../node_modules/element-plus/es/components/message/index.js");
const _hoisted_1 = { class: "dialog-header-content" };
const _hoisted_2 = {
  key: 1,
  class: "component-error"
};
const _hoisted_3 = {
  key: 3,
  class: "empty-content"
};
const _sfc_main = {
  __name: "DialogRenderer",
  props: {
    // 弹层配置
    dialogConfig: {
      type: Object,
      required: true
    },
    // 是否显示
    modelValue: {
      type: Boolean,
      default: false
    },
    fieldsList: {
      type: Array,
      default: []
    },
    formData: {
      type: Object,
      default: {}
    },
    displayField: {
      type: String,
      default: ""
    },
    componentCtx: {
      type: Object,
      default: {}
    },
    instance: {
      type: Object,
      default: {}
    }
  },
  emits: [
    "update:modelValue",
    "confirm",
    "cancel",
    "selection-change",
    "form-submit"
  ],
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const dialogVisible = Vue.ref(false);
    const tableSelectionRows = Vue.ref([]);
    Vue.ref(null);
    const currentDialogConfig = Vue.computed(() => props.dialogConfig);
    const dialogWidth = Vue.computed(() => {
      var _a, _b;
      const size = ((_a = currentDialogConfig.value) == null ? void 0 : _a.dialogSize) || "standard";
      const sizeMap = {
        standard: "50%",
        small: "30%",
        large: "70%"
      };
      if (size === "custom") {
        return ((_b = currentDialogConfig.value) == null ? void 0 : _b.customWidth) || "50%";
      }
      return sizeMap[size] || "50%";
    });
    const contentStyle = Vue.computed(() => {
      var _a, _b;
      const size = (_a = currentDialogConfig.value) == null ? void 0 : _a.dialogSize;
      if (size === "custom" && ((_b = currentDialogConfig.value) == null ? void 0 : _b.customMaxHeight)) {
        return {
          maxHeight: currentDialogConfig.value.customMaxHeight,
          overflow: "auto"
        };
      }
      return {};
    });
    Vue.computed(() => {
      var _a;
      const configParams = ((_a = currentDialogConfig.value) == null ? void 0 : _a.dialogParams) || [];
      const paramsObj = {};
      configParams.forEach((param) => {
        paramsObj[param.paramName] = param.paramValue;
      });
      return { ...paramsObj };
    });
    const currentComponent = Vue.ref(null);
    Vue.watch(
      () => {
        return props.modelValue;
      },
      (val) => {
        dialogVisible.value = val;
        if (val) {
          common.loadComponentByPath(
            currentDialogConfig.value.componentPath,
            props.componentCtx.$router,
            currentComponent
          );
        }
      },
      {
        immediate: true
      }
    );
    Vue.watch(dialogVisible, (val) => {
      emit("update:modelValue", val);
    });
    const componentParams = Vue.computed(() => {
      var _a;
      const params = parseRouteParams.parseRouteParams(
        ((_a = currentDialogConfig.value) == null ? void 0 : _a.componentParams) || [],
        props.formData,
        props.fieldsList
      );
      return params;
    });
    const handleSubmit = (data) => {
      emit("confirm", data);
    };
    const handleClose = () => {
      dialogVisible.value = false;
    };
    const dialogTableRef = Vue.ref();
    const handleConfirm = async () => {
      var _a, _b, _c, _d, _e, _f, _g;
      const contentSource = (_a = currentDialogConfig.value) == null ? void 0 : _a.contentSource;
      if (contentSource === "table") {
        if (tableSelectionRows.value.length == 0) {
          index$2.ElMessage.error("数据未选择，请选择");
          return;
        }
        const formData = {};
        const displayFormat = currentDialogConfig.value.displayFormat;
        const displayValues = tableSelectionRows.value.map((row) => {
          const calcResult = calculate.calculate({
            text: displayFormat == null ? void 0 : displayFormat.text,
            marks: [],
            value: row,
            fieldsList: props.fieldsList
          });
          return calcResult;
        });
        if (props.displayField) {
          formData[props.displayField] = displayValues.join(",");
        } else {
          console.log("未配置参数字段: displayField");
        }
        const isRowDataAssignToForm = currentDialogConfig.value.isRowDataAssignToForm;
        if (isRowDataAssignToForm) {
          Object.assign(formData, tableSelectionRows.value[0]);
        }
        const fieldMapping = currentDialogConfig.value.fieldMapping;
        if ((fieldMapping == null ? void 0 : fieldMapping.length) > 0) {
          fieldMapping.forEach((item) => {
            const field = props.fieldsList.find((field2) => field2.id === item.field);
            if (field) {
              const values = tableSelectionRows.value.map((row) => row[item.value]);
              formData[field.fieldName] = values.join(",");
            }
          });
        }
        if (Object.keys(formData).length > 0) {
          (_d = (_c = (_b = props.componentCtx) == null ? void 0 : _b.$) == null ? void 0 : _c.exposed) == null ? void 0 : _d.setFormData(formData);
        }
        const callbackEventConfig = currentDialogConfig.value.callbackEventConfig;
        if (callbackEventConfig && Object.keys(callbackEventConfig).length > 0 && ((_e = callbackEventConfig == null ? void 0 : callbackEventConfig.next) == null ? void 0 : _e.id) != "end") {
          await eventFlowHandler.executeEventFlow({
            eventFlow: callbackEventConfig,
            fields: props.fieldsList,
            instance: props.instance,
            localConfig: ((_g = (_f = props.componentCtx) == null ? void 0 : _f.$) == null ? void 0 : _g.exposed.localConfig.value) || {},
            components: {
              // table: {
              //   $: {
              //     exposed: dialogTableRef.value,
              //   },
              // },
              form: props.componentCtx,
              table: props.componentCtx
            },
            row: props.formData,
            item: {}
          });
        }
        emit("confirm", tableSelectionRows.value);
      } else {
        emit("confirm");
      }
      dialogVisible.value = false;
    };
    const handleCancel = () => {
      emit("cancel");
      dialogVisible.value = false;
    };
    const initDialogParams = Vue.computed(() => {
      var _a;
      if (((_a = currentDialogConfig.value.dialogParams) == null ? void 0 : _a.length) > 0) {
        const params = parseRouteParams.parseRouteParams(
          currentDialogConfig.value.dialogParams,
          props.formData,
          props.fieldsList
        );
        return params;
      }
      return {};
    });
    __expose({
      // 打开弹层
      open: (params = {}) => {
        dialogVisible.value = true;
      },
      // 关闭弹层
      close: () => {
        dialogVisible.value = false;
      }
      // // 获取当前选中的数据（列表模式）
      // getSelection: () => {
      //   return tableRendererRef.value?.getSelection?.();
      // },
      // // 获取表单数据（表单模式）
      // getFormData: () => {
      //   return formRendererRef.value?.getFormData?.();
      // },
      // // 重置表单（表单模式）
      // resetForm: () => {
      //   formRendererRef.value?.resetForm?.();
      // },
    });
    function tableSelectionChange(selectionRows) {
      tableSelectionRows.value = selectionRows;
    }
    const subFormOption = Vue.ref({});
    const handleEvent = Vue.ref(null);
    const dialogFormRef = Vue.ref();
    function subFormLoaded(subOption) {
      subFormOption.value = subOption;
      const fieldsData = subFormOption.value.fieldsData.map((item) => {
        return item.component;
      });
      const hiddenFields = subFormOption.value.hiddenFields;
      const { handleEvent: createHandleEvent } = eventFlowHandler.useEventFlow({
        fields: [...fieldsData, ...hiddenFields],
        instance: props.instance,
        localConfig: subFormOption.value || {},
        components: {
          form: {
            $: {
              exposed: dialogFormRef.value
            }
          }
        },
        onSuccess: (result, row, item) => {
          dialogVisible.value = false;
        },
        onError: (error, row, item) => {
        }
      });
      handleEvent.value = createHandleEvent;
    }
    const subFormFooterBtns = Vue.computed(() => {
      const btnArr = [];
      currentDialogConfig.value.subFormFooterButtons.forEach((btnId) => {
        var _a, _b;
        const btn = (_b = (_a = subFormOption.value) == null ? void 0 : _a.pageFooterConfig) == null ? void 0 : _b.actions.find(
          (btn2) => btn2.id == btnId
        );
        if (btn) {
          btnArr.push(btn);
        }
      });
      return btnArr;
    });
    async function formFooterClick(button) {
      var _a;
      const formData = dialogFormRef.value.getFormData();
      await handleEvent.value(
        formData,
        button,
        (_a = button.eventConfig) == null ? void 0 : _a.find((item) => item.name == "Click")
      );
      emit("confirm");
    }
    return (_ctx, _cache) => {
      const _component_fec_table = Vue.resolveComponent("fec-table");
      const _component_fec_form = Vue.resolveComponent("fec-form");
      const _component_el_button = index$1.ElButton;
      const _component_el_dialog = index.ElDialog;
      return __props.dialogConfig.componentIsDialog ? (Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(currentComponent.value), Vue.mergeProps({
        key: 0,
        modelValue: dialogVisible.value,
        "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => dialogVisible.value = $event),
        width: dialogWidth.value,
        draggable: true,
        "close-on-click-modal": false,
        "append-to-body": ""
      }, componentParams.value, {
        formData: __props.formData,
        onClose: handleClose,
        onSubmit: handleSubmit
      }), null, 16, ["modelValue", "width", "formData"])) : (Vue.openBlock(), Vue.createBlock(_component_el_dialog, {
        key: 1,
        modelValue: dialogVisible.value,
        "onUpdate:modelValue": _cache[2] || (_cache[2] = ($event) => dialogVisible.value = $event),
        width: dialogWidth.value,
        draggable: true,
        "close-on-click-modal": false,
        "append-to-body": "",
        class: "fec-dialog-renderer"
      }, {
        header: Vue.withCtx(() => {
          var _a;
          return [
            Vue.createElementVNode("div", _hoisted_1, [
              Vue.createElementVNode("span", null, Vue.toDisplayString(((_a = currentDialogConfig.value) == null ? void 0 : _a.dialogTitle) || "弹层"), 1)
            ])
          ];
        }),
        footer: Vue.withCtx(() => {
          var _a, _b, _c;
          return [
            Vue.createVNode(_component_el_button, { onClick: handleCancel }, {
              default: Vue.withCtx(() => _cache[3] || (_cache[3] = [
                Vue.createTextVNode("取消")
              ])),
              _: 1
            }),
            ((_a = __props.dialogConfig) == null ? void 0 : _a.contentSource) === "table" ? (Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, { key: 0 }, [
              !__props.dialogConfig.isSubTableReadOnly && __props.dialogConfig.selectionMode != "none" ? (Vue.openBlock(), Vue.createBlock(_component_el_button, {
                key: 0,
                type: "primary",
                onClick: handleConfirm
              }, {
                default: Vue.withCtx(() => _cache[4] || (_cache[4] = [
                  Vue.createTextVNode("确定")
                ])),
                _: 1
              })) : Vue.createCommentVNode("", true)
            ], 64)) : Vue.createCommentVNode("", true),
            ((_b = __props.dialogConfig) == null ? void 0 : _b.contentSource) === "form" && ((_c = __props.dialogConfig) == null ? void 0 : _c.subFormMode) != "query" ? (Vue.openBlock(true), Vue.createElementBlock(Vue.Fragment, { key: 1 }, Vue.renderList(subFormFooterBtns.value, (btn) => {
              return Vue.openBlock(), Vue.createBlock(_component_el_button, {
                key: btn.id,
                type: "primary",
                onClick: ($event) => formFooterClick(btn)
              }, {
                default: Vue.withCtx(() => [
                  Vue.createTextVNode(Vue.toDisplayString(btn.label), 1)
                ]),
                _: 2
              }, 1032, ["onClick"]);
            }), 128)) : Vue.createCommentVNode("", true)
          ];
        }),
        default: Vue.withCtx(() => {
          var _a, _b, _c, _d, _e;
          return [
            Vue.createElementVNode("div", {
              class: Vue.normalizeClass(["dialog-content-wrapper", "fec-dialog-" + ((_a = __props.dialogConfig) == null ? void 0 : _a.contentSource)]),
              style: Vue.normalizeStyle(contentStyle.value)
            }, [
              ((_b = __props.dialogConfig) == null ? void 0 : _b.contentSource) === "table" ? (Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, { key: 0 }, [
                __props.dialogConfig.tableContent === "select" ? (Vue.openBlock(), Vue.createBlock(_component_fec_table, {
                  key: 0,
                  templateKey: __props.dialogConfig.subTableKey,
                  mode: __props.dialogConfig.subTableMode,
                  isDialog: "",
                  hasPagination: __props.dialogConfig.isSubTablePagination,
                  initHiddenData: initDialogParams.value,
                  readonly: __props.dialogConfig.isSubTableReadOnly,
                  selectMode: __props.dialogConfig.selectionMode,
                  onSelectionChange: tableSelectionChange,
                  ref_key: "dialogTableRef",
                  ref: dialogTableRef
                }, null, 8, ["templateKey", "mode", "hasPagination", "initHiddenData", "readonly", "selectMode"])) : __props.dialogConfig.tableContent === "custom" ? (Vue.openBlock(), Vue.createBlock(_component_fec_table, {
                  key: 1,
                  initOption: __props.dialogConfig.customTableConfig,
                  isDialog: "",
                  hasPagination: __props.dialogConfig.isSubTablePagination,
                  initHiddenData: initDialogParams.value,
                  readonly: __props.dialogConfig.isSubTableReadOnly,
                  selectMode: __props.dialogConfig.selectionMode,
                  onSelectionChange: tableSelectionChange,
                  ref_key: "dialogTableRef",
                  ref: dialogTableRef
                }, null, 8, ["initOption", "hasPagination", "initHiddenData", "readonly", "selectMode"])) : Vue.createCommentVNode("", true)
              ], 64)) : ((_c = __props.dialogConfig) == null ? void 0 : _c.contentSource) === "form" ? (Vue.openBlock(), Vue.createBlock(_component_fec_form, {
                key: 1,
                templateKey: __props.dialogConfig.subFormKey,
                isDialog: "",
                modelValue: initDialogParams.value,
                "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => initDialogParams.value = $event),
                onLoaded: subFormLoaded,
                initFormMode: __props.dialogConfig.subFormMode,
                ref_key: "dialogFormRef",
                ref: dialogFormRef
              }, null, 8, ["templateKey", "modelValue", "initFormMode"])) : ((_d = __props.dialogConfig) == null ? void 0 : _d.contentSource) === "component" ? (Vue.openBlock(), Vue.createElementBlock(Vue.Fragment, { key: 2 }, [
                currentComponent.value ? (Vue.openBlock(), Vue.createBlock(Vue.resolveDynamicComponent(currentComponent.value), Vue.normalizeProps(Vue.mergeProps({ key: 0 }, componentParams.value)), null, 16)) : (Vue.openBlock(), Vue.createElementBlock("div", _hoisted_2, " 组件加载失败，请检查组件路径: " + Vue.toDisplayString((_e = __props.dialogConfig) == null ? void 0 : _e.componentPath), 1))
              ], 64)) : (Vue.openBlock(), Vue.createElementBlock("div", _hoisted_3, "请配置弹层内容"))
            ], 6)
          ];
        }),
        _: 1
      }, 8, ["modelValue", "width"]));
    };
  }
};
const DialogRenderer = /* @__PURE__ */ _pluginVue_exportHelper.default(_sfc_main, [["__scopeId", "data-v-bb1d2a15"]]);
exports.default = DialogRenderer;
