<script setup>
import { Icon } from "@iconify/vue";
import { computed, ref } from "vue";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger
} from "../../../../ui/dropdown-menu";
import { ExpressionEditor } from "../../../../ui/expression-editor";
import ValidationRulesField from "../../../ValidationRulesField.vue";
import { Field, FieldLabel } from "../../../../ui/field";
import { IconPicker } from "../../../../ui/icon-picker";
import {
  InputGroup,
  InputGroupAddon,
  InputGroupButton,
  InputGroupInput,
  InputGroupNumberField
} from "../../../../ui/input-group";
import { Locale as LocaleField } from "../../../../ui/locale";
import { Markdown } from "../../../../ui/markdown";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../../../../ui/select";
import { Switch } from "../../../../ui/switch";
import { getStructFieldDescription, getStructFieldTitle } from "../../../schema";
import { DEFAULT_FIELD_ORIENTATION, FIELD_ORIENTATION_OPTIONS } from "../../../utils/common";
import { JSON_VAR, schema } from "./schema";
defineOptions({ name: "ShwfedUploadFieldConfig" });
const value = defineModel({ type: null, ...{ required: true } });
const fieldSchema = schema(() => {
});
const fieldTitle = (f) => getStructFieldTitle(fieldSchema, f) ?? f;
const fieldDescription = (f) => getStructFieldDescription(fieldSchema, f);
const pathText = computed({
  get: () => value.value.binding ?? "",
  set: (next) => {
    const trimmed = next.trim();
    if (trimmed.length === 0) {
      const { binding: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, binding: trimmed };
    }
  }
});
const templateRequestText = computed({
  get: () => value.value.template?.request ?? "",
  set: (next) => {
    if (next.length === 0) {
      const { template: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      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;
    if (!current) return;
    if (next.length === 0) {
      const { download: _omit, ...rest } = current;
      value.value = { ...value.value, template: rest };
    } else {
      value.value = { ...value.value, template: { ...current, download: next } };
    }
  }
});
const templateIconText = computed({
  get: () => value.value.templateIcon ?? "",
  set: (next) => {
    const trimmed = next.trim();
    if (trimmed.length === 0) {
      const { templateIcon: _omit, ...rest } = value.value;
      value.value = rest;
    } else {
      value.value = { ...value.value, templateIcon: trimmed };
    }
  }
});
const MIME_GROUPS = [
  { id: "pdf", label: "PDF", mimes: ["application/pdf"] },
  { id: "docx", label: "DOCX", mimes: ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"] },
  { id: "doc", label: "DOC", mimes: ["application/msword"] },
  { id: "xlsx", label: "XLSX", mimes: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"] },
  { id: "xls", label: "XLS", mimes: ["application/vnd.ms-excel"] },
  { id: "pptx", label: "PPTX", mimes: ["application/vnd.openxmlformats-officedocument.presentationml.presentation"] },
  { id: "ppt", label: "PPT", mimes: ["application/vnd.ms-powerpoint"] },
  { id: "zip", label: "ZIP", mimes: ["application/zip", "application/x-zip-compressed"] },
  { id: "rar", label: "RAR", mimes: ["application/vnd.rar", "application/x-rar-compressed"] },
  { id: "ofd", label: "OFD", mimes: ["application/ofd"] },
  { id: "xml", label: "XML", mimes: ["application/xml"] },
  { id: "png", label: "PNG", mimes: ["image/png"] },
  { id: "jpeg", label: "JPEG", mimes: ["image/jpeg", "image/jpg"] }
];
const GROUP_BY_ID = new Map(MIME_GROUPS.map((g) => [g.id, g]));
const acceptList = computed(() => value.value.accept ?? []);
const selectedGroupIds = computed(
  () => MIME_GROUPS.filter((g) => g.mimes.every((m) => acceptList.value.includes(m))).map((g) => g.id)
);
const selectedGroupLabels = computed(
  () => selectedGroupIds.value.map((id) => GROUP_BY_ID.get(id)?.label).filter(Boolean).join("\u3001")
);
function onAcceptChange(next) {
  const ids = Array.isArray(next) ? next.filter((v) => typeof v === "string") : typeof next === "string" ? [next] : [];
  const mimes = ids.flatMap((id) => GROUP_BY_ID.get(id)?.mimes ?? []);
  if (mimes.length === 0) {
    const { accept: _omit, ...rest } = value.value;
    value.value = rest;
  } else {
    value.value = { ...value.value, accept: mimes };
  }
}
function pickUnitFor(bytes) {
  if (bytes === void 0) return "MB";
  return bytes < 1024 * 1024 ? "KB" : "MB";
}
function multiplierFor(unit) {
  return unit === "KB" ? 1024 : 1024 * 1024;
}
function makeSizeBinding(prop) {
  const unit = ref(pickUnitFor(value.value[prop]));
  const amount = computed({
    get: () => {
      const v = value.value[prop];
      return v === void 0 ? void 0 : v / multiplierFor(unit.value);
    },
    set: (next) => {
      if (next === void 0 || !(next > 0)) {
        const { [prop]: _omit, ...rest } = value.value;
        value.value = rest;
        return;
      }
      value.value = { ...value.value, [prop]: Math.round(next * multiplierFor(unit.value)) };
    }
  });
  return { unit, amount };
}
const perFile = makeSizeBinding("maxFileSize");
const total = makeSizeBinding("maxTotalSize");
function setMaxFiles(v) {
  if (v === void 0 || !(v > 0)) {
    const { maxFiles: _omit, ...rest } = value.value;
    value.value = rest;
  } else {
    value.value = { ...value.value, maxFiles: Math.round(v) };
  }
}
function setMultiple(v) {
  if (!v) {
    const { multiple: _omit, ...rest } = value.value;
    value.value = rest;
  } else {
    value.value = { ...value.value, multiple: true };
  }
}
</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
            v-if="fieldDescription('displayName')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('displayName')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("displayName") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            :model-value="value.displayName ?? ''"
            placeholder="例：附件"
            @update:model-value="(v) => {
  const s = String(v ?? '');
  value = { ...value, displayName: s.length > 0 ? s : void 0 };
}"
          />
        </InputGroup>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              source="写入表单状态的嵌套键路径，使用 `.` 分隔，例如 `attachments`"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("binding") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupInput
            v-model="pathText"
            placeholder="例：attachments"
            class="font-mono"
          />
        </InputGroup>
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('label')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('label')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("label") }}
        </FieldLabel>
        <LocaleField
          translate-hint="form field label"
          :model-value="value.label"
          @update:model-value="(v) => value = { ...value, label: v }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('tooltip')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('tooltip')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("tooltip") }}
        </FieldLabel>
        <LocaleField
          markdown
          translate-hint="form field tooltip"
          :model-value="value.tooltip"
          @update:model-value="(v) => value = { ...value, tooltip: v }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('description')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('description')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("description") }}
        </FieldLabel>
        <LocaleField
          markdown
          translate-hint="upload zone description"
          :model-value="value.description"
          @update:model-value="(v) => value = { ...value, description: v }"
        />
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('orientation')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('orientation')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("orientation") }}
        </FieldLabel>
        <Select
          :model-value="value.orientation ?? DEFAULT_FIELD_ORIENTATION"
          @update:model-value="(v) => value = { ...value, orientation: v }"
        >
          <SelectTrigger class="w-full">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem
              v-for="opt in FIELD_ORIENTATION_OPTIONS"
              :key="opt.value"
              :value="opt.value"
            >
              {{ opt.label }}
            </SelectItem>
          </SelectContent>
        </Select>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('multiple')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('multiple')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("multiple") }}
        </FieldLabel>
        <div>
          <Switch
            :model-value="value.multiple ?? false"
            @update:model-value="setMultiple"
          />
        </div>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('maxFiles')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('maxFiles')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("maxFiles") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupNumberField
            :model-value="value.maxFiles"
            :min="1"
            @update:model-value="setMaxFiles"
          />
        </InputGroup>
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('accept')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('accept')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("accept") }}
        </FieldLabel>
        <Select
          multiple
          :model-value="selectedGroupIds"
          @update:model-value="onAcceptChange"
        >
          <SelectTrigger class="w-full">
            <SelectValue placeholder="不限制">
              <span v-if="selectedGroupLabels.length > 0">{{ selectedGroupLabels }}</span>
              <span
                v-else
                class="text-zinc-400"
              >不限制</span>
            </SelectValue>
          </SelectTrigger>
          <SelectContent>
            <SelectItem
              v-for="group in MIME_GROUPS"
              :key="group.id"
              :value="group.id"
            >
              {{ group.label }}
            </SelectItem>
          </SelectContent>
        </Select>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('maxFileSize')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('maxFileSize')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("maxFileSize") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupNumberField
            :model-value="perFile.amount.value"
            :min="0"
            @update:model-value="(v) => perFile.amount.value = v"
          />
          <InputGroupAddon align="inline-end">
            <DropdownMenu>
              <DropdownMenuTrigger as-child>
                <InputGroupButton
                  variant="ghost"
                  class="pr-1.5! text-xs"
                >
                  {{ perFile.unit.value }}
                  <Icon
                    icon="lucide:chevron-down"
                    class="size-3"
                  />
                </InputGroupButton>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem @select="perFile.unit.value = 'KB'">
                  KB
                </DropdownMenuItem>
                <DropdownMenuItem @select="perFile.unit.value = 'MB'">
                  MB
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </InputGroupAddon>
        </InputGroup>
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('maxTotalSize')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('maxTotalSize')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("maxTotalSize") }}
        </FieldLabel>
        <InputGroup>
          <InputGroupNumberField
            :model-value="total.amount.value"
            :min="0"
            @update:model-value="(v) => total.amount.value = v"
          />
          <InputGroupAddon align="inline-end">
            <DropdownMenu>
              <DropdownMenuTrigger as-child>
                <InputGroupButton
                  variant="ghost"
                  class="pr-1.5! text-xs"
                >
                  {{ total.unit.value }}
                  <Icon
                    icon="lucide:chevron-down"
                    class="size-3"
                  />
                </InputGroupButton>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuItem @select="total.unit.value = 'KB'">
                  KB
                </DropdownMenuItem>
                <DropdownMenuItem @select="total.unit.value = 'MB'">
                  MB
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          </InputGroupAddon>
        </InputGroup>
      </Field>
    </div>

    <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\u8BBE\u7F6E\u540E\u4F1A\u6E32\u67D3\u4E0B\u8F7D\u6A21\u677F\u6309\u94AE'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          请求
        </FieldLabel>
        <ExpressionEditor
          :model-value="templateRequestText"
          placeholder="例：http.get('https://api.example.com/template.xlsx')"
          result-type="HttpRequest"
          class="min-h-10"
          @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"
          placeholder="例：http.get('https://api.example.com/download').query('key', json.data.key)"
          result-type="HttpRequest"
          :extra-vars="{ json: JSON_VAR }"
          class="min-h-10"
          @update:model-value="(v) => templateDownloadText = v"
        />
      </Field>
    </div>

    <div class="grid grid-cols-2 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('templateIcon')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('templateIcon')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("templateIcon") }}
        </FieldLabel>
        <IconPicker
          :model-value="templateIconText"
          @update:model-value="(v) => templateIconText = v"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template
            v-if="fieldDescription('templateLabel')"
            #tooltip
          >
            <Markdown
              :source="fieldDescription('templateLabel')"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("templateLabel") }}
        </FieldLabel>
        <LocaleField
          translate-hint="download template button label"
          :model-value="value.templateLabel"
          @update:model-value="(v) => value = { ...value, templateLabel: v }"
        />
      </Field>
    </div>

    <div class="grid grid-cols-3 gap-3">
      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('required') ?? '\u8FD4\u56DE `true` \u65F6\u663E\u793A\u5FC5\u586B\u661F\u53F7\u5E76\u8981\u6C42\u975E\u7A7A'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("required") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.required ?? ''"
          placeholder="例：form.type == 'company'"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, required: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('hidden') ?? '\u8FD4\u56DE `true` \u65F6\u5B57\u6BB5\u5728\u6240\u6709\u5E03\u5C40\u4E2D\u90FD\u4E0D\u6E32\u67D3'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("hidden") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.hidden ?? ''"
          placeholder="例：form.role == 'guest'"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, hidden: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('disabled') ?? '\u8FD4\u56DE `true` \u65F6\u4E0A\u4F20\u533A\u57DF\u4ECD\u7136\u6E32\u67D3\u4F46\u4E0D\u53EF\u64CD\u4F5C'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("disabled") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.disabled ?? ''"
          placeholder="例：form.status == 'locked'"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, disabled: v.length > 0 ? v : void 0 }"
        />
      </Field>

      <Field orientation="vertical">
        <FieldLabel class="text-xs text-zinc-500">
          <template #tooltip>
            <Markdown
              :source="fieldDescription('readonly') ?? '\u8FD4\u56DE `true` \u65F6\u4EC5\u4EE5\u6587\u4EF6\u5217\u8868\u5C55\u793A\u5F53\u524D\u503C'"
              block
              class="prose prose-sm prose-zinc"
            />
          </template>
          {{ fieldTitle("readonly") }}
        </FieldLabel>
        <ExpressionEditor
          :model-value="value.readonly ?? ''"
          placeholder="例：form.id != null"
          result-type="bool"
          class="min-h-10"
          @update:model-value="(v) => value = { ...value, readonly: v.length > 0 ? v : void 0 }"
        />
      </Field>
    </div>

    <Field orientation="vertical">
      <FieldLabel class="text-xs text-zinc-500">
        <template #tooltip>
          <Markdown
            :source="fieldDescription('validations')"
            block
            class="prose prose-sm prose-zinc"
          />
        </template>
        {{ fieldTitle("validations") }}
      </FieldLabel>
      <ValidationRulesField
        :model-value="value.validations"
        @update:model-value="(v) => value = { ...value, validations: v.length > 0 ? v : void 0 }"
      />
    </Field>
  </div>
</template>
