<template>
    <div :class="prefixCls">
        <div :class="`${prefixCls}-fixed`" ref="scrollContent">
            <div v-if='insearch' :class="`${prefixCls}-tab ${prefixCls}-tab-active`">
                {{t('selectMember.search')}}
            </div>
            <template v-else-if="root.enableSelectAll">
                <div :class="`${prefixCls}-tabs`" ref="selectAllscrollContent">
                    <div v-for="(tab) in sortedTabs" 
                        :key="tab.key || tab"
                        :class="[
                            `${prefixCls}-tab`,
                            {
                                [`${prefixCls}-tab-active`]: tab === activeTab || tab.key === activeTab
                            }
                        ]"
                        @click="handleSwitchTab(typeof tab == 'object' ? tab.key : tab)">
                        {{getTabName(tab)}}
                    </div>
                </div>
                <div style="width: 50px"></div>
            </template>
            <template v-else>
                <div v-for="(tab) in sortedTabs" 
                    :key="tab.key || tab"
                    :class="[
                        `${prefixCls}-tab`,
                        {
                            [`${prefixCls}-tab-active`]: tab === activeTab || tab.key === activeTab
                        }
                    ]"
                    @click="handleSwitchTab(typeof tab == 'object' ? tab.key : tab)">
                    {{getTabName(tab)}}
                </div>
            </template>
            <div :class="`${prefixCls}-checkbox`" v-if="root.enableSelectAll">
                <TreeCheckbox :checked="selectAllVal" @input="handleSelectAll"/>
            </div>
        </div>
        <div :class="`${prefixCls}-body`" :style="{
            height: root.position && (parseInt(root.position.height)  - 152 + 'px')
        }" v-show="insearch">
            <Search 
                @handleSelected="handleSelected" />
        </div>
        <div :class="`${prefixCls}-body`" :style="{
            height: root.position && (parseInt(root.position.height)  - 152 + 'px')
        }" v-show="!insearch">
            <keep-alive>
                <component 
                    ref="sections"
                    v-for="key in tabsPaneComponent"
                    @handleSelected="handleSelected"
                    :key="key"
                    :excludeDepts="excludeDepts"
                    :withMembers="!!(key.indexOf('Member') != -1)"
                    :forceWithMembers="forceWithMembers"
                    :is="`section-${key.replace(/member/gi, '')}`">
                </component>
                <SectionMember 
                    ref="sections"
                    v-if="activeTab === 'member'"
                    @handleSelected="handleSelected"/>
            </keep-alive>
            <keep-alive 
                v-for="tab in customTabs" 
                :key="tab.key">
                <SectionCustomMember
                    ref="customSections"
                    v-if="activeTab === tab.key && tab.type === 'member'"
                    :data="tab.data || []"
                    :onLoad="tab.onLoad"
                    @handleSelected="handleSelected"/>
                <SectionCustomDept
                    ref="customSections"
                    v-if="activeTab === tab.key && tab.type === 'dept'"
                    :data="tab.data || []"
                    :withMembers="!!tab.withMembers"
                    :onLoad="tab.onLoad"
                    @handleSelected="handleSelected"/>
                <SectionCustomList
                    ref="customSections"
                    v-if="activeTab === tab.key && tab.type === 'list'"
                    :data="tab.data || []"
                    :onLoad="tab.onLoad"
                    @handleSelected="handleSelected"/>
            </keep-alive>
        </div>
    </div>
</template>
<script>
    import SectionRecent from './section/section-recent';
    import SectionDept from './section/section-dept'
    import SectionRole from './section/section-role'
    import SectionGroup from './section/section-group'
    import SectionTeam from './section/section-team'
    import SectionMember from './section/section-member'
    import SectionOut from './section/section-out'
    import SectionCustomMember from './section/section-custom-member'
    import SectionCustomDept from './section/section-custom-dept'
    import SectionCustomList from './section/section-custom-list'
    import Search from './search'
    import PerfectScrollbar from 'perfect-scrollbar'
    import Locale from '../../../mixins/locale'
    import TreeCheckbox from './tree/checkbox'

    const prefixCls = 'yy-select-member-153-section'
    export default {
        name: 'YYSection',
        mixins: [Locale],
        inject: ['root'],
        components: {
            SectionRecent,
            SectionDept,
            SectionGroup,
            SectionTeam,
            SectionMember,
            SectionOut,
            SectionRole,
            SectionCustomMember,
            SectionCustomDept,
            SectionCustomList,
            Search,
            TreeCheckbox
        },
        props: ['tabs', 'selected', 'insearch', 'customTabs', 'defaultActiveTab' ,'forceWithMembers', 'excludeDepts'],
        data() {
            return {
                prefixCls: prefixCls,
                activeTab: this.tabs[0],
                tabsPane: {
                    recentMember: this.t('selectMember.recentMember'),
                    dept: this.t('selectMember.dept'),
                    deptMember: this.t('selectMember.deptMember'),
                    group: this.t('selectMember.group'),
                    groupMember: this.t('selectMember.groupMember'),
                    team: this.t('selectMember.team'),
                    teamMember: this.t('selectMember.teamMember'),
                    member: this.t('selectMember.member'),
                    out: this.t('selectMember.external'),
                    outMember: this.t('selectMember.externalMember'),
                    role: this.t('selectMember.role'),
                    roleMember: this.t('selectMember.roleMember'),
                },
                scroll: null,
                container: null,
                activeSection: null
            }
        },
        computed: {
            tabsPaneComponent() {
                return Object.keys((this.tabsPane)).filter(key => key === this.activeTab && key != 'member')
            },
            sortedTabs() {
                const tabs = [...this.tabs, ...this.customTabs];
                tabs.sort((a, b) => {
                    if (a.sort == undefined && b.sort == undefined) return 0;
                    else if (a.sort == undefined) return 1;
                    else if (b.sort == undefined) return -1;
                    else return a.sort - b.sort;
                })
                return tabs;
            },
            selectAllVal() {
                return this.activeSection && this.activeSection.isAllChecked
            }
        },
        watch: {
            'root.value': function(value) { // 关闭或者打开时重置页签激活状态
                this.activeTab = this.root.defaultActiveTab || this.sortedTabs[0].key || this.sortedTabs[0]
                this.handleSwitchTab(this.activeTab)
            }
        },
        methods: {
            handleSwitchTab(tab) {
                this.activeTab = tab
                if (this.root.enableSelectAll) {
                    this.$nextTick(() => {
                        const sections = this.$refs.sections;
                        const customSections = this.$refs.customSections;
                        if (sections instanceof Array && sections[0]) this.activeSection = sections[0];
                        else if (sections && !(sections instanceof Array)) this.activeSection = sections;
                        else if (customSections instanceof Array && customSections[0]) this.activeSection = customSections[0];
                        else if (!(customSections instanceof Array)) this.activeSection = customSections;
                    })
                }
            },
            handleSelected(data) {
                this.$emit('handleSelected', data)
            },
            setVerticalScroll() {
                this.container = this.root.enableSelectAll ? this.$refs.selectAllscrollContent : this.$refs.scrollContent
                this.scroll = new PerfectScrollbar(this.container, {
                    wheelSpeed: 0.5,
                    wheelPropagation: false,
                    useBothWheelAxes: true,
                    minScrollbarLength: 60,
                    maxScrollbarLength: 300,
                    useBothWheelAxes: true
                })
            },
            setCustomData() {
                if(this.defaultActiveTab) {
                    this.handleSwitchTab(this.defaultActiveTab)
                }
                if(this.customTabs) { // 自定义页签初始数据初始化
                    this.customTabs.forEach(tab => {
                        tab.data && tab.data.forEach(item => {
                            item.checked = item.checked || false
                            item.type = item.type || 0
                            
                            if(tab.type != 'list' && !item.memberId && (item.deptName || item.deptId)) {
                                item.children = []
                                item.expand = !!item.expand
                                item.loading = false
                                item.haveSub = !!item.haveSub
                                item.userNum = 10
                                item.type = item.type || 1
                            }
                            
                            if(tab.type === 'list') {
                                item.type === 5
                            }

                            if(item.checked) {
                                this.handleSelected(item)
                            }
                        })
                    })
                }
            },
            getTabName(tab) {
                if (typeof tab == 'string') return this.tabsPane[tab]
                else if (typeof tab == 'object') return tab.title ? tab.title : this.tabsPane[tab.code]
            },
            initDefaultTab() {
                if (this.defaultActiveTab) {
                    this.activeTab = this.defaultActiveTab;
                    return;
                }
                const tabs = [...this.tabs, ...this.customTabs];
                let first = tabs[0];
                tabs.forEach(e => {
                    if (e.sort != undefined) {
                        if (first.sort == undefined || first.sort > e.sort) first = e;
                    }
                })
                this.activeTab = first.key || first;
            },
            handleClearIndeterminate() {
                const sections = this.$refs.sections
                if (sections) {
                    if (sections instanceof Array) {
                        sections.forEach(section => {
                            if (typeof section.handleClearIndeterminate === 'function') {
                                section.handleClearIndeterminate()
                            }
                        })
                    } else if (typeof sections.handleClearIndeterminate === 'function') {
                        sections.handleClearIndeterminate()
                    }
                }
            },
            handleSelectAll(checked) {
                const sections = this.$refs.sections;
                const customSections = this.$refs.customSections;
                this.handleSectionsSelectAll(checked, sections);
                this.handleSectionsSelectAll(checked, customSections);
            },
            handleSectionsSelectAll(checked, sections) {
                if (sections instanceof Array) {
                    sections.forEach(section => {
                        if (typeof section.handleSelectAll == 'function') {
                            section.handleSelectAll(checked);
                        }
                    })
                } else if (sections && typeof sections.handleSelectAll == 'function') {
                    sections.handleSelectAll(checked);
                }
            }
        },
        created() {
            this.initDefaultTab();
            this.setCustomData();
        },
        activated() {
            this.setCustomData()
        },
        mounted() {
            this.setVerticalScroll();
            this.handleSwitchTab(this.activeTab)
        }
    }
</script>

