<template>
    <view :class="`easy-combobox-option${selected ? ' easy-combobox-selected' : ''}`" @tap="clickOption">
        <slot>{{text}}</slot>
    </view>
</template>

<script>
    let root = null;
    export default {
        name: "easy-combobox-option",
        props: {
            value: {
                default: ''
            },
            text: {
                type: String
            },
            checked: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                selected: true
            };
        },
        created() {
            this.selected = this.checked;
            root = this.getParent();
            root.addOption(this);
        },
        methods: {
            select() {
                this.selected = true;
            },

            unselect() {
                this.selected = false;
            },

            clickOption() {
                root.select(this);
            },

            getOption() {
                return {
                    value: this.value,
                    text: this.text
                };
            },

            getParent(name = 'easy-combobox') {
                let parent = this.$parent;
                let parentName = parent.$options.name;
                while (parentName !== name) {
                    parent = parent.$parent;
                    if (!parent) return false;
                    parentName = parent.$options.name;
                }
                return parent;
            }
        }
    }
</script>

<style lang="scss">
    .easy-combobox-option {
        position: relative;
        font-size: 26upx;
        padding: 0 30upx;
        text-wrap: nowrap;
        height: 70upx;
        display: flex;
        align-items: center;
    }

    .easy-combobox-option+.easy-combobox-option {
        border-top: 1upx solid #dfdfdf;
    }

    .easy-combobox-option.easy-combobox-selected {
        background-color: #cde6ff;
    }
</style>