<template>
    <div :class="prefixCls">
        <div :class="`${prefixCls}-fixed`">
            <div :class="`${prefixCls}-fixed-clear`">
                <span :class="`${prefixCls}fixed-limit`">
                    {{t('selectMember.selected')}}（{{getSelectedCount()}}/{{limit}}）
                </span>
                <span :class="`${prefixCls}-fixed-btn`" @click="handleClear">
                    {{t('selectMember.clear')}}
                </span>
            </div>
        </div>
        <div :class="`${prefixCls}-content`" :style="{
            height: root.position && (parseInt(root.position.height)  - 152 + 'px')
        }" ref="scrollContent">
            <Scroller ref="scroller">
                <template v-for="(data, key) in selected">
                    <Collapse v-if="Object.keys(data).length"
                        :key="key"
                        :title="tabs[key]">
                        <template slot="title">
                            {{tabs[key]}}
                        </template>
                        <template slot="content">
                            <div :class="`sortable-content-${key}`">
                                <div :class="`${prefixCls}-item sortable-item-${key}`"
                                    v-for="(item, index) in data"
                                    :key="index">
                                    <div :class="`${prefixCls}-item-member`" v-if="item.type === 0">
                                        <Avatar 
                                            size="32px"
                                            fontSize="12px"
                                            :name="item.userName || item.name"
                                            :memberId="item.memberId"
                                            :path="item.avatar"/>
                                        <div :class="`${prefixCls}-item-member-info`">
                                            <div :class="`${prefixCls}-item-member-name`">{{item.userName || item.name}}
                                                <span 
                                                    v-if="item.security"
                                                    :class="`${prefixCls}-item-member-security ${item.security || 'COMMON'}`">
                                                    · {{security[item.security || 'COMMON'].text}}
                                                </span>
                                            </div>
                                            <div :class="`${prefixCls}-item-member-dept`" v-if="root.showMemberOrg && item.orgName">{{item.orgName}}</div>
                                            <div :class="`${prefixCls}-item-member-dept`" v-if="!root.showMemberOrg">{{item.deptName}}</div>
                                            <div :class="`${prefixCls}-item-member-duty`" v-if="root.showMemberOrg && deptAndDuty(item)">{{deptAndDuty(item)}}</div>
                                        </div>
                                    </div>
                                    <div :class="`${prefixCls}-item-dept`" v-if="item.type === 1 && root.showDeptParentName">
                                        <div>{{(root.useShortName && item.shortName) || item.deptName}}</div>
                                        <div>{{(root.useShortName && item.parentShortName) || item.parentName || item.deptName}}</div>
                                    </div>
                                    <div v-else-if="item.type === 1">{{(root.useShortName && item.shortName) || item.deptName}}</div>
                                    <div v-if="item.type === 2">{{item.name}}</div>
                                    <div v-if="item.type === 3">{{item.groupName}}</div>
                                    <div v-if="item.type === 4">{{item.teamName}}</div>
                                    <div v-if="item.type === 5">{{item.name}}</div>
                                    <div v-if="item.type === 6">{{item.roleName}}</div>
                                    <i :class="`${prefixCls}-item-remove`" v-if="!item.disableDelete" @click="handleSelected(item)">
                                        <Icon type="close"/>
                                    </i>
                                </div>
                            </div>
                        </template>
                    </Collapse>
                </template>
            </Scroller>
        </div>
    </div>
</template>
<script>
    import Icon from '../../base/icon/'
    import Avatar from '../../base/avatar/'
    import Collapse from '../../base/collapse/'
    import Scroller from '../../base/scroller/'
    import Locale from '../../../mixins/locale'
    import Sortable from 'sortablejs'

    const prefixCls = 'yy-select-member-153-selected'
    export default {
        name: 'YYSelected',
        mixins: [Locale],
        components: {
            Icon,
            Avatar,
            Collapse,
            Scroller
        },
        inject: ['root'],
        props: {
            selected: {
                type: Object
            },
            limit: {
                type: Number
            }
        },
        data() {
            return {
                tabs: {
                    member: this.t('selectMember.member'),
                    dept: this.t('selectMember.dept'),
                    out: this.t('selectMember.external'),
                    group: this.t('selectMember.group'),
                    team: this.t('selectMember.team'),
                    list: this.t('selectMember.other'),
                    role: this.t('selectMember.role'),
                },
                security: {
					COMMON: {
						text: '一般'
					},
					CORE: {
						text: '核心'
					},
					IMPORTANT: {
						text: '重要'
					}
				},
                prefixCls: prefixCls
            }
        },
        watch: {
            selected: {
                deep: true,
                immediate: true,
                handler() {
                    this.sortable()
                }
            },
            'root.value': function(value) {
                if(value) {
                    this.$refs.scroller.updateScroll()
                }
            }
        },
        methods: {
            deptAndDuty(data) {
                if (data.deptName && data.duty) {
                    return `${data.deptName}(${data.duty})`
                } else if (data.deptName) return data.deptName
                else if (data.duty) return data.duty
                return ''
            },
            sortable() {
                Object.keys(this.selected).forEach((key) => {
                    this.$nextTick().then(()=>{
                        const wrapper = document.querySelector(`.sortable-content-${key}`)
                        const handle = `.sortable-item-${key}`
                        if(wrapper && handle) {
                            Sortable.create(wrapper, {
                                group: {
                                    name: key,
                                    pull: false,
                                    put: true
                                },
                                handle: handle,
                                onUpdate:  (evt) => {
                                    this.handleDragUpdate(evt, key)
                                },
                                animation: 150
                            })
                        }
                    })
                })
            },
            removeNode(node) { // 移除节点
                node.parentElement.removeChild(node)
            },
            insertNodeAt(fatherNode, node, position) { // 插入节点
                let refNode = position === 0 ? fatherNode.children[0] : fatherNode.children[position - 1].nextSibling
                fatherNode.insertBefore(node, refNode)
            },
            handleDragUpdate(evt, key) { // 更新数据的时候
                this.removeNode(evt.item)
                this.insertNodeAt(evt.from, evt.item, evt.oldIndex)
                
                let selectedArr = Object.keys(this.selected[key]).map((item, index)=>{
                    return this.selected[key][item]
                })
                selectedArr.splice(evt.newIndex, 0, selectedArr.splice(evt.oldIndex, 1)[0])
                let selectedMap = {}
                selectedArr.forEach(item => {
                    if(item.type === 0) {
                        selectedMap[`m${item.memberId}`] = item
                    }
                    if(item.type === 1) {
                        selectedMap[`m${item.deptId}`] = item
                    }
                    if(item.type === 2) {
                        selectedMap[`m${item.classId}`] = item
                    }
                    if(item.type === 3) {
                        selectedMap[`m${item.gid}`] = item
                    }
                    if(item.type === 4) {
                        selectedMap[`m${item.teamId}`] = item
                    }
                    if(item.type === 5) {
                        selectedMap[`m${item.id}`] = item
                    }
                    if(item.type === 6) {
                        selectedMap[`m${item.roleId}`] = item
                    }
                })
                this.root.selected[key] = selectedMap
            },
            getSelectedCount() {
                const selected = this.selected
                let count = 0
                Object.keys(selected).forEach((key)=>{
                    count += Object.keys(selected[key]).length
                })
                return count
            },
            handleSelected(data) {
                data.checked = false
                this.$emit('handleSelected', data)
                this.$refs.scroller.updateScroll()
            },
            handleClear() {
                this.root.handleClear()
                this.$refs.scroller.scrollTo(0)
            }
        }
    }
</script>

