import { defineComponent, ref, reactive, onMounted, watchEffect, openBlock, createElementBlock, createElementVNode, createVNode, unref, mergeProps, createSlots, withCtx, createCommentVNode, renderSlot, createBlock, createTextVNode, toDisplayString, renderList } from 'vue';
import { uuid } from './property-editor.mjs';
import { VxeGrid } from 'vxe-table';
import { VxeInput } from 'vxe-pc-ui';
import { MeLoadJson } from '../../load-json/index.mjs';
import { MeSvgIcon } from '../../svg-icon/index.mjs';
import { MeButton } from '../../button/index.mjs';

"use strict";
const _hoisted_1 = {
  class: "me-property-editor",
  style: {}
};
const _hoisted_2 = {
  "auto-resize": "",
  style: { "width": "100%", "margin-top": "10px" }
};
const _hoisted_3 = { key: 1 };
const _hoisted_4 = { style: { "display": "flex", "align-items": "center", "position": "relative", "z-index": "10" } };
const _hoisted_5 = ["onClick"];
const __default__ = defineComponent({
  name: "me-property-editor"
});
var script = /* @__PURE__ */ defineComponent({
  ...__default__,
  props: {
    case: { type: Boolean, required: false, default: true },
    defaultData: { type: Array, required: false, default: () => [] },
    data: { type: null, required: false },
    columns: { type: Array, required: false, default: () => [] },
    title: { type: String, required: false, default: "\u5C5E\u6027" },
    extData: { type: Array, required: false, default: () => [] },
    showDefaultValue: { type: Boolean, required: false, default: true },
    showDefaultName: { type: Boolean, required: false, default: true },
    editDefaultName: { type: Boolean, required: false, default: true },
    editDefaultValue: { type: Boolean, required: false, default: true },
    rules: { type: null, required: false, default: () => {
    } },
    importJson: { type: Boolean, required: false, default: false },
    gridData: { type: Array, required: false }
  },
  setup(__props, { expose: __expose }) {
    const props = __props;
    const getTableData = () => {
      const $grid = gridRef.value;
      if ($grid) {
        const tableData = $grid.getFullData();
        return tableData;
      }
    };
    const gridRef = ref();
    const gridOptions = reactive({
      showOverflow: true,
      editConfig: {
        trigger: "click",
        mode: "cell"
      },
      columnConfig: {},
      rowConfig: {
        useKey: true,
        drag: true
      },
      /** @ts-ignore */
      class: "table-wrapper",
      editRules: {
        propertyName: [{ required: true, validator: checkName }],
        ...props.rules
      },
      rowDragConfig: {
        visibleMethod({ row }) {
          return !row.isDefault;
        }
      },
      tooltipConfig: {
        showAll: false
      },
      columns: [
        {
          field: "propertyName",
          title: `${props.title}\u540D`,
          editRender: props.editDefaultName ? { name: "input" } : false,
          slots: { edit: "name-edit", default: "name-default" },
          visible: props.showDefaultName
        },
        ...props.columns,
        {
          field: "propertyValue",
          title: `${props.title}\u503C`,
          editRender: props.editDefaultValue ? { name: "input" } : false,
          slots: { edit: "value-edit", default: "value-default" },
          visible: props.showDefaultValue
        },
        { width: 60, title: "\u64CD\u4F5C", slots: { default: "handle", header: "handle-header" } },
        { width: 60, dragSort: true }
      ],
      data: []
    });
    let id = 1;
    const handleAddSpec = () => {
      if (getTableData().length == 0) {
        id = 1;
      }
      gridRef.value.insertAt({ uuid: uuid(), propertyName: "\u5C5E\u6027\u540D" + id++, propertyValue: "" }, -1);
    };
    const removeRow = (row) => {
      const $grid = gridRef.value;
      if ($grid) {
        $grid.remove(row);
      }
    };
    const columnsSlot = ref();
    onMounted(() => {
      if (props.gridData) {
        gridOptions.data = props.gridData;
      }
      if (!props.defaultData.length) return;
      const data = props.defaultData.map((item) => {
        return {
          isDefault: true,
          ...item
        };
      });
      data.forEach((item) => {
        gridOptions.data?.push(item);
      });
    });
    watchEffect(() => {
      if (props.columns?.length) {
        const slots = props.columns.map((item) => item.slots).filter((item) => item);
        columnsSlot.value = slots;
      }
      if (props.extData?.length) {
        gridOptions.data = props.extData;
      } else {
        gridOptions.data = [];
      }
    });
    const validEvent = async () => {
      const confirmData = {};
      const $grid = gridRef.value;
      if ($grid) {
        const errMap = await $grid.validate(true);
        if (errMap) {
          console.log(errMap);
        } else {
          getTableData().forEach((item) => {
            confirmData[item.propertyName] = item.propertyValue;
          });
          return confirmData;
        }
      }
    };
    const getData = () => {
      return validEvent();
    };
    const getFullData = () => {
      return gridRef.value.getFullData();
    };
    function checkName({ cellValue, rule, rules, row, rowIndex, column, columnIndex }) {
      if (cellValue.trim() == "") {
        return new Error("\u5C5E\u6027\u540D\u4E0D\u80FD\u4E3A\u7A7A");
      }
      if (cellValue.includes(",")) {
        return new Error("\u5C5E\u6027\u540D\u4E0D\u80FD\u5305\u542B\u9017\u53F7");
      }
      for (let i = 0; i < getTableData().length; i++) {
        if (i !== rowIndex) {
          let rule2;
          if (props.case) {
            rule2 = cellValue.toLowerCase().trim() === getTableData()[i].propertyName.toLowerCase().trim();
          } else {
            rule2 = cellValue.trim() === getTableData()[i].propertyName.trim();
          }
          if (rule2) {
            return new Error("\u8BE5\u5C5E\u6027\u540D\u5DF2\u5B58\u5728");
          }
        }
      }
    }
    const loadData = (data, isHandle = false) => {
      if (!data) return;
      clearData();
      const arr = [];
      if (Array.isArray(data)) {
        data.forEach((item) => {
          for (const [key, value] of Object.entries(item)) {
            arr.push({
              propertyName: key,
              propertyValue: value,
              uuid: uuid(),
              isDefault: isHandle
            });
          }
        });
      } else {
        for (const [key, value] of Object.entries(data)) {
          arr.push({
            propertyName: key,
            propertyValue: value,
            uuid: uuid(),
            isDefault: isHandle
          });
        }
      }
      arr.forEach((item) => {
        gridOptions.data?.push(item);
      });
      console.log(gridOptions.data);
    };
    const loadDefaultData = (data) => {
      loadData(data, true);
    };
    const clearData = () => {
      gridOptions.data = [];
    };
    const check = async () => {
      const res = await gridRef.value.validate(true);
      return new Promise((resolve, reject) => {
        if (res) {
          reject(false);
        }
        resolve(true);
      });
    };
    __expose({
      loadData,
      getData,
      clearData,
      check,
      getFullData,
      loadDefaultData,
      gridRef
    });
    return (_ctx, _cache) => {
      return openBlock(), createElementBlock("div", _hoisted_1, [
        createElementVNode("div", _hoisted_2, [
          createVNode(
            unref(VxeGrid),
            mergeProps({ ..._ctx.$attrs, ...gridOptions }, {
              ref_key: "gridRef",
              ref: gridRef
            }),
            createSlots({
              "name-default": withCtx(({ row }) => [
                renderSlot(_ctx.$slots, "property-name", { row }, () => [
                  createTextVNode(
                    toDisplayString(row.propertyName),
                    1
                    /* TEXT */
                  )
                ])
              ]),
              "value-default": withCtx(({ row }) => [
                renderSlot(_ctx.$slots, "property-value", { row }, () => [
                  createTextVNode(
                    toDisplayString(row.propertyValue),
                    1
                    /* TEXT */
                  )
                ])
              ]),
              "handle-header": withCtx(({ row }) => [
                createElementVNode("div", _hoisted_4, [
                  createVNode(unref(MeButton), {
                    type: "primary",
                    size: "small",
                    style: { "margin-right": "10px" },
                    circle: "",
                    onClick: handleAddSpec
                  }, {
                    default: withCtx(() => [
                      createVNode(unref(MeSvgIcon), { name: "ri-add-line" })
                    ]),
                    _: 1
                    /* STABLE */
                  }),
                  renderSlot(_ctx.$slots, "header", {}, () => [
                    props.importJson ? (openBlock(), createBlock(unref(MeLoadJson), {
                      key: 0,
                      onChange: loadData,
                      data: getData
                    })) : createCommentVNode("v-if", true)
                  ])
                ])
              ]),
              handle: withCtx(({ row }) => [
                createElementVNode("div", null, [
                  !row.isDefault ? (openBlock(), createElementBlock("div", {
                    key: 0,
                    style: { "color": "#f56c6c", "line-height": "22px", "text-align": "center", "cursor": "pointer" },
                    onClick: ($event) => removeRow(row)
                  }, " \u5220\u9664 ", 8, _hoisted_5)) : createCommentVNode("v-if", true)
                ])
              ]),
              _: 2
              /* DYNAMIC */
            }, [
              props.editDefaultName ? {
                name: "name-edit",
                fn: withCtx(({ row }) => [
                  renderSlot(_ctx.$slots, "property-name-edit", { row }, () => [
                    !row.isDefault ? (openBlock(), createBlock(unref(VxeInput), {
                      key: 0,
                      modelValue: row.propertyName,
                      "onUpdate:modelValue": ($event) => row.propertyName = $event
                    }, null, 8, ["modelValue", "onUpdate:modelValue"])) : createCommentVNode("v-if", true),
                    row.isDefault ? (openBlock(), createElementBlock(
                      "span",
                      _hoisted_3,
                      toDisplayString(row.propertyName),
                      1
                      /* TEXT */
                    )) : createCommentVNode("v-if", true)
                  ])
                ]),
                key: "0"
              } : void 0,
              props.editDefaultValue ? {
                name: "value-edit",
                fn: withCtx(({ row }) => [
                  renderSlot(_ctx.$slots, "property-value-edit", { row }, () => [
                    createVNode(unref(VxeInput), {
                      modelValue: row.propertyValue,
                      "onUpdate:modelValue": ($event) => row.propertyValue = $event
                    }, null, 8, ["modelValue", "onUpdate:modelValue"])
                  ])
                ]),
                key: "1"
              } : void 0,
              renderList(columnsSlot.value, (item) => {
                return {
                  name: item.default,
                  fn: withCtx(({ row }) => [
                    renderSlot(_ctx.$slots, item.default, { row })
                  ])
                };
              }),
              renderList(columnsSlot.value, (item) => {
                return {
                  name: item.edit,
                  fn: withCtx(({ row }) => [
                    renderSlot(_ctx.$slots, item.edit, { row })
                  ])
                };
              })
            ]),
            1040
            /* FULL_PROPS, DYNAMIC_SLOTS */
          )
        ])
      ]);
    };
  }
});

export { script as default };
//# sourceMappingURL=property-editor.vue2.mjs.map
