import "../../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                             */
/* empty css                                                                   */
/* empty css                                                                  */
/* empty css                                                                  */
import { ref, computed, watch, resolveComponent, createBlock, openBlock, resolveDynamicComponent, mergeProps, withCtx, createElementVNode, normalizeStyle, normalizeClass, createElementBlock, Fragment, createCommentVNode, normalizeProps, toDisplayString, createVNode, createTextVNode, renderList } from "vue";
import { parseRouteParams } from "../../utils/parseRouteParams.mjs";
import { calculate } from "../../utils/formulajs/calculate.mjs";
import { useEventFlow, executeEventFlow } from "../../utils/eventFlow/eventFlowHandler.mjs";
/* empty css                                                                 */
/* empty css                                                                   */
/* empty css                                                                   */
import { loadComponentByPath } from "../../utils/common.mjs";
/* empty css                    */
import _export_sfc from "../../../../../_virtual/_plugin-vue_export-helper.mjs";
/* empty css                                                  */
/* empty css                                                        */
/* empty css                                                   */
/* empty css                                                  */
/* empty css                                                     */
/* empty css                                                    */
/* empty css                                                               */
/* empty css                                                     */
/* empty css                                                   */
/* empty css                                                    */
/* empty css                                                                 */
/* empty css                                                                       */
import { ElDialog } from "../../../../../node_modules/element-plus/es/components/dialog/index.mjs";
import { ElButton } from "../../../../../node_modules/element-plus/es/components/button/index.mjs";
import { ElMessage } from "../../../../../node_modules/element-plus/es/components/message/index.mjs";
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 = ref(false);
    const tableSelectionRows = ref([]);
    ref(null);
    const currentDialogConfig = computed(() => props.dialogConfig);
    const dialogWidth = 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 = 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 {};
    });
    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 = ref(null);
    watch(
      () => {
        return props.modelValue;
      },
      (val) => {
        dialogVisible.value = val;
        if (val) {
          loadComponentByPath(
            currentDialogConfig.value.componentPath,
            props.componentCtx.$router,
            currentComponent
          );
        }
      },
      {
        immediate: true
      }
    );
    watch(dialogVisible, (val) => {
      emit("update:modelValue", val);
    });
    const componentParams = computed(() => {
      var _a;
      const params = 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 = 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) {
          ElMessage.error("数据未选择，请选择");
          return;
        }
        const formData = {};
        const displayFormat = currentDialogConfig.value.displayFormat;
        const displayValues = tableSelectionRows.value.map((row) => {
          const calcResult = 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 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 = computed(() => {
      var _a;
      if (((_a = currentDialogConfig.value.dialogParams) == null ? void 0 : _a.length) > 0) {
        const params = 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 = ref({});
    const handleEvent = ref(null);
    const dialogFormRef = 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 } = 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 = 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 = resolveComponent("fec-table");
      const _component_fec_form = resolveComponent("fec-form");
      const _component_el_button = ElButton;
      const _component_el_dialog = ElDialog;
      return __props.dialogConfig.componentIsDialog ? (openBlock(), createBlock(resolveDynamicComponent(currentComponent.value), 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"])) : (openBlock(), 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: withCtx(() => {
          var _a;
          return [
            createElementVNode("div", _hoisted_1, [
              createElementVNode("span", null, toDisplayString(((_a = currentDialogConfig.value) == null ? void 0 : _a.dialogTitle) || "弹层"), 1)
            ])
          ];
        }),
        footer: withCtx(() => {
          var _a, _b, _c;
          return [
            createVNode(_component_el_button, { onClick: handleCancel }, {
              default: withCtx(() => _cache[3] || (_cache[3] = [
                createTextVNode("取消")
              ])),
              _: 1
            }),
            ((_a = __props.dialogConfig) == null ? void 0 : _a.contentSource) === "table" ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
              !__props.dialogConfig.isSubTableReadOnly && __props.dialogConfig.selectionMode != "none" ? (openBlock(), createBlock(_component_el_button, {
                key: 0,
                type: "primary",
                onClick: handleConfirm
              }, {
                default: withCtx(() => _cache[4] || (_cache[4] = [
                  createTextVNode("确定")
                ])),
                _: 1
              })) : createCommentVNode("", true)
            ], 64)) : createCommentVNode("", true),
            ((_b = __props.dialogConfig) == null ? void 0 : _b.contentSource) === "form" && ((_c = __props.dialogConfig) == null ? void 0 : _c.subFormMode) != "query" ? (openBlock(true), createElementBlock(Fragment, { key: 1 }, renderList(subFormFooterBtns.value, (btn) => {
              return openBlock(), createBlock(_component_el_button, {
                key: btn.id,
                type: "primary",
                onClick: ($event) => formFooterClick(btn)
              }, {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(btn.label), 1)
                ]),
                _: 2
              }, 1032, ["onClick"]);
            }), 128)) : createCommentVNode("", true)
          ];
        }),
        default: withCtx(() => {
          var _a, _b, _c, _d, _e;
          return [
            createElementVNode("div", {
              class: normalizeClass(["dialog-content-wrapper", "fec-dialog-" + ((_a = __props.dialogConfig) == null ? void 0 : _a.contentSource)]),
              style: normalizeStyle(contentStyle.value)
            }, [
              ((_b = __props.dialogConfig) == null ? void 0 : _b.contentSource) === "table" ? (openBlock(), createElementBlock(Fragment, { key: 0 }, [
                __props.dialogConfig.tableContent === "select" ? (openBlock(), 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" ? (openBlock(), 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"])) : createCommentVNode("", true)
              ], 64)) : ((_c = __props.dialogConfig) == null ? void 0 : _c.contentSource) === "form" ? (openBlock(), 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" ? (openBlock(), createElementBlock(Fragment, { key: 2 }, [
                currentComponent.value ? (openBlock(), createBlock(resolveDynamicComponent(currentComponent.value), normalizeProps(mergeProps({ key: 0 }, componentParams.value)), null, 16)) : (openBlock(), createElementBlock("div", _hoisted_2, " 组件加载失败，请检查组件路径: " + toDisplayString((_e = __props.dialogConfig) == null ? void 0 : _e.componentPath), 1))
              ], 64)) : (openBlock(), createElementBlock("div", _hoisted_3, "请配置弹层内容"))
            ], 6)
          ];
        }),
        _: 1
      }, 8, ["modelValue", "width"]));
    };
  }
};
const DialogRenderer = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-bb1d2a15"]]);
export {
  DialogRenderer as default
};
