<script setup>
import { computed } from "vue";
import { Field, FieldLabel } from "../../../../ui/field";
import { ExpressionEditor } from "../../../../ui/expression-editor";
import { Markdown } from "../../../../ui/markdown";
import { getStructFieldDescription, getStructFieldTitle } from "../../../schema";
import TriggersField from "../../../components/triggers-field.vue";
import { JSON_VAR, schema } from "./schema";
defineOptions({ name: "ShwfedHttpDownloadActionConfig" });
const value = defineModel({ type: null, ...{ required: true } });
const actionSchema = schema(() => {
});
const fieldTitle = (f) => getStructFieldTitle(actionSchema, f) ?? f;
const fieldDescription = (f) => getStructFieldDescription(actionSchema, f);
const RESULT_FIELDS = ["onSuccess", "onWarning", "onError", "onInfo"];
const templateRequestText = computed({
  get: () => value.value.template?.request ?? "",
  set: (next) => {
    value.value = {
      ...value.value,
      template: { ...value.value.template, request: next }
    };
  }
});
const templateDownloadText = computed({
  get: () => value.value.template?.download ?? "",
  set: (next) => {
    const current = value.value.template ?? { request: "" };
    if (next.length === 0) {
      const { download: _omit, ...rest } = current;
      value.value = { ...value.value, template: rest };
    } else {
      value.value = { ...value.value, template: { ...current, download: next } };
    }
  }
});
function updateMessageExpression(v) {
  const next = { ...value.value };
  if (v.length === 0) delete next.messageExpression;
  else next.messageExpression = v;
  value.value = next;
}
function updateResultExpression(v) {
  const next = { ...value.value };
  if (v.length === 0) delete next.resultExpression;
  else next.resultExpression = v;
  value.value = next;
}
function updateTriggers(key, next) {
  const draft = { ...value.value };
  if (next.length === 0) Reflect.deleteProperty(draft, key);
  else draft[key] = next;
  value.value = draft;
}
</script>

<template>
  <div class="flex flex-col gap-3">
    <div class="grid grid-cols-2 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('template') ?? '\u8FD4\u56DE `HttpRequest` \u7684 CEL \u8868\u8FBE\u5F0F\uFF1B\u672A\u914D\u7F6E\u300C\u4E0B\u8F7D\u8BF7\u6C42\u300D\u65F6\u76F4\u63A5\u4E0B\u8F7D\u5176\u54CD\u5E94'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          请求
        </FieldLabel>
        <ExpressionEditor
          :model-value="templateRequestText"
          multiline
          placeholder="例：http.get('https://api.example.com/files/123')"
          result-type="HttpRequest"
          class="min-h-16"
          @update:model-value="(v) => templateRequestText = v"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              source="可选的第二步：用第一步响应 `json` 中的凭据构造真正的下载请求，例如 `json.data.key`"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          下载请求
        </FieldLabel>
        <ExpressionEditor
          :model-value="templateDownloadText"
          multiline
          placeholder="例：http.get('https://api.example.com/download').query('key', json.data.key)"
          result-type="HttpRequest"
          :extra-vars="{ json: JSON_VAR }"
          class="min-h-16"
          @update:model-value="(v) => templateDownloadText = v"
        />
      </Field>
    </div>

    <div class="flex items-start gap-2">
      <Field
        orientation="vertical"
        class="flex-1 basis-0 min-w-0"
      >
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('messageExpression')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('messageExpression')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("messageExpression") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.messageExpression ?? ''"
          placeholder="例：string(json.message)"
          result-type="string"
          :extra-vars="{ json: JSON_VAR }"
          @update:model-value="updateMessageExpression"
        />
      </Field>

      <Field
        orientation="vertical"
        class="flex-1 basis-0 min-w-0"
      >
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('resultExpression')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('resultExpression')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("resultExpression") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.resultExpression ?? ''"
          placeholder="例：json.code == 0 ? 'success' : 'error'"
          result-type="string"
          :extra-vars="{ json: JSON_VAR }"
          @update:model-value="updateResultExpression"
        />
      </Field>
    </div>

    <!-- One trigger list per 「执行结果」: the request completes, the result
         classifies the outcome, and the matching cell's operations run. -->
    <div class="grid grid-cols-2 gap-3">
      <Field
        v-for="key in RESULT_FIELDS"
        :key="key"
        orientation="vertical"
        class="min-w-0"
      >
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription(key)"
            #tooltip
          >
            <Markdown
              :source="fieldDescription(key)"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle(key) }}
        </FieldLabel>
        <TriggersField
          :triggers="value[key] ?? []"
          @update:triggers="(v) => updateTriggers(key, v)"
        />
      </Field>
    </div>
  </div>
</template>
