<!-- Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.  See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. -->
<template>
  <div class="flex-h row" style="justify-content: space-between">
    <div class="flex-h">
      <div class="mr-10 flex-h" v-if="dashboardStore.entity === EntityType[1].value">
        <span class="grey mr-5 label">{{ t("service") }}:</span>
        <Selector
          size="small"
          :value="state.service.value"
          :options="traceStore.services"
          placeholder="Select a service"
          @change="changeField('service', $event)"
        />
      </div>
      <div class="mr-10 flex-h" v-if="dashboardStore.entity !== EntityType[3].value">
        <span class="grey mr-5 label">{{ t("instance") }}:</span>
        <Selector
          size="small"
          :value="state.instance.value"
          :options="traceStore.instances"
          placeholder="Select a instance"
          @change="changeField('instance', $event)"
        />
      </div>
      <div class="mr-10 flex-h" v-if="dashboardStore.entity !== EntityType[2].value">
        <span class="grey mr-5 label">{{ t("endpoint") }}:</span>
        <Selector
          size="small"
          :value="state.endpoint.value"
          :options="traceStore.endpoints"
          placeholder="Select a endpoint"
          :isRemote="true"
          @change="changeField('endpoint', $event)"
          @query="searchEndpoints"
        />
      </div>
      <div class="mr-10 flex-h">
        <span class="grey mr-5 label">{{ t("status") }}:</span>
        <Selector
          size="small"
          :value="state.status.value"
          :options="Status"
          placeholder="Select a status"
          @change="changeField('status', $event)"
        />
      </div>
    </div>
    <div class="mr-10">
      <el-button type="primary" @click="searchTraces" :loading="traceStore.loading">
        {{ t("runQuery") }}
      </el-button>
    </div>
  </div>
  <div class="flex-h row">
    <div class="mr-10">
      <span class="grey mr-5">{{ t("traceID") }}:</span>
      <el-input size="small" v-model="traceId" class="traceId" />
    </div>
    <div class="mr-10">
      <span class="sm b grey mr-5">{{ t("duration") }}:</span>
      <el-input size="small" class="inputs mr-5" v-model="minTraceDuration" type="number" />
      <span class="grey mr-5">-</span>
      <el-input size="small" class="inputs" v-model="maxTraceDuration" type="number" />
    </div>
    <div>
      <span class="sm b grey mr-5">{{ t("timeRange") }}</span>
      <TimePicker
        :value="[durationRow.start, durationRow.end]"
        :maxRange="maxRange"
        position="bottom"
        format="YYYY-MM-DD HH:mm"
        @input="changeDuration"
      />
    </div>
  </div>
  <div class="flex-h">
    <ConditionTags :type="'TRACE'" @update="updateTags" />
  </div>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch, onUnmounted, computed } from "vue";
  import type { PropType } from "vue";
  import { useI18n } from "vue-i18n";
  import type { Option, DurationTime, Duration } from "@/types/app";
  import { useTraceStore, PageSize } from "@/store/modules/trace";
  import { useDashboardStore } from "@/store/modules/dashboard";
  import { useAppStoreWithOut, InitializationDurationRow } from "@/store/modules/app";
  import { useSelectorStore } from "@/store/modules/selectors";
  import timeFormat from "@/utils/timeFormat";
  import ConditionTags from "@/views/components/ConditionTags.vue";
  import { ElMessage } from "element-plus";
  import { EntityType, QueryOrders, Status } from "@/views/dashboard/data";
  import type { LayoutConfig, FilterDuration } from "@/types/dashboard";
  import { useDuration } from "@/hooks/useDuration";
  import { TimeType } from "@/constants/data";

  /*global defineProps, defineEmits, Recordable */
  const emits = defineEmits(["get", "search"]);
  const props = defineProps({
    needQuery: { type: Boolean, default: true },
    data: {
      type: Object as PropType<LayoutConfig>,
      default: () => ({}),
    },
  });
  const { t } = useI18n();
  const appStore = useAppStoreWithOut();
  const selectorStore = useSelectorStore();
  const dashboardStore = useDashboardStore();
  const traceStore: ReturnType<typeof useTraceStore> = useTraceStore();
  const { setDurationRow, getDurationTime, getMaxRange } = useDuration();
  const filters = computed(() => props.data.filters || {});
  const traceId = ref<string>(filters.value.traceId || "");
  const { duration: filtersDuration } = filters.value;
  const duration = ref<DurationTime | FilterDuration>(
    filtersDuration
      ? { start: filtersDuration.startTime || "", end: filtersDuration.endTime || "", step: TimeType.SECOND_TIME }
      : getDurationTime(),
  );
  const minTraceDuration = ref<number>();
  const maxTraceDuration = ref<number>();
  const tagsMap = ref<Option[]>([]);
  const state = reactive<Recordable>({
    status: filters.value.status === "ERROR" ? Status[2] : Status[0],
    instance: { value: "0", label: "All" },
    endpoint: { value: "0", label: "All" },
    service: { value: "", label: "" },
  });
  const durationRow = ref<Duration>(InitializationDurationRow);
  const maxRange = computed(() =>
    getMaxRange(appStore.coldStageMode ? appStore.recordsTTL?.coldTrace || 0 : appStore.recordsTTL?.trace || 0),
  );
  if (filters.value.queryOrder) {
    traceStore.setTraceCondition({
      queryOrder: filters.value.queryOrder,
    });
  }
  if (props.needQuery) {
    init();
  }

  async function init() {
    if (dashboardStore.entity === EntityType[1].value) {
      await getServices();
    }
    if (dashboardStore.entity === EntityType[2].value) {
      await getInstances();
    }
    if (dashboardStore.entity === EntityType[3].value) {
      await getEndpoints();
    }
    if (dashboardStore.entity === EntityType[0].value) {
      await getInstances();
      await getEndpoints();
    }
    await searchTraces();
  }

  async function getServices() {
    const resp = await traceStore.getServices(dashboardStore.layerId);
    if (resp.errors) {
      ElMessage.error(resp.errors);
      return;
    }
    if (props.data.filters && props.data.filters.id === "0") {
      state.service = { value: "", label: "" };
      return;
    } else {
      state.service = getCurrentNode(traceStore.services as { id: string }[]) || traceStore.services[0];
    }

    emits("get", state.service.id);

    getEndpoints(state.service.id);
    getInstances(state.service.id);
  }

  async function getEndpoints(id?: string, keyword?: string) {
    const resp = await traceStore.getEndpoints(id, keyword);
    if (resp.errors) {
      ElMessage.error(resp.errors);
      return;
    }
    state.endpoint = getCurrentNode(traceStore.endpoints as { id: string }[]) || traceStore.endpoints[0];
  }
  async function getInstances(id?: string) {
    const resp = await traceStore.getInstances(id);
    if (resp.errors) {
      ElMessage.error(resp.errors);
      return;
    }
    state.instance = getCurrentNode(traceStore.instances as { id: string }[]) || traceStore.instances[0];
  }
  function getCurrentNode(arr: { id: string }[]) {
    let item;
    if (!props.data.filters) {
      return item;
    }
    if (props.data.filters.id) {
      item = arr.find((d: { id: string }) => d.id === props.data.filters?.id);
    }

    return item;
  }
  function setCondition() {
    let param: Recordable = {
      traceState: state.status.value || "ALL",
      tags: tagsMap.value.length ? tagsMap.value : undefined,
      queryOrder: traceStore.conditions.queryOrder || QueryOrders[1].value,
      queryDuration: duration.value,
      minTraceDuration: Number(minTraceDuration.value),
      maxTraceDuration: Number(maxTraceDuration.value),
      traceId: traceId.value || undefined,
    };
    if (!traceStore.hasQueryTracesV2Support) {
      param.paging = { pageNum: 1, pageSize: PageSize };
    }
    if (props.data.filters && props.data.filters.id) {
      param = {
        ...param,
        serviceId: props.data.filters.id && props.data.filters.id !== "0" ? props.data.filters.id : undefined,
        endpointId: state.endpoint.id || undefined,
        serviceInstanceId: state.instance.id || undefined,
      };
      return param;
    }
    let endpoint = "",
      instance = "";
    if (dashboardStore.entity === EntityType[2].value) {
      endpoint = selectorStore.currentPod?.id || "";
    }
    if (dashboardStore.entity === EntityType[3].value) {
      instance = selectorStore.currentPod?.id || "";
    }
    param = {
      ...param,
      serviceId: selectorStore.currentService ? selectorStore.currentService.id : state.service.id,
      endpointId: endpoint || state.endpoint.id || undefined,
      serviceInstanceId: instance || state.instance.id || undefined,
    };
    return param;
  }
  function searchTraces() {
    emits("search");
    traceStore.setTraceCondition(setCondition());
    queryTraces();
  }
  async function queryTraces() {
    const res = await traceStore.getTraces();
    if (res && res.errors) {
      ElMessage.error(res.errors);
    }
  }
  function changeField(type: string, opt: Recordable) {
    state[type] = opt[0];
    if (type === "service") {
      getEndpoints(state.service.id);
      getInstances(state.service.id);
      emits("get", state.service.id);
    }
  }
  function updateTags(data: { tagsMap: Array<Option> }) {
    tagsMap.value = data.tagsMap;
  }
  async function searchEndpoints(keyword: string) {
    const resp = await traceStore.getEndpoints(state.service.id, keyword);
    if (resp.errors) {
      ElMessage.error(resp.errors);
    }
  }
  function changeDuration(val: Date[]) {
    durationRow.value = timeFormat(val);
    setDurationRow(durationRow.value);
    duration.value = getDurationTime();
  }
  onUnmounted(() => {
    traceStore.resetState();
    const config = props.data;
    delete config.filters;
    dashboardStore.setWidget(config);
  });
  watch(
    () => [selectorStore.currentPod],
    () => {
      if (dashboardStore.entity === EntityType[0].value) {
        return;
      }
      init();
    },
  );
  watch(
    () => [selectorStore.currentService],
    () => {
      if (dashboardStore.entity !== EntityType[0].value) {
        return;
      }
      init();
    },
  );
  watch(
    () => appStore.coldStageMode,
    () => {
      durationRow.value = InitializationDurationRow;
      setDurationRow(durationRow.value);
      duration.value = getDurationTime();
      init();
    },
  );
  // Event widget associate with trace widget
  watch(
    () => props.data.filters,
    (newJson, oldJson) => {
      if (!props.data.filters) {
        return;
      }
      if (JSON.stringify(newJson) === JSON.stringify(oldJson)) {
        return;
      }
      const { traceId: filtersTraceId, duration: filtersDuration } = props.data.filters || {};
      traceId.value = filtersTraceId || "";
      duration.value = filtersDuration
        ? {
            start: filtersDuration.startTime || "",
            end: filtersDuration.endTime || "",
            step: TimeType.SECOND_TIME,
          }
        : getDurationTime();
      init();
    },
  );
</script>
<style lang="scss" scoped>
  .inputs {
    width: 120px;
  }

  .row {
    margin-bottom: 5px;
  }

  .traceId {
    width: 270px;
  }

  .label {
    line-height: var(--el-input-height, 24px);
    flex-shrink: 0;
  }
</style>
