<script setup lang="ts">
/**
 * OA 场景 - 钉钉 feedCard 链接列表（links）
 *
 * 用于 dingtalk 平台 feedCard 消息类型的 links 字段编辑。
 * 每条 link 字段对齐钉钉官方结构（DingTalkChannel::buildPayload case 'feedCard'）：
 *   - title       标题（必填）
 *   - messageURL  跳转链接（必填）
 *   - picURL      封面图（可选，从素材库选图片 xk_file.type=0）
 *
 * 受 maxCount 限制（默认 10）。
 */
import { computed } from 'vue';

import { Button, Input } from 'ant-design-vue';

import UploadImage from '#/components/form/components/upload-image.vue';

interface FeedLink {
  title?: string;
  messageURL?: string;
  picURL?: string;
}

const props = withDefaults(
  defineProps<{
    /** 双向绑定的 links 数组 */
    modelValue?: FeedLink[];
    /** 最大条数 */
    maxCount?: number;
  }>(),
  {
    modelValue: () => [],
    maxCount: 10,
  },
);

const emit = defineEmits<{
  'update:modelValue': [value: FeedLink[]];
}>();

const list = computed<FeedLink[]>({
  get: () => (Array.isArray(props.modelValue) ? props.modelValue : []),
  set: (val) => emit('update:modelValue', val),
});

const canAdd = computed(() => list.value.length < props.maxCount);

function updateItem(index: number, key: keyof FeedLink, value: string) {
  list.value = list.value.map((item, i) =>
    i === index ? { ...item, [key]: value } : item,
  );
}

function updateImage(index: number, urls: string[]) {
  updateItem(index, 'picURL', urls[0] || '');
}

function addItem() {
  if (!canAdd.value) return;
  list.value = [...list.value, {}];
}

function removeItem(index: number) {
  list.value = list.value.filter((_, i) => i !== index);
}
</script>

<template>
  <div class="link-list">
    <div
      v-for="(item, idx) in list"
      :key="idx"
      class="link-item"
    >
      <div class="link-head">
        <span class="link-index">链接 {{ idx + 1 }}</span>
        <Button
          type="link"
          size="small"
          danger
          class="link-del"
          @click="removeItem(idx)"
        >
          删除
        </Button>
      </div>

      <div class="link-form">
        <div class="form-row">
          <label class="row-label">
            标题<span class="req">*</span>
          </label>
          <Input
            :value="item.title"
            placeholder="链接标题（必填）"
            size="small"
            allow-clear
            @update:value="(v: string) => updateItem(idx, 'title', v)"
          />
        </div>

        <div class="form-row">
          <label class="row-label">
            跳转链接<span class="req">*</span>
          </label>
          <Input
            :value="item.messageURL"
            placeholder="https://（必填）"
            size="small"
            allow-clear
            @update:value="(v: string) => updateItem(idx, 'messageURL', v)"
          />
        </div>

        <div class="form-row">
          <label class="row-label">封面图（可选）</label>
          <UploadImage
            :model-value="item.picURL ? [item.picURL] : []"
            :multiple="false"
            :max-count="1"
            :accept-types="[0]"
            @update:model-value="(urls: string[]) => updateImage(idx, urls)"
          />
        </div>
      </div>
    </div>

    <Button
      v-if="canAdd"
      type="dashed"
      size="small"
      block
      @click="addItem"
    >
      + 添加链接（{{ list.length }}/{{ maxCount }}）
    </Button>
    <div v-else-if="list.length > 0" class="max-hint">
      已达上限 {{ maxCount }} 条
    </div>
  </div>
</template>

<style scoped lang="scss">
.link-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 100%;
}

.link-item {
  padding: 8px;
  border: 1px solid var(--ant-color-border-secondary, #e5e6eb);
  border-radius: 6px;
}

.link-head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.link-index {
  font-size: 12px;
  font-weight: 600;
  color: var(--ant-color-text-secondary, #4e5969);
}

.link-del {
  padding: 0 4px;
  height: auto;
  font-size: 12px;
}

.link-form {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-row {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.row-label {
  font-size: 11px;
  color: var(--ant-color-text-secondary, #4e5969);
}

.req {
  margin-left: 2px;
  color: var(--ant-color-error, #f53f3f);
}

.max-hint {
  text-align: center;
  font-size: 11px;
  color: var(--ant-color-text-tertiary, #86909c);
}
</style>
