import "../../../../../../node_modules/element-plus/es/index.mjs";
/* empty css                                                                */
/* empty css                                                                    */
/* empty css                                                                     */
import { getCurrentInstance, inject, computed, ref, watch, onMounted, createElementBlock, openBlock, Fragment, createVNode, mergeProps, toHandlers, createSlots, withCtx, createElementVNode, toDisplayString, createBlock, createCommentVNode, createTextVNode, unref } from "vue";
import { Decimal } from "../../../../../../node_modules/decimal.js/decimal.mjs";
/* empty css                                                                    */
/* empty css                                                                      */
/* empty css                                                                      */
import { openDialog } from "../../dialog/index.mjs";
/* empty css                                                     */
/* empty css                                                           */
/* empty css                                                      */
/* empty css                                                     */
/* empty css                                                        */
/* empty css                                                       */
/* empty css                                                                  */
/* empty css                                                        */
/* empty css                                                      */
/* empty css                                                       */
import api from "../../../api/index.mjs";
/* empty css                                                                      */
/* empty css                                                                          */
import { useEventFlow } from "../../../utils/eventFlow/eventFlowHandler.mjs";
/* empty css             */
import _export_sfc from "../../../../../../_virtual/_plugin-vue_export-helper.mjs";
import { ElInput } from "../../../../../../node_modules/element-plus/es/components/input/index.mjs";
import { ElButton } from "../../../../../../node_modules/element-plus/es/components/button/index.mjs";
const _hoisted_1 = { class: "prefix-content" };
const _hoisted_2 = { class: "suffix-content" };
const _sfc_main = /* @__PURE__ */ Object.assign({
  inheritAttrs: false
}, {
  __name: "Number",
  props: {
    config: {
      type: Object,
      required: true
    },
    modelValue: {
      type: [Number, String],
      default: null
    },
    placeholder: {
      type: String,
      default: ""
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    format: {
      type: String,
      default: "number"
      // number, wan, million, percentage
    },
    hasDecimalPlaces: {
      type: Boolean,
      default: false
    },
    decimalPlaces: {
      type: Number,
      default: 2
    },
    minValue: {
      type: Number
    },
    maxValue: {
      type: Number
    },
    prefix: {
      type: String,
      default: ""
    },
    suffix: {
      type: String,
      default: ""
    },
    suffixButton: {
      type: String,
      default: ""
    },
    suffixButtonName: {
      type: String,
      default: ""
    },
    suffixButtonConfig: {
      type: Array,
      default: []
    },
    suffixDialogId: {
      type: String,
      default: ""
    },
    formMode: {
      type: String,
      default: ""
    },
    dialogSource: {
      type: String,
      default: ""
    },
    selectionMode: {
      type: String,
      default: ""
    },
    displayFormatText: {
      type: String,
      default: ""
    },
    displayFormat: {
      type: Object,
      default: {}
    },
    fieldMapping: {
      type: Array,
      default: []
    },
    callbackEventConfig: {
      type: Object,
      default: {}
    }
  },
  emits: ["update:modelValue", "change"],
  setup(__props, { emit: __emit }) {
    const props = __props;
    const emit = __emit;
    const instance = getCurrentInstance();
    const formData = inject("formData", null);
    const localConfig = inject("localConfig", null);
    const fieldsData = inject("fieldsData", null);
    const hiddenFields = inject("hiddenFields", null);
    const formCtx = inject("formCtx", null);
    const fieldsList = [
      ...(fieldsData == null ? void 0 : fieldsData.value) || [],
      ...(hiddenFields == null ? void 0 : hiddenFields.value) || []
    ];
    const { getEventHandlers: createEventHandlers } = useEventFlow({
      fields: fieldsList,
      instance,
      localConfig: localConfig == null ? void 0 : localConfig.value,
      components: {
        form: formCtx
      }
    });
    const getEventHandlers = (row, item, eventConfig) => createEventHandlers(item, row, eventConfig);
    async function openSuffixDialog() {
      let dialog = null;
      if (props.dialogSource == "global") {
        const data = await api.getTemplateDialogById(
          ctx.$http,
          props.suffixDialogId
        );
        dialog = JSON.parse(data.config);
        dialog.id = data.id;
        dialog.name = data.name;
        dialog.selectionMode = props.selectionMode;
        dialog.displayFormat = props.displayFormat;
        dialog.displayFormatText = props.displayFormatText;
        dialog.fieldMapping = props.fieldMapping;
        dialog.callbackEventConfig = props.callbackEventConfig;
      } else if (props.dialogSource == "custom") {
        const dialogsConfig = localConfig.value.dialogs || [];
        dialog = dialogsConfig.find((item) => item.id == props.suffixDialogId);
      }
      if (dialog) {
        openDialog(
          props.config.fieldName,
          dialog,
          instance,
          formCtx,
          fieldsList,
          formData.value
        ).then((result) => {
          console.log("确定", result);
        }).catch(() => {
          console.log("取消");
        });
      } else {
        console.error(`对话框配置不存在:${props.suffixDialogId}`);
      }
    }
    function handleChange(val) {
      emit("change", val);
    }
    const precision = computed(() => {
      return props.hasDecimalPlaces ? props.decimalPlaces : 0;
    });
    const textValue = ref(0);
    const formatter = (value) => {
      if (showThousandsSeparator.value) {
        value = formatNumberWithComma(value);
      }
      return value;
    };
    const showThousandsSeparator = computed(() => {
      return props.format == "yuan" || props.format == "wan" || props.format == "million";
    });
    const parser = (value) => {
      let result = moneyCheck(value);
      if (precision.value > 0 && result.includes(".")) {
        const [intPart, decPart] = result.split(".");
        if (decPart && decPart.length > precision.value) {
          result = intPart + "." + decPart.slice(0, precision.value);
        }
      }
      return result;
    };
    const compValue = computed({
      get: () => {
        if (!props.modelValue && props.modelValue != 0) {
          emit("update:modelValue", 0);
        }
        return props.modelValue;
      },
      set: (val) => {
        emit("update:modelValue", val);
      }
    });
    const initTextValue = () => {
      if (!props.modelValue && props.modelValue !== 0) {
        textValue.value = "";
        return;
      }
      let displayValue = props.modelValue;
      switch (props.format) {
        case "wan":
          displayValue = numDiv(displayValue, 1e4);
          break;
        case "million":
          displayValue = numDiv(displayValue, 1e6);
          break;
        case "percentage":
          displayValue = numMulti(displayValue, 100);
          break;
        case "permillage":
          displayValue = numMulti(displayValue, 1e3);
          break;
        case "permillion":
          displayValue = numMulti(displayValue, 1e4);
          break;
      }
      if (props.format == "yuan" || props.format == "wan" || props.format == "million") {
        textValue.value = formatMoney(
          displayValue,
          precision.value,
          ".",
          ",",
          true
        );
      } else {
        textValue.value = Number(Number(displayValue).toFixed(precision.value));
      }
      if (!showThousandsSeparator.value) {
        textValue.value = delcommafy(textValue.value);
      }
    };
    watch(
      () => props.modelValue,
      (value) => {
        initTextValue();
      },
      { immediate: true }
    );
    const handleInput = (value) => {
      if (precision.value > 0) {
        const dotIndex = value.indexOf(".");
        if (dotIndex !== -1) {
          const afterDot = value.slice(dotIndex + 1);
          if (afterDot.length > precision.value) {
            textValue.value = value.slice(0, dotIndex + 1 + precision.value);
          }
        }
      }
    };
    const handleBlur = (event) => {
      let value = event.target.value;
      if (!value && value !== 0) {
        compValue.value = value;
        return;
      }
      let cleanValue = delcommafy(value.toString());
      let numValue = Number(cleanValue);
      if (isNaN(numValue)) return;
      numValue = Number(numValue.toFixed(precision.value));
      switch (props.format) {
        case "wan":
          numValue = numMulti(numValue, 1e4);
          break;
        case "million":
          numValue = numMulti(numValue, 1e6);
          break;
        case "percentage":
          numValue = numDiv(numValue, 100);
          break;
        case "permillage":
          numValue = numDiv(numValue, 1e3);
          break;
        case "permillion":
          numValue = numDiv(numValue, 1e4);
          break;
      }
      const effectiveMax = props.maxValue != null ? props.maxValue : 999999999999999;
      const effectiveMin = props.minValue != null ? props.minValue : -999999999999999;
      numValue = Math.max(effectiveMin, Math.min(effectiveMax, numValue));
      compValue.value = numValue;
      switch (props.format) {
        case "wan":
          textValue.value = numDiv(numValue, 1e4);
          break;
        case "million":
          textValue.value = numDiv(numValue, 1e6);
          break;
        case "percentage":
          textValue.value = numMulti(numValue, 100);
          break;
        case "permillage":
          textValue.value = numMulti(numValue, 1e3);
          break;
        case "permillion":
          textValue.value = numMulti(numValue, 1e4);
          break;
      }
      textValue.value = formatMoney(
        textValue.value,
        precision.value,
        ".",
        ",",
        true
      );
      if (!showThousandsSeparator.value) {
        textValue.value = delcommafy(textValue.value);
      }
    };
    function formatNumberWithComma(numValue) {
      if (isNaN(numValue) || numValue === null || numValue === void 0) {
        return numValue;
      }
      let numStr = numValue.toString();
      const endsWithDot = numStr.endsWith(".");
      const [integerPart, decimalPart] = numStr.split(".");
      const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      if (endsWithDot) {
        return `${formattedInteger}.`;
      } else if (decimalPart !== void 0) {
        return `${formattedInteger}.${decimalPart}`;
      } else {
        return formattedInteger;
      }
    }
    function formatMoney(number, decimals = 2, decPoint = ".", thousandsSep = ",", zeroFill = false) {
      if (!number) {
        return "0.00";
      }
      if (Number(number) < 0.01 && Number(number) > 0) {
        return number;
      }
      number = delcommafy(number);
      number = (number + "").replace(/[^0-9+-Ee.]/g, "");
      let n = !isFinite(+number) ? 0 : +number;
      let prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
      let sep = typeof thousandsSep === "undefined" ? "," : thousandsSep;
      let dec = typeof decPoint === "undefined" ? "." : decPoint;
      let s = "";
      let toFixedFix = function(n2, prec2) {
        let k = Math.pow(10, prec2);
        return "" + Math.round(numMulti(n2, k)) / k;
      };
      s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".");
      let re = /(-?\d+)(\d{3})/;
      while (re.test(s[0])) {
        s[0] = s[0].replace(re, "$1" + sep + "$2");
      }
      if (zeroFill) {
        if ((s[1] || "").length < prec) {
          s[1] = s[1] || "";
          s[1] += new Array(prec - s[1].length + 1).join("0");
        }
        if (s == "0") {
          s = "0.00";
        }
      }
      return s.join(dec);
    }
    function moneyCheck(num) {
      var str = num;
      var len1 = str.substr(0, 1);
      var len2 = str.substr(1, 1);
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      if (len1 == ".") {
        str = "";
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      if (len1 == "-") {
        str = str.substr(1, str.length - 1);
        str = len1 + str.replace(/[^\d^\.]+/g, "");
      } else {
        str = str.replace(/[^\d^\.]+/g, "");
      }
      return str;
    }
    function delcommafy(num) {
      if (!num) return num;
      num = num.toString();
      num = num.replace(/,/gi, "");
      return num;
    }
    function numMulti(num1, num2) {
      if (!num1) {
        num1 = 0;
      }
      if (!num2) {
        num2 = 0;
      }
      return new Decimal(num1).mul(new Decimal(num2)).toNumber();
    }
    function numDiv(num1, num2) {
      if (!num1) {
        num1 = 0;
      }
      if (!num2) {
        num2 = 0;
      }
      return new Decimal(num1).div(new Decimal(num2)).toNumber();
    }
    onMounted(() => {
      initTextValue();
    });
    return (_ctx, _cache) => {
      const _component_el_button = ElButton;
      const _component_el_input = ElInput;
      return openBlock(), createElementBlock(Fragment, null, [
        createVNode(_component_el_input, mergeProps({
          modelValue: textValue.value,
          "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => textValue.value = $event),
          type: "text",
          placeholder: __props.placeholder,
          disabled: __props.disabled,
          readonly: __props.readonly,
          formatter,
          parser,
          onBlur: handleBlur,
          onInput: handleInput
        }, toHandlers(__props.config.eventHandlers), {
          onChange: handleChange,
          style: { "width": "100%" }
        }), createSlots({ _: 2 }, [
          __props.prefix ? {
            name: "prefix",
            fn: withCtx(() => [
              createElementVNode("span", _hoisted_1, toDisplayString(__props.prefix), 1)
            ]),
            key: "0"
          } : void 0,
          __props.suffix ? {
            name: "suffix",
            fn: withCtx(() => [
              createElementVNode("span", _hoisted_2, toDisplayString(__props.suffix), 1)
            ]),
            key: "1"
          } : void 0,
          __props.formMode != "query" && __props.suffixButton && __props.suffixButton != "none" ? {
            name: "append",
            fn: withCtx(() => [
              __props.suffixButton == "dialog" ? (openBlock(), createBlock(_component_el_button, {
                key: 0,
                class: "suffixButton",
                onClick: openSuffixDialog
              }, {
                default: withCtx(() => _cache[2] || (_cache[2] = [
                  createTextVNode("选择")
                ])),
                _: 1
              })) : __props.suffixButton == "custom" ? (openBlock(), createBlock(_component_el_button, mergeProps({
                key: 1,
                class: "suffixButton"
              }, toHandlers(getEventHandlers(unref(formData), {}, __props.suffixButtonConfig))), {
                default: withCtx(() => [
                  createTextVNode(toDisplayString(__props.suffixButtonName), 1)
                ]),
                _: 1
              }, 16)) : createCommentVNode("", true)
            ]),
            key: "2"
          } : void 0
        ]), 1040, ["modelValue", "placeholder", "disabled", "readonly"]),
        createVNode(_component_el_input, {
          modelValue: compValue.value,
          "onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => compValue.value = $event),
          type: "hidden"
        }, null, 8, ["modelValue"])
      ], 64);
    };
  }
});
const _Number = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-01611195"]]);
export {
  _Number as default
};
