<template>
    <Scroller ref="scroller">    
        <DeptNode 
            v-for="(item, index) in list"
            @handleExpand="handleExpand"
            @handleChecked="handleChecked"
            @getDeptChildList="getDeptChildList"
            :data="item"
            :key="index"
            :excludeDepts="excludeDepts"
            :withMembers="withMembers" />
        <Load 
            v-if="!root.deptList"
            :hasData="!!list.length"
            :hasMore="hasMore"
            :loading="loading" 
            @on-load="getDeptList"/>
        <Empty v-if="!loading && !hasMore && !list.length"/>
    </Scroller>
</template>
<script>
    /**
     * 组织
     *  */
    import DeptNode from './section-dept-node'
    import Section from '../mixins/section'
    import Empty from '../../../base/empty/'
    import Message from '../../../base/message/'
    import { t } from '../../../../locale/'
    import axios from 'axios'

    export default {
        name: 'YYSectionDept',
        mixins: [Section],
        components: {
            DeptNode,
            Empty
        },
        inject: ['root'],
        props: {
            withMembers: {
                type: Boolean,
                default: false
            },
            forceWithMembers: {
                type: Boolean,
                default: false
            },
            excludeDepts: {
                type: Array,
                default() {
                    return []
                }
            }
        },
        computed: {
            isAllChecked() {
                return this.list.length && this.list.every(data => data.checked || data.indeterminate)
            }
        },
        methods: {
            getDeptList(deptId, params, checked, isFirst) { // 拉取当前组织树
                this.loading = true
                params && (params.loading = true)
                const { host, qzId, orgId, chooseDeptType, chooseDeptMemberType, language, security, token, deptFirst } = this.root
                const withMembers = this.forceWithMembers ? 1 : (1 - !(+deptId && this.withMembers))
                axios.get(`${host}/cooperation/rest/v1/candidate/${qzId}/depts`, {
                    params: {
                        withMembers,
                        deptIds: deptId || orgId || 0,
                        size: 9999,
                        type: chooseDeptType,
                        language: language,
                        security: security,
                        token: token,
                        deptFirst: deptFirst,
                        includeDuty: !!withMembers
                    },
                    withCredentials: true
                }).then(res => {
                    let data = res && res.data || []
                    let members = []
                    data.forEach(item => {
                        item.expand = false
                        item.checked = false
                        item.contain = false
                        item.children = []
                        item.loading = false
                        if (params) {
                            item.parentName = params.deptName;
                            item.parentShortName = params.shortName;
                        } else {
                            item.parentName = item.deptName;
                            item.parentShortName = item.shortName;
                        }

                        if(this.withMembers) {
                            item.indeterminate = false
                        }
                        // 当存在父级， 并且为人员，只选择一级下面的人
                        if(params && +item.type === 0 && chooseDeptMemberType == 1) {
                            if(checked) {
                                item.parent = params
                                item.checked = checked
                                this.$emit('handleSelected', item)
                            }
                            members.push(item)
                        }
                    })

                    if(params && chooseDeptMemberType == 1 && this.withMembers) {
                        params.members = members
                    }
                    this.loading = false
                    this.hasMore = false

                    if (this.excludeDepts && this.excludeDepts.length) {
                        data = data.filter(e => this.excludeDepts.indexOf(e.deptId) == -1)
                    }

                    if(isFirst) {
                        return this.list = this.list.concat(data)
                    }
                    params && (params.children = data)
                    params && (params.loading = false)
                }).catch(error => {
                    this.handleError(params || null)
                })
            },
            getMyDept() { // 获取我的部门
                const { host, qzId, language, token } = this.root
                axios.get(`${host}/cooperation/rest/v1/candidate/${qzId}/dept`, {
                    params: {
                        withMembers: 1 - !this.withMembers,
                        language: language,
                        token: token
                    },
                    withCredentials: true
                }).then(res => {
                    let data = res && res.data || []
                    data.forEach(item => {
                        item.deptName = item.deptName + "（本部门）"

                        item.userNum = 1
                        item.expand = false
                        item.checked = false
                        item.contain = false
                        item.loading = false
                        item.children = []
                        if(this.withMembers) {
                            item.indeterminate = false
                        }
                    })
                    if(data.length) this.list.unshift(data[0])
                })
            },
            // containDept 2021新加需求，包含下级组织按钮，不管左侧待选是否包含部门
            getDeptChildList(deptId, params, containDept) { // 包含下级接口
                const { enableOrg } = this.root
                params.contain = !params.contain
                params.checked = params.contain
                
                if(enableOrg || +params.orgType === 0) { // 不允许选择组织情况下
                    this.$emit('handleSelected', params)
                } 
                if(params.data) {
                    return params.data.forEach(item => {
                        item.checked = params.contain
                        this.$emit('handleSelected', item)
                    })
                }
                params.loading = true
                const { host, qzId, language, chooseDeptType, token } = this.root
                axios.get(`${host}/cooperation/rest/v1/candidate/${qzId}/${deptId}/sub_depts`, {
                    params: {
                        language: language,
                        type: containDept ? chooseDeptType : 2,
                        token: token
                    },
                    withCredentials: true
                }).then(res => {
                    let data = res && res.data || []
                    data.forEach(item => {
                        item.checked = params.contain;
                        item.parentName = params.deptName;
                        item.parentShortName = params.shortName;
                        if(enableOrg || +item.orgType === 0) { // 不允许选择组织情况下
                            this.$emit('handleSelected', item)
                        }
                    })
                    params.loading = false
                    params.data = data
                }).catch(error => {
                    this.handleError(params)
                })
            },
            getDeptMemberList(deptId, params, checked) { // 拉取当前组织下人员
                params.loading = true
                const { host, qzId, chooseDeptType, language, security, token } = this.root

                axios.get(`${host}/cooperation/rest/v1/candidate/${qzId}/members`, {
                    params: {
                        deptIds: deptId,
                        size: 9999,
                        type: chooseDeptType,
                        language: language,
                        security: security,
                        token: token,
                        includeDuty: true
                    },
                    withCredentials: true
                }).then(res => {
                    let data = res && res.data || []
                    data.forEach(item => {
                        item.parent = params
                        item.checked = !!checked
                        this.$emit('handleSelected', item)
                    })
                    params.members = data
                    params.loading = false
                }).catch(error => {
                    params.loading = false
                })
            },
            handleExpand(expand, data) {
                data.expand = expand
                if(data.children && data.children.length) return
                this.getDeptList(data.deptId, data)
            },
            handleChecked(checked, data) {
                if(data.loading) return false
                if(!this.withMembers || +data.type === 0) { // 如果只选择组织或者单选人员
                    if(checked && 1 + this.root.selectedCount > this.root.limit && this.root.limit != 1) {
                        Message.warning(t('selectMember.maximum'))
                        return false
                    }
                    data.checked = checked
                    this.$emit('handleSelected', data)
                    return true
                }
                if(checked && data.userNum + this.root.selectedCount > this.root.limit) {
                    Message.warning(t('selectMember.maximum'))
                    return false
                }
                // 按照部门选择人员的时候
                this.$set(data, 'indeterminate', checked)
                // data.indeterminate = checked
                if(data.members && data.members.length) {
                    data.members.forEach(item => {
                        item.checked = !!checked
                        this.$emit('handleSelected', item)
                    })
                    return true
                } 
                if(this.root.chooseDeptMemberType == 1) {
                    this.getDeptList(data.deptId, data, checked)
                } else {
                    this.getDeptMemberList(data.deptId, data, checked)
                }
                return true;
            },
            handleClearIndeterminate () {
                clearIndeterminate(this.list)
                function clearIndeterminate(list) {
                    if (list && list instanceof Array) {
                        list.forEach(e => {
                            if (e.indeterminate != undefined) e.indeterminate = false
                            if (e.children && e.children.length > 0) {
                                clearIndeterminate(e.children)
                            }
                        })
                    }
                }
            },
            init() {
                if(this.root.deptList && this.root.deptList.length) return
                if(this.root.chooseDeptType != 2 && this.root.showMyDept) {
                    this.getMyDept()
                }
                this.getDeptList(null, null, null, true)
            }
        },
        created() {
            this.init()
        },
        activated() { // 每次激活更新当前组织列表
            if(this.root.deptList && this.root.deptList.length) { // 如果传根组织列表了 一级为当前传入的组织
                return this.list = this.root.deptList.map((item)=>{
                    return {
                        ...item,
                        loading: false,
                        checked: false,
                        expand: false,
                        indeterminate: false,
                        type: 1,
                        haveSub: 1,
                        userNum: 1,
                        children: []
                    }
                })
            }
        }
    }
</script>
