import { defineComponent, toRefs, ref, computed, watch, resolveComponent, openBlock, createElementBlock, Fragment, unref, createBlock, withCtx, createVNode, createTextVNode, createElementVNode, toRaw, pushScopeId, popScopeId, nextTick, withDirectives, renderList, toDisplayString, vShow, isRef, createCommentVNode } from "vue";
import { I as cloneDeep, b7 as toString, i as icon, b8 as customizeHttp, d as goDialog, _ as _export_sfc, a2 as JSONParse, a1 as JSONStringify, b2 as RequestDataTypeEnum, aa as ChartFrameEnum, b9 as isArray } from "./index-e2623483.js";
import { T as TimelineTitleEnum, D as DataResultEnum } from "./index-dda8e899.js";
import { u as useTargetData } from "./useTargetData.hook-2b5299d6.js";
import { M as MonacoEditor } from "./EditorWorker-c209331a.js";
import { F as FileTypeEnum } from "./fileTypeEnum-d13b2cef.js";
const readFile = (file) => {
  return new Promise((resolve) => {
    try {
      const reader = new FileReader();
      reader.onload = (evt) => {
        if (evt.target) {
          resolve(evt.target.result);
        }
      };
      reader.readAsText(file);
    } catch (error) {
      window["$message"].error("文件读取失败！");
    }
  });
};
const downloadByA = (url, filename = (/* @__PURE__ */ new Date()).getTime(), fileSuffix) => {
  const ele = document.createElement("a");
  ele.download = `${filename}.${fileSuffix}`;
  ele.style.display = "none";
  ele.href = url;
  document.body.appendChild(ele);
  ele.click();
  document.body.removeChild(ele);
};
const downloadTextFile = (content, filename = (/* @__PURE__ */ new Date()).getTime(), fileSuffix) => {
  const blob = new Blob([content]);
  downloadByA(URL.createObjectURL(blob), filename, fileSuffix);
};
const _withScopeId = (n) => (pushScopeId("data-v-394ad52c"), n = n(), popScopeId(), n);
const _hoisted_1 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createElementVNode("p", null, [
  /* @__PURE__ */ createElementVNode("span", { class: "func-keyword" }, "function"),
  /* @__PURE__ */ createTextVNode("  filter(data, res)  {")
], -1));
const _hoisted_2 = { class: "go-ml-4" };
const _hoisted_3 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createElementVNode("p", null, "}", -1));
const _hoisted_4 = /* @__PURE__ */ _withScopeId(() => /* @__PURE__ */ createElementVNode("span", { class: "func-keyword" }, "function", -1));
const _hoisted_5 = { class: "editor-data-show" };
const _hoisted_6 = { class: "editor-data-show" };
const _hoisted_7 = { class: "editor-data-show" };
const _hoisted_8 = { class: "go-flex-items-center" };
const _sfc_main$1 = /* @__PURE__ */ defineComponent({
  __name: "index",
  setup(__props) {
    const { DocumentTextIcon } = icon.ionicons5;
    const { FilterIcon, FilterEditIcon } = icon.carbon;
    const { targetData, chartEditStore } = useTargetData();
    toRefs(targetData.value.request);
    toRefs(chartEditStore.getRequestGlobalConfig);
    const showModal = ref(false);
    const filter = ref(targetData.value.filter || `return data`);
    const errorFlag = ref(false);
    const sourceData = ref("");
    const fetchTargetData = async () => {
      try {
        const res = await customizeHttp(toRaw(targetData.value.request), toRaw(chartEditStore.getRequestGlobalConfig));
        if (res) {
          sourceData.value = res;
          return;
        }
        window["$message"].warning("没有拿到返回值，请检查接口！");
      } catch (error) {
        console.error(error);
        window["$message"].warning("数据异常，请检查参数！");
      }
    };
    const filterRes = computed(() => {
      try {
        const fn = new Function("data", "res", filter.value);
        const response = cloneDeep(sourceData.value);
        const res = fn(response == null ? void 0 : response.data, response);
        errorFlag.value = false;
        return toString(res);
      } catch (error) {
        errorFlag.value = true;
        return `过滤函数错误，日志：${error}`;
      }
    });
    const addFilter = () => {
      showModal.value = true;
    };
    const delFilter = () => {
      goDialog({
        message: "是否删除过滤器",
        onPositiveCallback: () => {
          targetData.value.filter = void 0;
        }
      });
    };
    const closeFilter = () => {
      showModal.value = false;
    };
    const saveFilter = () => {
      if (errorFlag.value) {
        window["$message"].error("过滤函数错误，无法进行保存");
        return;
      }
      targetData.value.filter = filter.value;
      closeFilter();
    };
    watch(
      () => showModal.value,
      (newData) => {
        if (newData) {
          fetchTargetData();
          filter.value = targetData.value.filter || `return data`;
        }
      }
    );
    return (_ctx, _cache) => {
      const _component_n_code = resolveComponent("n-code");
      const _component_n_icon = resolveComponent("n-icon");
      const _component_n_button = resolveComponent("n-button");
      const _component_n_space = resolveComponent("n-space");
      const _component_n_card = resolveComponent("n-card");
      const _component_n_text = resolveComponent("n-text");
      const _component_n_tag = resolveComponent("n-tag");
      const _component_n_divider = resolveComponent("n-divider");
      const _component_n_scrollbar = resolveComponent("n-scrollbar");
      const _component_n_modal = resolveComponent("n-modal");
      return openBlock(), createElementBlock(Fragment, null, [
        unref(targetData).filter ? (openBlock(), createBlock(_component_n_card, { key: 0 }, {
          footer: withCtx(() => [
            createVNode(_component_n_space, { justify: "end" }, {
              default: withCtx(() => [
                createVNode(_component_n_button, {
                  type: "primary",
                  tertiary: "",
                  size: "small",
                  onClick: addFilter
                }, {
                  icon: withCtx(() => [
                    createVNode(_component_n_icon, null, {
                      default: withCtx(() => [
                        createVNode(unref(FilterEditIcon))
                      ]),
                      _: 1
                    })
                  ]),
                  default: withCtx(() => [
                    createTextVNode(" 编辑 ")
                  ]),
                  _: 1
                }),
                createVNode(_component_n_button, {
                  tertiary: "",
                  size: "small",
                  onClick: delFilter
                }, {
                  default: withCtx(() => [
                    createTextVNode(" 删除 ")
                  ]),
                  _: 1
                })
              ]),
              _: 1
            })
          ]),
          default: withCtx(() => [
            _hoisted_1,
            createElementVNode("div", _hoisted_2, [
              createVNode(_component_n_code, {
                code: unref(targetData).filter,
                language: "typescript"
              }, null, 8, ["code"])
            ]),
            _hoisted_3
          ]),
          _: 1
        })) : (openBlock(), createBlock(_component_n_button, {
          key: 1,
          class: "go-ml-3",
          onClick: addFilter
        }, {
          icon: withCtx(() => [
            createVNode(_component_n_icon, null, {
              default: withCtx(() => [
                createVNode(unref(FilterIcon))
              ]),
              _: 1
            })
          ]),
          default: withCtx(() => [
            createTextVNode(" 新增过滤器 ")
          ]),
          _: 1
        })),
        createVNode(_component_n_modal, {
          class: "go-chart-data-monaco-editor",
          show: showModal.value,
          "onUpdate:show": _cache[1] || (_cache[1] = ($event) => showModal.value = $event),
          "mask-closable": false,
          closeOnEsc: false
        }, {
          default: withCtx(() => [
            createVNode(_component_n_card, {
              bordered: false,
              role: "dialog",
              size: "small",
              "aria-modal": "true",
              style: { "width": "1200px", "height": "700px" }
            }, {
              header: withCtx(() => [
                createVNode(_component_n_space, null, {
                  default: withCtx(() => [
                    createVNode(_component_n_text, null, {
                      default: withCtx(() => [
                        createTextVNode("过滤器函数编辑器")
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                })
              ]),
              "header-extra": withCtx(() => []),
              action: withCtx(() => [
                createVNode(_component_n_space, { justify: "space-between" }, {
                  default: withCtx(() => [
                    createElementVNode("div", _hoisted_8, [
                      createVNode(_component_n_tag, {
                        bordered: false,
                        type: "primary"
                      }, {
                        icon: withCtx(() => [
                          createVNode(_component_n_icon, { component: unref(DocumentTextIcon) }, null, 8, ["component"])
                        ]),
                        default: withCtx(() => [
                          createTextVNode(" 规则 ")
                        ]),
                        _: 1
                      }),
                      createVNode(_component_n_text, {
                        class: "go-ml-2",
                        depth: "2"
                      }, {
                        default: withCtx(() => [
                          createTextVNode("过滤器默认处理接口返回值的「data」字段")
                        ]),
                        _: 1
                      })
                    ]),
                    createVNode(_component_n_space, null, {
                      default: withCtx(() => [
                        createVNode(_component_n_button, {
                          size: "medium",
                          onClick: closeFilter
                        }, {
                          default: withCtx(() => [
                            createTextVNode("取消")
                          ]),
                          _: 1
                        }),
                        createVNode(_component_n_button, {
                          size: "medium",
                          type: "primary",
                          onClick: saveFilter
                        }, {
                          default: withCtx(() => [
                            createTextVNode("保存")
                          ]),
                          _: 1
                        })
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                })
              ]),
              default: withCtx(() => [
                createVNode(_component_n_space, {
                  size: "small",
                  vertical: ""
                }, {
                  default: withCtx(() => [
                    createVNode(_component_n_space, { justify: "space-between" }, {
                      default: withCtx(() => [
                        createElementVNode("div", null, [
                          createVNode(_component_n_space, { vertical: "" }, {
                            default: withCtx(() => [
                              createVNode(_component_n_tag, { type: "info" }, {
                                default: withCtx(() => [
                                  _hoisted_4,
                                  createTextVNode("  filter(data, res)  { ")
                                ]),
                                _: 1
                              }),
                              createVNode(unref(MonacoEditor), {
                                modelValue: filter.value,
                                "onUpdate:modelValue": _cache[0] || (_cache[0] = ($event) => filter.value = $event),
                                width: "660px",
                                height: "500px",
                                language: "javascript"
                              }, null, 8, ["modelValue"]),
                              createVNode(_component_n_tag, { type: "info" }, {
                                default: withCtx(() => [
                                  createTextVNode("}")
                                ]),
                                _: 1
                              })
                            ]),
                            _: 1
                          })
                        ]),
                        createVNode(_component_n_divider, {
                          vertical: "",
                          style: { "height": "580px" }
                        }),
                        createVNode(_component_n_scrollbar, { style: { "max-height": "580px" } }, {
                          default: withCtx(() => [
                            createVNode(_component_n_space, {
                              size: 15,
                              vertical: ""
                            }, {
                              default: withCtx(() => [
                                createElementVNode("div", _hoisted_5, [
                                  createVNode(_component_n_space, null, {
                                    default: withCtx(() => {
                                      var _a;
                                      return [
                                        createVNode(_component_n_text, { depth: "3" }, {
                                          default: withCtx(() => [
                                            createTextVNode("默认过滤数据(data)：")
                                          ]),
                                          _: 1
                                        }),
                                        createVNode(_component_n_code, {
                                          code: unref(toString)((_a = sourceData.value) == null ? void 0 : _a.data) || "暂无",
                                          language: "json",
                                          "word-wrap": true
                                        }, null, 8, ["code"])
                                      ];
                                    }),
                                    _: 1
                                  })
                                ]),
                                createElementVNode("div", _hoisted_6, [
                                  createVNode(_component_n_space, null, {
                                    default: withCtx(() => [
                                      createVNode(_component_n_text, { depth: "3" }, {
                                        default: withCtx(() => [
                                          createTextVNode("接口返回数据(res)：")
                                        ]),
                                        _: 1
                                      }),
                                      createVNode(_component_n_code, {
                                        code: unref(toString)(sourceData.value) || "暂无",
                                        language: "json",
                                        "word-wrap": true
                                      }, null, 8, ["code"])
                                    ]),
                                    _: 1
                                  })
                                ]),
                                createElementVNode("div", _hoisted_7, [
                                  createVNode(_component_n_space, null, {
                                    default: withCtx(() => [
                                      createVNode(_component_n_text, { depth: "3" }, {
                                        default: withCtx(() => [
                                          createTextVNode("过滤器结果：")
                                        ]),
                                        _: 1
                                      }),
                                      createVNode(_component_n_code, {
                                        code: filterRes.value || "暂无",
                                        language: "json",
                                        "word-wrap": true
                                      }, null, 8, ["code"])
                                    ]),
                                    _: 1
                                  })
                                ])
                              ]),
                              _: 1
                            })
                          ]),
                          _: 1
                        })
                      ]),
                      _: 1
                    })
                  ]),
                  _: 1
                })
              ]),
              _: 1
            })
          ]),
          _: 1
        }, 8, ["show"])
      ], 64);
    };
  }
});
const index_vue_vue_type_style_index_0_scoped_394ad52c_lang = "";
const ChartDataMonacoEditor = /* @__PURE__ */ _export_sfc(_sfc_main$1, [["__scopeId", "data-v-394ad52c"]]);
const useFile = (targetData) => {
  const uploadFileListRef = ref();
  const beforeUpload = ({ file }) => {
    uploadFileListRef.value = [];
    const type = file.file.type;
    if (type !== FileTypeEnum.JSON && type !== FileTypeEnum.TXT) {
      window["$message"].warning("仅支持上传 【JSON】 格式文件，请重新上传！");
      return false;
    }
    return true;
  };
  const customRequest = (options) => {
    const { file } = options;
    nextTick(() => {
      if (file.file) {
        readFile(file.file).then((fileData) => {
          targetData.value.option.dataset = JSONParse(fileData);
        });
      } else {
        window["$message"].error("导入数据失败，请稍后重试或联系管理员！");
      }
    });
  };
  const download = () => {
    try {
      window["$message"].success("下载中，请耐心等待...");
      downloadTextFile(JSONStringify(targetData.value.option.dataset), void 0, "json");
    } catch (error) {
      window["$message"].error("下载失败，数据错误！");
    }
  };
  return {
    uploadFileListRef,
    beforeUpload,
    customRequest,
    download
  };
};
const _sfc_main = /* @__PURE__ */ defineComponent({
  __name: "index",
  props: {
    show: {
      type: Boolean,
      required: false
    },
    ajax: {
      type: Boolean,
      required: true
    }
  },
  setup(__props) {
    const { targetData } = useTargetData();
    const tableTitle = ["字段", "映射", "状态"];
    const { HelpOutlineIcon } = icon.ionicons5;
    const { DocumentAddIcon, DocumentDownloadIcon } = icon.carbon;
    const source = ref();
    const dimensions = ref();
    const dimensionsAndSource = ref();
    const noData = ref(false);
    const { uploadFileListRef, customRequest, beforeUpload, download } = useFile(targetData);
    const filterShow = computed(() => {
      return targetData.value.request.requestDataType !== RequestDataTypeEnum.STATIC;
    });
    const isCharts = computed(() => {
      return targetData.value.chartConfig.chartFrame === ChartFrameEnum.ECHARTS;
    });
    const matchingHandle = (mapping) => {
      let res = DataResultEnum.SUCCESS;
      for (let i = 0; i < source.value.length; i++) {
        if (source.value[i][mapping] === void 0) {
          res = DataResultEnum.FAILURE;
          return res;
        }
      }
      return DataResultEnum.SUCCESS;
    };
    const dimensionsAndSourceHandle = () => {
      try {
        return dimensions.value.map((dimensionsItem, index) => {
          return index === 0 ? {
            // 字段
            field: "通用标识",
            // 映射
            mapping: dimensionsItem,
            // 结果
            result: DataResultEnum.NULL
          } : {
            field: `数据项-${index}`,
            mapping: dimensionsItem,
            result: matchingHandle(dimensionsItem)
          };
        });
      } catch (error) {
        return [];
      }
    };
    watch(
      () => {
        var _a, _b;
        return (_b = (_a = targetData.value) == null ? void 0 : _a.option) == null ? void 0 : _b.dataset;
      },
      (newData) => {
        var _a, _b;
        if (newData && ((_b = (_a = targetData == null ? void 0 : targetData.value) == null ? void 0 : _a.chartConfig) == null ? void 0 : _b.chartFrame) === ChartFrameEnum.ECHARTS) {
          source.value = newData;
          if (isCharts.value) {
            dimensions.value = newData.dimensions;
            dimensionsAndSource.value = dimensionsAndSourceHandle();
          }
        } else if (newData !== void 0 && newData !== null) {
          dimensionsAndSource.value = null;
          source.value = newData;
        } else {
          noData.value = true;
          source.value = "此组件无数据源";
        }
        if (isArray(newData)) {
          dimensionsAndSource.value = null;
        }
      },
      {
        immediate: true
      }
    );
    return (_ctx, _cache) => {
      const _component_n_badge = resolveComponent("n-badge");
      const _component_n_text = resolveComponent("n-text");
      const _component_n_space = resolveComponent("n-space");
      const _component_n_table = resolveComponent("n-table");
      const _component_n_timeline_item = resolveComponent("n-timeline-item");
      const _component_n_icon = resolveComponent("n-icon");
      const _component_n_button = resolveComponent("n-button");
      const _component_n_upload = resolveComponent("n-upload");
      const _component_n_tooltip = resolveComponent("n-tooltip");
      const _component_n_code = resolveComponent("n-code");
      const _component_n_card = resolveComponent("n-card");
      const _component_n_timeline = resolveComponent("n-timeline");
      return openBlock(), createBlock(_component_n_timeline, { class: "go-chart-configurations-timeline" }, {
        default: withCtx(() => [
          withDirectives(createVNode(_component_n_timeline_item, {
            type: "info",
            title: unref(TimelineTitleEnum).MAPPING
          }, {
            default: withCtx(() => [
              createVNode(_component_n_table, { striped: "" }, {
                default: withCtx(() => [
                  createElementVNode("thead", null, [
                    createElementVNode("tr", null, [
                      (openBlock(), createElementBlock(Fragment, null, renderList(tableTitle, (item) => {
                        return createElementVNode("th", { key: item }, toDisplayString(item), 1);
                      }), 64))
                    ])
                  ]),
                  createElementVNode("tbody", null, [
                    (openBlock(true), createElementBlock(Fragment, null, renderList(dimensionsAndSource.value, (item, index) => {
                      return openBlock(), createElementBlock("tr", { key: index }, [
                        createElementVNode("td", null, toDisplayString(item.field), 1),
                        createElementVNode("td", null, toDisplayString(item.mapping), 1),
                        createElementVNode("td", null, [
                          item.result === 0 ? (openBlock(), createBlock(_component_n_space, { key: 0 }, {
                            default: withCtx(() => [
                              createVNode(_component_n_badge, {
                                dot: "",
                                type: "success"
                              }),
                              createVNode(_component_n_text, null, {
                                default: withCtx(() => [
                                  createTextVNode("无")
                                ]),
                                _: 1
                              })
                            ]),
                            _: 1
                          })) : (openBlock(), createBlock(_component_n_space, { key: 1 }, {
                            default: withCtx(() => [
                              createVNode(_component_n_badge, {
                                dot: "",
                                type: item.result === 1 ? "success" : "error"
                              }, null, 8, ["type"]),
                              createVNode(_component_n_text, null, {
                                default: withCtx(() => [
                                  createTextVNode("匹配" + toDisplayString(item.result === 1 ? "成功" : "失败"), 1)
                                ]),
                                _: 2
                              }, 1024)
                            ]),
                            _: 2
                          }, 1024))
                        ])
                      ]);
                    }), 128))
                  ])
                ]),
                _: 1
              })
            ]),
            _: 1
          }, 8, ["title"]), [
            [vShow, isCharts.value && dimensionsAndSource.value]
          ]),
          withDirectives(createVNode(_component_n_timeline_item, {
            color: "#97846c",
            title: unref(TimelineTitleEnum).FILTER
          }, {
            default: withCtx(() => [
              createVNode(_component_n_space, {
                size: 18,
                vertical: ""
              }, {
                default: withCtx(() => [
                  createVNode(_component_n_text, { depth: "3" }, {
                    default: withCtx(() => [
                      createTextVNode("过滤器默认处理接口返回值的「data」字段")
                    ]),
                    _: 1
                  }),
                  createVNode(unref(ChartDataMonacoEditor))
                ]),
                _: 1
              })
            ]),
            _: 1
          }, 8, ["title"]), [
            [vShow, filterShow.value]
          ]),
          createVNode(_component_n_timeline_item, {
            type: "success",
            title: unref(TimelineTitleEnum).CONTENT
          }, {
            default: withCtx(() => [
              createVNode(_component_n_space, { vertical: "" }, {
                default: withCtx(() => [
                  createVNode(_component_n_space, { class: "source-btn-box" }, {
                    default: withCtx(() => [
                      createVNode(_component_n_upload, {
                        "file-list": unref(uploadFileListRef),
                        "onUpdate:fileList": _cache[0] || (_cache[0] = ($event) => isRef(uploadFileListRef) ? uploadFileListRef.value = $event : null),
                        "show-file-list": false,
                        customRequest: unref(customRequest),
                        onBeforeUpload: unref(beforeUpload)
                      }, {
                        default: withCtx(() => [
                          createVNode(_component_n_space, null, {
                            default: withCtx(() => [
                              !__props.ajax ? (openBlock(), createBlock(_component_n_button, {
                                key: 0,
                                class: "sourceBtn-item",
                                disabled: noData.value
                              }, {
                                icon: withCtx(() => [
                                  createVNode(_component_n_icon, null, {
                                    default: withCtx(() => [
                                      createVNode(unref(DocumentAddIcon))
                                    ]),
                                    _: 1
                                  })
                                ]),
                                default: withCtx(() => [
                                  createTextVNode(" 导入（json / txt） ")
                                ]),
                                _: 1
                              }, 8, ["disabled"])) : createCommentVNode("", true)
                            ]),
                            _: 1
                          })
                        ]),
                        _: 1
                      }, 8, ["file-list", "customRequest", "onBeforeUpload"]),
                      createElementVNode("div", null, [
                        createVNode(_component_n_button, {
                          class: "sourceBtn-item",
                          disabled: noData.value,
                          onClick: unref(download)
                        }, {
                          icon: withCtx(() => [
                            createVNode(_component_n_icon, null, {
                              default: withCtx(() => [
                                createVNode(unref(DocumentDownloadIcon))
                              ]),
                              _: 1
                            })
                          ]),
                          default: withCtx(() => [
                            createTextVNode(" 下载 ")
                          ]),
                          _: 1
                        }, 8, ["disabled", "onClick"]),
                        createVNode(_component_n_tooltip, { trigger: "hover" }, {
                          trigger: withCtx(() => [
                            createVNode(_component_n_icon, {
                              class: "go-ml-1",
                              size: "21",
                              depth: 3
                            }, {
                              default: withCtx(() => [
                                createVNode(unref(HelpOutlineIcon))
                              ]),
                              _: 1
                            })
                          ]),
                          default: withCtx(() => [
                            createVNode(_component_n_text, { depth: "3" }, {
                              default: withCtx(() => [
                                createTextVNode("点击【下载】查看完整数据")
                              ]),
                              _: 1
                            })
                          ]),
                          _: 1
                        })
                      ])
                    ]),
                    _: 1
                  }),
                  createVNode(_component_n_card, { size: "small" }, {
                    default: withCtx(() => [
                      createVNode(_component_n_code, {
                        code: unref(toString)(source.value),
                        language: "json"
                      }, null, 8, ["code"])
                    ]),
                    _: 1
                  })
                ]),
                _: 1
              })
            ]),
            _: 1
          }, 8, ["title"])
        ]),
        _: 1
      });
    };
  }
});
const index_vue_vue_type_style_index_0_scoped_f6d90859_lang = "";
const ChartDataMatchingAndShow = /* @__PURE__ */ _export_sfc(_sfc_main, [["__scopeId", "data-v-f6d90859"]]);
export {
  ChartDataMatchingAndShow as C
};
