<template>
    <u-row class="bg-white fx-wrap">
        <u-col v-for="tab in list" :key="tab.name" :span="4">
            <view class="fx-row fx-cen-cen f13" style="height: 32px;" @click="current=tab,popShow=true">
                <view class="rel">
                    {{ tab.name }}
                    <u-badge :show="tab.isActived" is-dot :custom-style="dotStyle"></u-badge>
                </view>
                <mx-icons type="arrowdown" class="ml5"></mx-icons>
            </view>
        </u-col>
        <u-col v-if="activedTabs.length" :span="12" class="pl12 pr12">
            <view class="fx-row fx-bet-cen pl12 pr12 pb10">
                <view class="fx-row fx-wrap">
                    <u-tag v-for="item in activedItems" :key="item.text" :text="item.text" type="success" size="mini"
                           plain closable @close="handleSingleRemove(item)"/>
                </view>
                <u-icon name="trash" @click="handleResetAll"></u-icon>
            </view>
        </u-col>
        <u-popup v-if="current" :show="popShow" mode="top" @close="popShow=false">
            <scroll-view class="popup-scroll-view" scroll-y>
                <component :is="current.popType" ref="popFilter" :filter="filter" :batch="batch"/>
            </scroll-view>
            <view class="text-right pd12">
                <view class="fx-inline">
                    <u-button size="small" text="重置" class="mr10" @click="handleReset"/>
                    <u-button size="small" type="primary" text="确认" @click="handleConfirm"/>
                </view>
            </view>
        </u-popup>
    </u-row>
</template>

<script>
import RecommendFilterPickType from './recommend-filter-pick-type.vue'
import RecommendFilterExtra from './recommend-filter-extra.vue'
import RecommendFilterMajor from './recommend-filter-major.vue'
import RecommendFilterCollege from "./recommend-filter-college.vue"
import MxConst from '@/common/MxConst'
import * as Ext from '@/common/tools/ext'
import SearchMajorInjectionMixin from "@/pagesOther/pages/voluntary/components/SearchMajorInjectionMixin";

export default {
    name: 'recommend-filter-group',
    components: {
        RecommendFilterPickType,
        RecommendFilterExtra,
        RecommendFilterMajor,
        RecommendFilterCollege
    },
    mixins: [SearchMajorInjectionMixin],
    inject: ['fetchOptionKeys'],
    props: {
        filter: {
            type: Object,
            default: () => ({})
        },
        batch: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            dotStyle: {
                position: 'absolute',
                right: '-4px',
                top: 0
            },
            list: [
                {
                    name: '概率筛选',
                    isActived: false,
                    popType: 'recommend-filter-pick-type',
                    refreshAction: this.pickTypeActived,
                    getActiveItems: this.getActivePickTypes
                },
                {
                    name: '院校筛选',
                    isActived: false,
                    popType: 'recommend-filter-college',
                    refreshAction: this.collegeActived,
                    getActiveItems: this.getActiveCollegeFilters
                },
                // {
                //     name: '专业筛选',
                //     isActived: false,
                //     popType: 'recommend-filter-major',
                //     refreshAction: this.majorActived,
                //     getActiveItems: this.getActiveMajors
                // }
            ],
            current: null,
            popShow: false
        }
    },
    computed: {
        activedTabs() {
            return this.list.filter(tab => tab.isActived)
        },
        activedItems() {
            return this.activedTabs.reduce((total, cur) => {
                total.push(...cur.getActiveItems())
                return total
            }, [])
        },
        collegeOptionKeys() {
            return this.fetchOptionKeys()
        }
    },
    watch: {
        filter: {
            immediate: true,
            deep: true,
            handler: function () {
                this.list.forEach(tab => {
                    tab.isActived = !!tab.refreshAction() // force to boolean
                })
            }
        }
    },
    methods: {
        closePopup() {
            this.popShow = false
        },
        pickTypeActived() {
            return this.filter.pickType
        },
        extraActived() {
            return this.filter.collect !== '' || this.filter.sinoforeign !== '' ||
                this.filter.specialProjectNation !== '' || this.filter.specialProjectLocal !== '' ||
                this.filter.specialProjects.length
        },
        majorActived() {
            return this.filter.majors?.length
        },
        collegeActived() {
            return this.collegeOptionKeys.some(k => this.filter[k.writeKey]?.length)
        },
        handleReset() {
            this.$refs.popFilter.handleReset()
        },
        handleConfirm() {
            const changed = this.$refs.popFilter.handleConfirm()
            if (changed === undefined) return // special situation
            this.popShow = false
            if (changed) this.$emit('search')
        },
        // shortcut
        getActivePickTypes() {
            const match = MxConst.enum.simulatePickTypes.find(t => t.value == this.filter.pickType)
            return [{
                text: match.text,
                handler: () => this.filter.pickType = ''
            }]
        },
        getActiveExtras() {
            const results = []
            if (this.filter.sinoforeign !== '') {
                const foreignMatch = MxConst.enum.sinoforeignOptions.find(f => f.value === this.filter.sinoforeign)
                if (foreignMatch) {
                    results.push({
                        text: foreignMatch.label,
                        handler: () => this.filter.sinoforeign = ''
                    })
                }
            }
            if (this.filter.collect !== '') {
                const collectMatch = MxConst.enum.collectOptions.find(c => c.value === this.filter.collect)
                if (collectMatch) {
                    results.push({
                        text: collectMatch.label,
                        handler: () => this.filter.collect = ''
                    })
                }
            }
            if (this.filter.specialProjectNation !== '') {
                const nationMatch = MxConst.enum.specialProjectNationOptions.find(n => n.value === this.filter
                    .specialProjectNation)
                results.push({
                    text: nationMatch.label,
                    handler: () => this.filter.specialProjectNation = ''
                })
            }
            if (this.filter.specialProjectLocal !== '') {
                const localMatch = MxConst.enum.specialProjectLocalOptions.find(l => l.value === this.filter
                    .specialProjectLocal)
                results.push({
                    text: localMatch.label,
                    handler: () => this.filter.specialProjectLocal = ''
                })
            }
            this.filter.specialProjects.forEach(spFilter => {
                results.push({
                    text: spFilter,
                    handler: () => Ext.arrayRemove(this.filter.specialProjects, spFilter)
                })
            })
            return results
        },
        getActiveMajors() {
            return this.filter.majors.map(major => ({
                text: major,
                handler: () => Ext.arrayRemove(this.filter.majors, major)
            }))
        },
        getActiveCollegeFilters() {
            const results = []
            this.collegeOptionKeys.forEach(k => {
                results.push(...this.filter[k.writeKey].map(v => ({
                    text: v,
                    handler: () => Ext.arrayRemove(this.filter[k.writeKey], v)
                })))
            })
            return results
        },
        handleSingleRemove(item) {
            item.handler()
            this.$nextTick(() => this.$emit('search'))
        },
        clearMajorFilters() {
            this.filter.majors = []
            this.updateCheckedList(this.filter.majors)
        },
        clearCollegeFilters() {
            this.collegeOptionKeys.forEach(k => this.filter[k.writeKey] = [])
        },
        handleResetAll() {
            this.filter.pickType = ''
            this.filter.sinoforeign = ''
            this.filter.collect = ''
            this.filter.specialProjectNation = ''
            this.filter.specialProjectLocal = ''
            this.filter.specialProjects = []
            this.clearMajorFilters()
            this.clearCollegeFilters()
            this.$nextTick(() => this.$emit('search'))
        }
    }
}
</script>

<style lang="scss" scoped>
.popup-scroll-view {
  max-height: 40vh;
  height: fit-content;
}
</style>
