<template>
  <scroll-view :scroll-x="!wrap" class="nana-tags">
    <FlexRow :wrap="wrap" align="center" gap="gap.md">
      <Tag 
        v-for="(tag, index) in tags"
        :key="tag.value"
        v-bind="props"
        :text="tag.text"
        :type="value == tag.value || (Array.isArray(value) && value.includes(tag.value)) ? activeType : unActiveType"
        :touchable="!disabled"
        @click="onToggleTag(tag.value)"
        @close="onTagClose(tag.value)"
      />
    </FlexRow>
  </scroll-view>
</template>

<script setup lang="ts">
import { computed, toRef } from 'vue';
import Tag, { type TagProps } from '../display/Tag.vue';
import FlexRow from '../layout/FlexRow.vue';
import { useFieldChildValueInjector } from './FormContext';

export type TagsAcceptKey = string|number;
export interface TagsProps extends TagProps {
  /**
   * 当前选中的标签值，传入数组时为多选模式
   */
  modelValue?: TagsAcceptKey|TagsAcceptKey[];
  /**
   * 标签数据列表
   */
  tags?: {
    value: TagsAcceptKey,
    text: string,
  }[],
  /**
   * 是否禁用
   * @default false
   */
  disabled?: boolean;
  /**
   * 激活时的标签颜色类型
   * @default 'primary'
   */
  activeType?: TagProps['type'];
  /**
   * 非激活时的标签颜色类型
   * @default 'default'
   */
  unActiveType?: TagProps['type'];
  /**
   * 是否换行显示，为 false 时横向滚动
   * @default false
   */
  wrap?: boolean;
}

const props = withDefaults(defineProps<TagsProps>(), {
  modelValue: 50,
  disabled: false,
  size: "small",
  activeType: "primary",
  unActiveType: "default",
  wrap: false,
  tags: () => [],
});

const emit = defineEmits([ 'update:modelValue', 'tagClose' ])

const {
  value,
  updateValue,
  context,
} = useFieldChildValueInjector(
  toRef(props, 'modelValue'), 
  (v) => emit('update:modelValue', v)
);

const isMulitselect = computed(() => Array.isArray(value.value));

function onTagClose(tag: TagsAcceptKey) {
  emit('tagClose', tag);
}
function onToggleTag(tag: TagsAcceptKey) {
  if (isMulitselect.value) {
    const arr = value.value as TagsAcceptKey[];
    if (arr.includes(tag)) {
      arr.splice(arr.indexOf(tag), 1);
    } else {
      arr.push(tag);
    }
    updateValue(arr);
  } else {
    updateValue(tag);
  } 
}

defineOptions({
  options: {
    styleIsolation: "shared",
    virtualHost: true,
  }
})
</script>