<template>
    <view class="fx-row items-center gap-5" @click="handleClick" @touchmove.stop>
        <text class="whitespace-nowrap relative" :class="{'text-primary': opening, 'text-fired': fired}">
            {{ display }}
        </text>
        <uv-icon :name="opening?'arrow-up':'arrow-down'" :color="opening?'primary':undefined"/>
    </view>
</template>

<script setup>
import {computed} from 'vue';
import {createPropDefine} from "@/utils";
import {useInjectSearchModel} from "@/components/mx-condition/useSearchModelInjection";
import {toValue} from "@vueuse/core";
import {useInjectConditionDropdownPopup} from "@/components/mx-condition-dropdown/useConditionDropdownPopupInjection";

const props = defineProps({
    condition: createPropDefine({}, Object),
    useValueAsTitle: createPropDefine(false, Boolean)
})

const {popup} = useInjectConditionDropdownPopup()
const {queryParams} = useInjectSearchModel()
const list = computed(() => props.condition.list)
const config = computed(() => props.condition.config)
const current = computed(() => toValue(queryParams)[config.value.key])
const currentItems = computed(() => list.value.filter(i => [].concat(current.value).includes(getValue(i))))
const display = computed(() => {
    if (props.useValueAsTitle && currentItems.value.length == 1) return getLabel(currentItems.value[0])
    return config.value.title
})
const fired = computed(() => {
    // 命中的是默认条件
    if (currentItems.value.length == 1 && !getValue(currentItems.value[0])) return false
    // 有条件命中了
    return !props.useValueAsTitle && currentItems.value.length > 0
})
const opening = computed(() => popup.value?.condition == props.condition) // 当前弹窗打开

const getLabel = (item) => config.value.keyName ? item[config.value.keyName] : item
const getValue = (item) => config.value.keyValue ? item[config.value.keyValue] : item

const handleClick = () => {
    popup.value.open(props.condition)
}
</script>

<style scoped lang="scss">
.text-fired::before {
    content: ' ';
    position: absolute;
    top: 0;
    right: -3px;
    width: 6px;
    height: 6px;
    border-radius: 3px;
    background-color: var(--error-light-color);
}
</style>