import { defineComponent, ref, computed, nextTick, watch, resolveComponent, createElementBlock, openBlock, normalizeClass, unref, createVNode, withCtx, createCommentVNode, Fragment, renderList, createBlock, createSlots, renderSlot, mergeProps, createElementVNode, createTextVNode, toDisplayString } from 'vue';
import { Form } from 'ant-design-vue';
import '../../../utils/index.mjs';
import './config/index.mjs';
import './components/key-value-item.vue.mjs';
import { createNamespace } from '../../../utils/create-namespace.mjs';
import { guid, hasValue, deepCompare } from '../../../utils/data.mjs';
import { getKeyValueItem, keyValueEmits, keyValueProps } from './config/key-value.mjs';
import _sfc_main$1 from './components/key-value-item.vue2.mjs';

"use strict";
var _sfc_main = /* @__PURE__ */ defineComponent({
  ...{ name: "LlKeyValue" },
  __name: "key-value",
  props: keyValueProps,
  emits: keyValueEmits,
  setup(__props, { expose: __expose, emit: __emit }) {
    const props = __props;
    const emits = __emit;
    const bem = createNamespace("key-value");
    const formItemContext = Form.useInjectFormItemContext();
    const innerValue = ref(
      !props.value || props.value && !props.value.length ? [{ key: null, value: null, guid: guid() }] : props.value.map((e) => {
        return {
          ...e,
          guid: guid()
        };
      })
    );
    const keyValueItems = ref({});
    const setKeyValueItems = (el, type) => {
      if (el) {
        keyValueItems.value[type] = el;
      }
    };
    const keyValueTypeDict = computed(() => {
      const obj = {};
      props.keyTypes.forEach((e) => {
        obj[e.value] = e.option;
      });
      return obj;
    });
    const validate = async () => {
      await nextTick();
      const validationPromises = Object.values(keyValueItems.value).map(
        async (item) => {
          try {
            await item.validate();
            return { item, valid: true };
          } catch (error) {
            console.error("Validation failed for item:", item, error);
            return { item, valid: false, error };
          }
        }
      );
      const validationResults = await Promise.all(validationPromises);
      const allValid = validationResults.every((result) => result.valid);
      const errors = validationResults.filter((result) => !result.valid);
      if (!allValid) {
        console.log("Validation errors:", errors);
        return { valid: false, errors };
      }
      return { valid: true };
    };
    const resetFields = async () => {
      await nextTick();
      for (const i of Object.values(keyValueItems.value)) {
        if (i) {
          i.resetFields();
        }
      }
    };
    const clearValidate = async () => {
      await nextTick();
      for (const i of Object.values(keyValueItems.value)) {
        if (i) {
          i.clearValidate();
        }
      }
    };
    const handleAddItem = async () => {
      const { valid } = await validate();
      if (!valid) return;
      innerValue.value.push(getKeyValueItem());
      emits("add", {
        index: innerValue.value.length - 1,
        item: innerValue.value[innerValue.value.length - 1],
        value: innerValue.value
      });
    };
    const handleDelete = (idx) => {
      if (innerValue.value.length === 1) {
        innerValue.value = [{ key: null, value: null, guid: guid() }];
      } else {
        innerValue.value.splice(idx, 1);
        emits("delete", idx);
      }
    };
    const getValue = (val) => {
      return val.filter((e) => hasValue(e.key) || hasValue(e.value)).map((e) => ({
        key: e.key,
        value: e.value
      }));
    };
    watch(
      () => props.value,
      (n) => {
        if (!n || n && !n.length) return;
        const copyInnerValue = getValue(innerValue.value);
        const copyPropsValue = getValue(n);
        if (deepCompare(copyInnerValue, copyPropsValue)) return;
        innerValue.value = [
          ...n && n.length > 0 ? n : props.keepLast ? [{ key: null, value: null, guid: guid() }] : n
        ].map((e) => {
          return {
            ...e,
            guid: guid()
          };
        });
      },
      {
        immediate: true,
        deep: true
      }
    );
    watch(
      () => innerValue.value,
      (val) => {
        const copyInnerValue = getValue(val);
        const copyPropsValue = getValue(props.value);
        if (deepCompare(copyInnerValue, copyPropsValue)) return;
        try {
          formItemContext.onFieldChange();
          emits("change", copyInnerValue);
          emits("update:value", copyInnerValue);
        } catch (error) {
          console.error(error);
        }
      },
      {
        deep: true
      }
    );
    __expose({
      validate,
      resetFields,
      clearValidate
    });
    return (_ctx, _cache) => {
      const _component_ll_icon = resolveComponent("ll-icon");
      const _component_ll_button = resolveComponent("ll-button");
      const _component_a_spin = resolveComponent("a-spin");
      return openBlock(), createElementBlock(
        "div",
        {
          class: normalizeClass(unref(bem).b())
        },
        [
          createVNode(_component_a_spin, {
            spinning: props.loading
          }, {
            default: withCtx(() => [
              innerValue.value.length > 0 ? (openBlock(), createElementBlock(
                "div",
                {
                  key: 0,
                  class: normalizeClass(unref(bem).e("list"))
                },
                [
                  (openBlock(true), createElementBlock(
                    Fragment,
                    null,
                    renderList(innerValue.value, (_item, idx) => {
                      return openBlock(), createBlock(_sfc_main$1, {
                        key: _item.guid,
                        ref_for: true,
                        ref: (el) => setKeyValueItems(el, _item.guid),
                        value: innerValue.value[idx],
                        "onUpdate:value": ($event) => innerValue.value[idx] = $event,
                        idx,
                        "key-label": props.keyLabel,
                        "value-label": props.valueLabel,
                        "key-value-type-dict": keyValueTypeDict.value,
                        "key-value-type": props.keyValueType,
                        "key-type": props.keyType,
                        "key-types": props.keyTypes,
                        "value-type": props.valueType,
                        values: innerValue.value,
                        disabled: props.disabled,
                        "disabled-value": props.disabledValue,
                        "disabled-key": props.disabledKey,
                        "disabled-delete": props.disabledDelete,
                        "keep-last": props.keepLast,
                        onDelete: ($event) => handleDelete(idx)
                      }, createSlots({
                        _: 2
                        /* DYNAMIC */
                      }, [
                        renderList(Object.keys(_ctx.$slots), (item) => {
                          return {
                            name: item,
                            fn: withCtx((data) => [
                              renderSlot(_ctx.$slots, item, mergeProps({ ref_for: true }, data || {}, { index: idx }))
                            ])
                          };
                        })
                      ]), 1032, ["value", "onUpdate:value", "idx", "key-label", "value-label", "key-value-type-dict", "key-value-type", "key-type", "key-types", "value-type", "values", "disabled", "disabled-value", "disabled-key", "disabled-delete", "keep-last", "onDelete"]);
                    }),
                    128
                    /* KEYED_FRAGMENT */
                  ))
                ],
                2
                /* CLASS */
              )) : createCommentVNode("v-if", true),
              createVNode(_component_ll_button, {
                class: normalizeClass(unref(bem).e("add")),
                loading: _ctx.loading,
                disabled: props.disabled || props.disabledAdd,
                onClick: handleAddItem
              }, {
                default: withCtx(() => [
                  createElementVNode(
                    "div",
                    {
                      class: normalizeClass(unref(bem).e("plus"))
                    },
                    [
                      !_ctx.loading ? (openBlock(), createBlock(_component_ll_icon, {
                        key: 0,
                        "icon-name": "icon-add",
                        class: normalizeClass(unref(bem).e("icon-add"))
                      }, null, 8, ["class"])) : createCommentVNode("v-if", true),
                      createTextVNode(
                        " " + toDisplayString(props.addText),
                        1
                        /* TEXT */
                      )
                    ],
                    2
                    /* CLASS */
                  )
                ]),
                _: 1
                /* STABLE */
              }, 8, ["class", "loading", "disabled"])
            ]),
            _: 3
            /* FORWARDED */
          }, 8, ["spinning"])
        ],
        2
        /* CLASS */
      );
    };
  }
});

export { _sfc_main as default };
//# sourceMappingURL=key-value.vue2.mjs.map
