<script>
import { createComponentName, componentMixin } from '../_utils/component';
import item from './Item';
import _get from 'lodash/get';

export default {
    name: createComponentName('filter'),
    components: {
        item,
    },
    mixins: [componentMixin],

    props: {
        tags: {
            type: Array,
            default: () => ([]),
        },
        hides: {
            type: Array,
            default: () => ([]),
        },
    },

    data() {
        return {
            maps: {},
        };
    },

    watch: {
        maps: {
            handler(value) {
                const ids = Object.values(value).filter(Boolean);
                this.$emit('change', ids);
            },
            deep: true,
        },
    },

    mounted() {
        // 映射关系
        const { filter = [] } = this.$route.query;

        this.maps = this.tags.reduce((prev, curr) => {
            const item = curr.lists.find(o => filter.includes(String(o.id)));
            let val = item ? item.id : null;
            // 某些筛选项需要自定义隐藏选择全部的按钮
            if (!val && this.hides.includes(curr.name)) {
                val = _get(curr, 'lists[0].id');
            }

            prev[curr.name] = val;
            return prev;
        }, {});
    },

    methods: {
        selected(name, id, index, parentIndex) {
            this.maps[name] = id;
            this.$emit('selected', { name, id, index, parentIndex });
        },
    },

    render() {
        return (
            <div class={this.bem()}>
                {
                    this.tags.map((item, index) => {
                        return <item
                            info={item}
                            key={index}
                            parentIndex={index}
                            selected={this.selected}
                            visiableAllBtn={!this.hides.includes(item.name)}
                            selectId={this.maps[item.name]} />;
                    })
                }
            </div>
        );
    },
};
</script>

<style lang="less">
@import '../_styles/base.less';
@b: ~'@{prefix}-filter';

.@{b} {
    border-bottom: 1px solid @border-color-default;
    padding: 24px 0 8px;
}

</style>
