<template>
    <div class="office-select-box">
        <el-dialog
            title="部门选择"
            width="800px"
            :close-on-click-modal="false"
            :append-to-body="true"
            v-dialogDrag
            :visible.sync="visible"
            class="select-modal-box">
            <div class="select-modal-body">
                <!--搜索-->
                <div style="overflow: hidden">
                    <div style="float: left">
                        <el-form :inline="true" ref="contactSearchForm" @keyup.enter.native="searchTabForm()" @submit.native.prevent>
                            <el-form-item prop="name">
                                <el-input v-model="contactOfficeName" placeholder="请输入名称" clearable>
                                    <el-button slot="append" icon="el-icon-search" @click="searchTabForm()"></el-button>
                                </el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                    <div style="float: right">
                        <el-button @click="visible = false">取消</el-button>
                        <el-button type="danger" @click="doSubmit()">确定</el-button>
                    </div>
                </div>
                
                <el-row>
                    <el-col :span="15">
                        <el-tabs :tab-position="'left'" @tab-click="handleTabClick" v-model="activeTabName">
                            <el-tab-pane name="contact">
                                <div slot="label" class="tab-pane">
                                    <span>常用单位</span>
                                </div>
                                <el-table
                                    :data="contactOfficeList"
                                    v-loading="contactLoading"
                                    size="medium"
                                    ref="contactOfficeTable"
                                    height="500"
                                    @selection-change="selectionChangeHandle"
                                    @row-click="handleRowClick"
                                    @select-all="allSelect"
                                    @select="handleRowSelect"
                                    style="width: 100%;">
                                    <el-table-column
                                        type="selection"
                                        header-align="center"
                                        align="center"
                                        width="50" :selectable="checkSelectableCondition">
                                    </el-table-column>
                                    <el-table-column
                                        prop="name"
                                        show-overflow-tooltip
                                        align="left"
                                        label="部门名称">
                                    </el-table-column>
                                </el-table>
                            </el-tab-pane>
                            <el-tab-pane name="all">
                                <div slot="label" class="tab-pane">
                                    <span>所有单位</span>
                                </div>
                                <div class="right-box" style="border-right: 0">
                                    <div class="title">所有单位</div>
                                    <el-scrollbar class="allOffice" style="height: 452px">
                                        <el-tree
                                            show-checkbox
                                            check-strictly
                                            node-key="id"
                                            ref="tree"
                                            :load="loadNode"
                                            lazy
                                            :props="{
                                                      value: 'id',             // ID字段名
                                                      label: 'shortName',         // 显示名称
                                                      children: 'children'    // 子级字段名
                                                    }"
                                            :filter-node-method="filterNode"
                                            @check="getCheckedNodes"></el-tree>
                                    </el-scrollbar>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane v-for="(officeGroup, index) in officeGroupList"
                                         :key="'officeGroupPanel' + officeGroup.id" :label="officeGroup.name"
                                         :name="officeGroup.id">
                                <div slot="label" class="tab-pane">
                                    <span>{{ officeGroup.name }}</span>
                                </div>
                                <el-table
                                    :data="officeGroupOfficeTreeList[officeGroup.id]"
                                    v-loading="officeGroupTreeListLoading[officeGroup.id]"
                                    border
                                    size="medium"
                                    :ref="officeGroupOfficeTable[officeGroup.id]"
                                    height="500"
                                    row-key="id"
                                    default-expand-all
                                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                                    @selection-change="selectionChangeHandle"
                                    @row-click="handleRowClick"
                                    @select="handleRowSelect">
                                    <el-table-column
                                        type="selection"
                                        header-align="center"
                                        align="center"
                                        width="50" :selectable="checkSelectableCondition">
                                    </el-table-column>
                                    <el-table-column
                                        prop="name"
                                        show-overflow-tooltip
                                        align="left"
                                        label="部门名称">
                                    </el-table-column>
                                </el-table>
                            </el-tab-pane>
                        </el-tabs>
                    </el-col>
                    <!--右侧已选人员-->
                    <el-col :span="9" class="right-box">
                        <div class="title">已选部门</div>
                        <el-scrollbar class="allOffice" style="height: 452px">
                            <div class="tag-box">
                                <el-tag v-for="tag in dataListSelections"
                                        :key="tag.id"
                                        closable
                                        :disable-transitions="false"
                                        @close="handleDelTag(tag)">
                                    {{ tag.name }}
                                </el-tag>
                            </div>
                        </el-scrollbar>
                    </el-col>
                </el-row>
            </div>
            <!--<span slot="footer" class="dialog-footer">
                <el-button @click="visible = false">关闭</el-button>
                <el-button type="primary" @click="doSubmit()">确定</el-button>
            </span>-->
        </el-dialog>
    </div>
</template>

<script>
import Vue from 'vue'

export default {
    data() {
        return {
            visible: false,     // 是否显示当前选择框
            activeTabName: 'contact',   //默认打开近期联系人面板
            searchForm: {       // 人员列表检索表单
                name: ''
            },
            dataListSelections: [],
            dataListSelectionsMap: {},
            pageNo: 1,          // 分页查询, 暂时固定
            pageSize: 10,       // 分页数量, 暂时不用
            orderBy: '',        // 排序字段, 默认为部门排序字段sort
            contactOfficeName: '',    // 近期联系人搜索关键字
            contactLoading: false,     // 是否显示加载图标
            contactOfficeList: [],    // 近期联系人列表
            searchOfficeName: '',   // 全部人员的人员列表检索关键字
            allLoading: false,     // 是否显示加载图标
            allOfficeTreeList: [],     // 全部人员的组织机构树列表\
            officeGroupList: [],    // 自定义组织机构面板列表
            currentOfficeGroupId: '',   // 当前已激活的自定义组织机构面板的组ID
            officeGroupOfficeTable: {},  // 自定义组织机构面板内的表格引用
            officeGroupSearchOfficeName: {},  //自定义组织机构面板内的搜索
            officeGroupTreeListLoading: {},  // 自定义组织机构面板内的loading
            officeGroupOfficeTreeList: {},  // 自定义组织机构面板内的组织机构树
            parentId: '',
            checkList: []
        }
    },
    props: {
        selectData: {
            type: Array,
            default: () => {
                return []
            }
        },
        limit: {
            type: Number,
            default: 0
        },
        checkSelectable: ''
    },
    watch: {
        contactOfficeName(val) {
            if (this.activeTabName === 'all') {
                this.$refs.tree.filter(val)
            }
        }
    },
    created() {
        // this.refreshAllOfficeTree()
    },
    methods: {
        loadNode(node, resolve) {
            //如果展开第一级节点，从后台加载一级节点列表
            if (node.level === 0) {
                this.loadfirstnode(resolve)
            }
            //如果展开其他级节点，动态从后台加载下一级节点列表
            if (node.level >= 1) {
                this.loadchildnode(node, resolve)
            }
        },
        //加载第一级节点
        loadfirstnode(resolve) {
            this.$http({
                url: '/sys/office/list',
                method: 'get',
                params: {
                    'parent.id': '0'
                }
            }).then(({data}) => {
                return resolve(data.list)
            })
        },
        //加载节点的子节点集合
        loadchildnode(node, resolve) {
            this.$http({
                url: '/sys/office/list',
                method: 'get',
                params: {
                    'parent.id': node.data.id
                }
            }).then(({data}) => {
                return resolve(data.list)
            })
        },
        init() {
            this.dataListSelections = []
            this.visible = true
            this.$nextTick(() => {
                this.dataListSelections = JSON.parse(JSON.stringify(this.selectData))
                this.resetSearch()
                // this.refreshAllOfficeTree()
                this.refreshOfficeGroups()
                this.resetContactSearch()
            })
        },
        filterNode(value, data) {
            if (!value) return true
            return data.name.indexOf(value) !== -1
        },
        searchTabForm() {
            if (this.activeTabName === 'contact') {
                this.refreshSearchOfficeList()
            }
        },
        // 设置选中的方法
        setSelectRow() {
            this.$refs.contactOfficeTable.clearSelection()
            // this.$refs.allOfficeTable.clearSelection()
            if (!this.dataListSelections || this.dataListSelections.length <= 0) {
                return
            }
            // 标识当前行的唯一键的名称
            let selectAllIds = []
            this.dataListSelections.forEach(row => {
                selectAllIds.push(row['id'])
            })
            if (this.limit === 1) {
                this.dataListSelections = [this.dataListSelections[this.dataListSelections.length - 1]]
            } else if (this.limit > 0 && this.dataListSelections.length > this.limit) {
                this.$message({
                    showClose: true,
                    message: `你最多只能选择 ${this.limit} 个用户！`,
                    type: 'warning'
                })
            }
            // 设置联系人表格选中项
            for (let i = 0; i < this.contactOfficeList.length; i++) {
                if (selectAllIds.indexOf(this.contactOfficeList[i]['id']) >= 0) {
                    this.$refs.contactOfficeTable.toggleRowSelection(this.contactOfficeList[i], true)
                }
            }
            // 设置自定义组织机构部门用户表格选中项
            if (this.officeGroupList && this.officeGroupList.length > 0 && this.currentOfficeGroupId) {
                let vue = this
                this.officeGroupList.forEach(officeGroup => {
                    let table = vue.$refs.officeGroupOfficeTable[officeGroup.id]
                    table.clearSelection()
                    if (selectAllIds.indexOf(this.officeGroupOfficeTreeList[officeGroup.id]['id']) >= 0) {
                        table.toggleRowSelection(this.officeGroupOfficeTreeList[officeGroup.id], true)
                    }
                })
            }
        },
        // 标签选项卡切换事件
        handleTabClick(tab) {
            if (tab.name === 'contact') {
                this.searchForm.name = this.contactOfficeName
            } else if (tab.name === 'all') {
                this.searchForm.name = this.searchOfficeName
            } else {
                this.searchForm.name = this.officeGroupSearchOfficeName[this.currentOfficeGroupId]
                this.currentOfficeGroupId = tab.name
            }
        },
        // 加载所有左侧tab标签页及标签页内的组织机构树
        refreshOfficeGroups() {
            this.$http({
                url: '/sys/officeGroup/list',
                method: 'get',
                params: {
                    'pageNo': this.pageNo,
                    'pageSize': -1
                }
            }).then(({data}) => {
                if (data && data.success) {
                    this.officeGroupList.forEach(officeGroup => {
                        Vue.set(this.officeGroupSearchOfficeName, officeGroup.id, '')
                        Vue.set(this.officeGroupTreeListLoading, officeGroup.id, false)
                        this.refreshOfficeGroupOfficeTree(officeGroup.id)
                    })
                    this.officeGroupList = data.page.list
                }
            })
        },
        // 加载常用联系人列表
        refreshContactOfficeList() {
            this.contactLoading = true
            this.$http({
                url: '/sys/office/list',
                method: 'get',
                params: {
                    'pageNo': this.pageNo,
                    'pageSize': -1,
                    name: this.contactOfficeName
                }
            }).then(({data}) => {
                if (data && data.success) {
                    var dataList = data.page.list
                    this.contactOfficeList = dataList
                }
                this.$nextTick(() => {
                    this.setSelectRow()
                })
                this.contactLoading = false
            }).catch(() => {
                this.contactLoading = false
            })
        },
        // 搜索
        refreshSearchOfficeList() {
            this.contactLoading = true
            this.$http({
                url: '/sys/office/list',
                method: 'get',
                params: {
                    'pageNo': this.pageNo,
                    'pageSize': -1,
                    name: this.contactOfficeName
                }
            }).then(({data}) => {
                if (data && data.success) {
                    var dataList = data.list
                    this.contactOfficeList = dataList
                }
                this.$nextTick(() => {
                    this.setSelectRow()
                })
                this.contactLoading = false
            }).catch(() => {
                this.contactLoading = false
            })
        },
        resetContactSearch() {
            this.contactOfficeName = ''
            this.refreshContactOfficeList()
        },
        // 加载"所有单位"的组织机构树
        refreshAllOfficeTree() {
            this.allLoading = true
            this.$http({
                url: `/sys/office/treeData`,
                method: 'get',
                params: {
                    name: this.searchOfficeName
                }
            }).then(({data}) => {
                if (data && data.success) {
                    this.allOfficeTreeList = data.treeData
                }
                this.allLoading = false
            }).catch(() => {
                this.allLoading = false
            })
        },
        resetAllOfficeSearch() {
            this.searchOfficeName = ''
            // this.refreshAllOfficeTree()
        },
        refreshOfficeGroupOfficeTree(id) {
            this.officeGroupTreeListLoading[id] = true
            this.$http({
                url: '/sys/officeGroup/officeTreeData',
                method: 'get',
                params: {
                    'id': id,
                    name: this.officeGroupSearchUserName[id] || ''
                }
            }).then(({data}) => {
                if (data && data.success) {
                    Vue.set(this.officeGroupOfficeTreeList, id, data.treeData)
                }
                this.officeGroupTreeListLoading[id] = false
            }).catch(() => {
                this.officeGroupTreeListLoading[id] = false
            })
        },
        resetOfficeGroupOfficeSearch(id) {
            this.officeGroupSearchUserName[id] = ''
            this.refreshOfficeGroupOfficeTree(id)
        },
        // 处理单行选中或取消选中, 判断选中项最后不在选中结果里, 说明删除了元素, 在结果中删除本元素
        handleRowSelect(selections, currentRow) {
            let result = selections.filter(row => row.id === currentRow.id)
            if (result.length === 0) {
                this.dataListSelections.splice(this.dataListSelections.findIndex(row => row.id === currentRow.id), 1)
            }
        },
        handleRowClick(row, index) {
            //
        },
        allSelect(selection) {
            if (selection.length === 0) {
                this.dataListSelections = []
            }
        },
        dataChange(data) {
            let obj = []
            let nums = data.length
            for (var i = 0; i < nums; i++) {
                if (data[i].id === this.parentId) {
                    obj.push(data[i])
                    return obj
                } else {
                    if (data[i].children !== undefined) {
                        obj = this.dataChange(data[i].children)
                        if (obj.length > 0) {
                            obj.push(data[i])
                        }
                    }
                }
                if (i === nums - 1) {
                    return obj
                }
            }
        },
        // 单位树节点点击
        getCheckedNodes() {
            var nodes = this.$refs.tree.getCheckedNodes()
            this.dataListSelections = nodes
            // 标识当前行的唯一键的名称
            let selectAllIds = []
            this.dataListSelections.forEach(row => {
                selectAllIds.push(row['id'])
            })
            // 设置联系人表格选中项
            for (let i = 0; i < this.contactOfficeList.length; i++) {
                if (selectAllIds.indexOf(this.contactOfficeList[i].id) >= 0) {
                    this.$refs.contactOfficeTable.toggleRowSelection(this.contactOfficeList[i], true)
                } else {
                    this.$refs.contactOfficeTable.toggleRowSelection(this.contactOfficeList[i], false)
                }
            }
        },
        // 表格多选
        selectionChangeHandle(rows) {
            // 所有已选择的元素, id作为key, 元素作为value
            let selectionRows = {}
            if (this.dataListSelections) {
                this.dataListSelections.forEach(row => {
                    selectionRows[row.id] = row
                })
            }
            // 本次新选择的内容
            rows.forEach(row => {
                if (!selectionRows[row.id]) {
                    selectionRows[row.id] = row
                }
            })
            // 全部选择的内容
            this.dataListSelections = []
            for (let key in selectionRows) {
                this.dataListSelections.push(selectionRows[key])
            }
            // 设置所有单位选中项
            let selectAllIds = []
            this.dataListSelections.forEach(row => {
                selectAllIds.push(row['id'])
            })
            this.$refs.tree.setCheckedKeys(selectAllIds)
        },
        // 删除选中的人员标签
        handleDelTag(tag) {
            this.dataListSelections.splice(this.dataListSelections.indexOf(tag), 1)
            this.$nextTick(() => {
                this.setSelectRow()
            })
        },
        // 重置搜索表单
        resetSearch() {
            if (this.currentOfficeGroupId) {
                this.officeGroupSearchOfficeName[this.currentOfficeGroupId] = ''
            } else {
                this.searchOfficeName = ''
            }
            this.searchForm.name = ''
        },
        // 确认选择
        doSubmit() {
            if (this.limit > 0 && this.dataListSelections.length > this.limit) {
                this.$message({
                    showClose: true,
                    message: '你最多只能选择${this.limit}个单位！',
                    type: 'warning'
                })
                return
            }
            this.$emit('confirmSelect', this.dataListSelections)
            this.visible = false
        },
        // 设置禁止选中条件
        checkSelectableCondition(row) {
            return row.id !== this.checkSelectable
        }
    }
}
</script>
<style lang="scss">
.allOffice {
    .el-scrollbar__wrap {
        overflow-x: hidden;
    }
}
</style>
