<template>
    <div class="ajm-panel-container">
        <div class="main-left-tree">
            <el-input :placeholder="$t('message.Manager.confirmDepart')" v-model="filterMenuName" prefix-icon="el-icon-search" class="tree-search"></el-input>
            <el-tree ref="departmentTree" :data="departmentNodes" :props="departmentTreeProps" v-loading="departLoading" node-key="departmentId"
                     @node-click="viewNode" :highlight-current="true" :filter-node-method="filterMenuNode"
                     :current-node-key="currentNodeKey" :indent="15">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>{{ node.label }}</span>
                    <span class="span-tree-icons">
                        <el-dropdown ref="dropDown" :hide-on-click="false" @command="closeDropDown" trigger="click" menu-align="start" style="width:100%">
                            <el-tooltip disabled placement="top">
                                <i class="el-icon-ajm-more1" style="font-size: 20px"></i>
                            </el-tooltip>
                            <el-dropdown-menu slot="dropdown" class="dropDown1">
                                <el-dropdown-item class="ajm-drop-items" @click.native="goAddDepart(data)">
                                    <i class="el-icon-ajm-add"></i>{{$t('message.add')}}
                                </el-dropdown-item>
                                <el-dropdown-item class="ajm-drop-items" @click.native="editDepart(data)" v-if="data.departmentId > 0">
                                    <i class="el-icon-ajm-edit"></i>{{$t('message.edit')}}
                                </el-dropdown-item>
                                <el-dropdown-item class="ajm-drop-items" @click.native="deleteDepart(data)" v-if="data.departmentId > 0">
                                    <i class="el-icon-ajm-delete"></i>{{$t('message.delete')}}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </span>
                </span>
            </el-tree>
        </div>
        <div class="main-right-panel">
            <div class="main-right-list">
                <div class="ajm-search-form">
                    <el-form ref="searchForm" :model="searchForm" :inline="true">
                        <el-row>
                            <el-col :span="24" class="ajm-search-items">
                                <el-form-item>
                                    <el-input id="enterSearch" class="search-item" v-model="searchForm.userName" :placeholder="$t('message.UserInfo.confirmUserName')">
                                    </el-input>
                                </el-form-item>
                                <el-form-item class="ajm-search-btns">
                                    <el-button icon="el-icon-ajm-search" @click="goSearch"></el-button>
                                    <el-button icon="el-icon-ajm-refresh" @click="refreshSearch"></el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div class="ajm-table">
                    <el-table :data="pageResult.list" v-loading="listLoading" @sort-change="handleSortChange" @filter-change="handleFilterChange" tooltip-effect="light">
                        <el-table-column type="index" :label="$t('message.Table.index')" width="70"></el-table-column>
                        <el-table-column prop="userName" :label="$t('message.UserInfo.userName')" :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="realName" :label="$t('message.UserInfo.name')" :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="departmentName" :label="$t('message.Manager.department')" :show-overflow-tooltip="true"></el-table-column>
                        <el-table-column prop="status.name" :label="$t('message.Table.status')" :filters="statusUser" :filter-multiple="false" column-key="status" :filter-method="filterStatus" width="70" />
                        <el-table-column prop="createdUserName" :label="$t('message.Table.createdId')" :show-overflow-tooltip="true" />
                        <el-table-column prop="createdTime" :label="$t('message.Table.createdTime')" sortable="custom" width="180"/>
                        <el-table-column :label="$t('message.Table.operate')" width="90" fixed="right">
                            <template slot-scope="scope">
                                <el-tooltip :content="$t('message.edit')" placement="top">
                                    <el-button size="small" type="text" @click="goEditDepartment(scope.$index, scope.row)">
                                        <i class="el-icon-ajm-remove"></i>
                                    </el-button>
                                </el-tooltip>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="ajm-pagination-bar">
                    <el-pagination background @current-change="changePage" @size-change="goChangePageSize" :current-page="pageResult.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageResult.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageResult.total">
                    </el-pagination>
                </div>
            </div>
        </div>
        <!--编辑部门-->
        <el-dialog custom-class="ajm-dialog-middle" width="30%" top="0" :title="dialogTitle" :visible.sync="addDepartDialogVisible" :modal-append-to-body="false" :before-close="closeDepartDialog" :close-on-click-modal="false">
            <el-form class="ajm-form" :model="departForm" ref="departForm" :rules="departmentRules" label-width="90px">
                <el-form-item :label="$t('message.Manager.lastDepart')" required>
                    <el-input v-model="departForm.departmentParentName" disabled></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.departName')" prop="departmentName" required>
                    <el-input v-model="departForm.departmentName" :maxlength="20" :placeholder="$t('message.Manager.conDepartName')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('message.Manager.departMaster')" prop="departmentMaster">
                    <el-select :placeholder="$t('message.Manager.conDepartMaster')" v-model="departForm.departmentMaster" filterable>
                        <el-option class="master" v-for="item in departmentMasterList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.disabled" :title="item.name"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" :loading="saveDepartLoading" @click="saveAndUpdateDepart('objectForm')">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="cancelDepartForm">{{$t('message.cancel')}}</el-button>
            </div>
        </el-dialog>
        <!--移动部门-->
        <el-dialog custom-class="ajm-dialog-middle" width="35%" top="0" :title="$t('message.Manager.move')" :visible.sync="moveDepartVisible" :modal-append-to-body="false">
            <el-tree ref="vuetree" :data="departmentNodes" :current-node-key="currentKey" :props="departmentTreeProps" :expand-on-click-node="false" :default-expand-all="true" :highlight-current="true" @node-click="handleNodeClick" node-key="departmentId">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" @click="updateDepartment" :disabled="saveDisabled == true">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="cancelMove">{{$t('message.cancel')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    //企业服务
    import companySerivce from "../services/companyService";
    //用户信息服务
    import userInfoService from "../services/userInfoService";
    import SecurityManager from "ajm-framework/core/manager/SecurityManager";
    import $ from 'jquery'

    export default {
        data() {
            return {
                //加载公司部门树动画
                departLoading: false,
                //公司部门树数据
                departmentNodes: [],
                //公司部门树属性
                departmentTreeProps: {
                    label: "departmentName",
                    children: "childDepartments"
                },
                //当前选中节点
                currentNodeData:[],
                //展开节点组
                expandedDepartmentId: [],
                //默认选中节点
                currentNodeKey:'',
                //部门负责人列表
                departmentMasterList: [],

                saveDisabled: false,
                statusUser: [{ text: '启用', value: 1 }, { text: '禁用', value: 2 }],
                searchForm: {
                    userName: '',
                    realName: ''
                },
                userId: "",
                listLoading: false,
                filterMenuName: "",
                pageResult: {
                    pageNum: 1,
                    pageSize: 10,
                    total: 0,
                    list: []
                },
                isReload: false,
                /*departmentRules: {
                    departmentName: [
                        { validator: checkDepartName, trigger: "" }
                    ]
                },*/
                //弹窗名称
                dialogTitle:'',
                addDepartDialogVisible: false,
                moveDepartVisible: false,
                //部门表单数据
                departForm: {
                    companyId: "",
                    departmentName: "",
                    departmentId: "",
                    departmentParentName: "",
                    departmentParentId: "",
                    departmentMaster: ""
                },
                saveDepartLoading: false,
                departmentName: "",
                currentKey: '',
                status: '',
                sortType: 2
            };
        },
        computed:{
            departmentRules(){
                var checkDepartName = (rule, value, callback) => {
                    if (!value) {
                        return callback(new Error(this.$t('message.Manager.conDepartName')));
                    }
                    var reg = /^\S{1,50}$/;
                    if (reg.test(value)) {
                        let params = {
                            companyId: this.currentNodeData.companyId,
                            departmentId: this.departForm.departmentId,
                            departmentName: value
                        }
                        companySerivce.checkDepartmentNameExist(params).then(resp => {
                            var result = resp;
                            if (result == true) {
                                return callback(new Error(this.$t('message.Manager.hasDepart')));
                            } else {
                                callback();
                            }
                        });
                    } else {
                        callback(new Error(this.$t('message.Manager.DepartClue')));
                    }
                };
                return{
                    departmentName: [
                        { validator: checkDepartName, trigger: "" }
                    ]
                }
            }
        },
        watch: {
            // 过滤菜单名
            filterMenuName(value) {
                this.$refs.departmentTree.filter(value);
            }
        },
        methods: {
            //查询所有公司及部门
            findAllCompanyAndDepartments() {
                this.departLoading = true;
                companySerivce.findAllCompanyAndDepartments().then(resp => {
                    this.departLoading = false;
                    let result = resp;

                    if (result && resp.length > 0) {
                        this.departmentNodes = result;
                        this.currentNodeData = result[0];
                        if (this.expandedDepartmentId.length == 0) {
                            this.expandDefaultKeys([this.currentNodeData.departmentId]);
                        } else {
                            this.expandDefaultKeys(this.expandedDepartmentId);
                        }
                        this.currentNodeKey = result[0].departmentId
                        this.findUserInfoListByPage();
                    }
                }).catch(() => {
                    this.departLoading = false;
                });
            },
            //查询部门用户分页列表
            findUserInfoListByPage() {
                this.$refs.departmentTree.setCurrentNode({departmentId:this.currentNodeData.departmentId});
                this.listLoading = true;
                let departmentId = '';
                if (this.currentNodeData.departmentId <= -1) {
                    departmentId = ''
                }else{
                    departmentId = this.currentNodeData.departmentId
                }
                let params = {
                    page: this.pageResult.pageNum,
                    rows: this.pageResult.pageSize,
                    userName: this.searchForm.userName,
                    realName: this.searchForm.realName,
                    companyId: this.currentNodeData.companyId,
                    departmentId: departmentId,
                    status: {
                        value: this.status
                    },
                    sortType: this.sortType
                };
                userInfoService.findUserInfoListByPage(params).then(resp => {
                    this.pageResult = resp || resp.data;
                    this.isReload = true;
                    this.listLoading = false;

                    let list = resp.list;
                    this.pageResult.list = [];

                    this.pageResult.list = list.filter(item => item.isDefault == 2)
                }).catch(() => {
                    this.listLoading = false;
                });
            },
            //选中树节点
            viewNode(data, node, store) {
                this.currentNodeData = data;
                node.expanded = true;
                this.findUserInfoListByPage();
            },
            //查找部门负责人
            findUserInfoList() {
                let params = {
                    userId: this.departForm.departmentMaster
                }
                userInfoService.findUserInfoList(params).then(resp => {
                    let departmentMasterList = resp;
                    this.departmentMasterList = [];
                    departmentMasterList.forEach(item => {
                        if (item.expired == true || item.status.value == 2 || item.status.value == 3) {
                            this.departmentMasterList.push({
                                id: item.userId,
                                name: item.realName + '（' + item.userName + '）',
                                disabled: true
                            })
                        } else {
                            this.departmentMasterList.push({
                                id: item.userId,
                                name: item.realName + '（' + item.userName + '）',
                                disabled: false
                            })
                        }
                    })
                })
            },
            //关闭部门按钮弹窗
            closeDropDown() {
                $('.el-dropdown-menu').hide();
            },
            //添加部门
            goAddDepart(data) {
                this.currentNodeData = data;
                this.dialogTitle = this.$t('message.Manager.addDepart');
                this.departForm.departmentName = "";
                this.departForm.departmentId = "";
                this.departForm.departmentMaster = "";
                this.departForm.departmentParentName = data.departmentName;
                this.departForm.departmentParentId = data.departmentId;
                this.addDepartDialogVisible = true;
                this.findUserInfoList();
            },
            //编辑修改部门信息
            editDepart(data) {
                this.currentNodeData = data;
                this.dialogTitle = this.$t('message.Manager.editDepart');
                this.departForm.departmentMaster = data.departmentMaster;
                this.departForm.departmentName = data.departmentName;
                this.departForm.departmentId = data.departmentId;
                this.departForm.departmentParentName = this.$refs.departmentTree.getNode({departmentId:data.parentDepartmentId}).label;
                this.departForm.departmentParentId = data.parentDepartmentId;
                this.addDepartDialogVisible = true;
                this.findUserInfoList();
            },
            //删除部门
            deleteDepart(data) {
                let departName = data.departmentName;
                var id = data.departmentId;
                var expandedDepartmentId = data.parentDepartmentId == undefined ? data.departmentId : data.parentDepartmentId;
                this.expandedDepartmentId = [expandedDepartmentId];

                this.$confirm(this.$t('message.confirmRequest') +" [" + departName + "] ?", this.$t('message.delClue'), {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: "warning"
                }).then(() => {
                    companySerivce.deleteDepartmentById(id).then(resp => {
                        if (resp.status == 500) {
                            this.$message({
                                type: 'error',
                                message: resp.message
                            })
                            return;
                        }else{
                            this.$message({
                                type: "success",
                                message: this.$t('message.delSuccess')
                            });
                            this.findAllCompanyAndDepartments();
                        }
                    });
                }).catch(() => { })
            },
            // 去除空格
            trim(val) {
                return val.replace(/(^\s*)|(\s*$)/g, "");
            },
            //保存部门
            saveAndUpdateDepart() {
                let params = {
                    companyId: this.currentNodeData.companyId,
                    departmentName: this.trim(this.departForm.departmentName),
                    parentDepartmentId: this.departForm.departmentParentId,
                    departmentMaster: this.departForm.departmentMaster,
                    departmentId: this.departForm.departmentId
                };
                var expandedDepartmentId = params.parentDepartmentId == undefined ? params.departmentId : params.parentDepartmentId;
                this.expandedDepartmentId = [expandedDepartmentId];

                this.$refs["departForm"].validate(valid => {
                    if (valid) {
                        this.saveDepartLoading = true;

                        companySerivce.saveAndUpdateDepartment(params).then(resp => {
                            if (resp.status == 500) {
                                this.$message({
                                    message: resp.message,
                                    type: "error"
                                });
                                return;
                            }else{
                                this.$message({
                                    message: this.$t('message.saveSuccess'),
                                    type: "success"
                                });
                                this.saveDepartLoading = false;
                                this.addDepartDialogVisible = false;
                                this.findAllCompanyAndDepartments();
                                this.$refs.departForm.resetFields();
                            }
                        })
                    }
                });
            },

            //时间排序
            handleSortChange(column, prop, order) {
                if (column.order === "ascending") {
                    this.sortType = 1;
                } else if (column.order === "descending") {
                    this.sortType = 2;
                }
                this.findUserInfoListByPage();
            },
            //状态筛选
            handleFilterChange(filters) {
                this.status = filters.status[0];
                this.findUserInfoListByPage();
            },
            //移动修改部门
            goEditDepartment(index, row) {
                this.moveDepartVisible = true;
                this.userId = row.userId;
                this.currentKey = row.departmentId;
                this.saveDisabled = true;
            },
            //选中移动部门
            handleNodeClick(data) {
                this.departmentId = data.departmentId;
                this.currentNodeData = data;
                if (data.departmentId !== this.currentKey) {
                    this.saveDisabled = false;
                } else {
                    this.saveDisabled = true;
                }
				if(!data.parentDepartmentId){
                    this.saveDisabled = true;
				}
            },
            //取消移动
            cancelMove() {
                this.moveDepartVisible = false;
            },
            //保存移动更新部门信息
            updateDepartment() {
                let params = {
                    departmentId: this.departmentId,
                    userId: this.userId,
                    companyId: this.currentNodeData.companyId
                }
                userInfoService.updateDepartment(params).then(resp => {
                    if (resp.status == 500) {
                        this.$message({
                            type: 'error',
                            message: resp.message
                        })
                        return;
                    }
                    this.$message({
                        type: 'success',
                        message: this.$t('message.Manager.editDepartSuccess')
                    })
                    this.moveDepartVisible = false;
                    this. findAllCompanyAndDepartments();
                })
            },
            //关闭弹窗
            closeDepartDialog(done) {
                done();
                this.$refs.departForm.resetFields();
            },
            //取消部门表单
            cancelDepartForm() {
                this.addDepartDialogVisible = false;
                this.$refs.departForm.resetFields();
            },
            //筛选部门树
            filterMenuNode(value, data) {
                if (!value) return true;
                return data.departmentName.indexOf(value) !== -1;
            },
            //默认展开树节点
            expandDefaultKeys(keys) {
                let treeStore = this.$refs.departmentTree.store;
                treeStore.setDefaultExpandedKeys(keys);
            },
            //筛选状态
            filterStatus(value, row) {
                return row.status.name === value;
            },
            //切换页面
            changePage(page) {
                this.pageResult.pageNum = page;
                this.findUserInfoListByPage();
            },
            goChangePageSize(pageSize) {
                this.pageResult.pageSize = pageSize;
                this.findUserInfoListByPage();
            },
            goSearch() {
                this.pageResult.pageNum = 1;
                this.findUserInfoListByPage();
            },
            //刷新页面
            refreshSearch(){
                this.searchForm.userName = '';
                this.pageResult.pageNum = 1
                this.pageResult.pageSize = 10
                this.sortType = 2
                this.findUserInfoListByPage();
            },
        },
        mounted() {
            this.findAllCompanyAndDepartments();
            let self = this;
            document.getElementById("enterSearch").addEventListener("keydown", function (event) {
                if (event.keyCode === 13) {
                    self.goSearch(event);
                }
            }, false);
        }
    };
</script>

<style lang="less" scoped>
    .dropDown1{
        padding: 0;
        width:120px;
    }
    .ajm-drop-items{
        line-height: 30px;
        padding: 0;
        color: #71757B;
        i{
            padding: 0 8px 0 12px;
        }
    }
    .more {
        display: inline-block;
        width: 16px;
        height: 16px;
        background: url("../images/more.png") no-repeat;
        background-size: 100% 100%;
    }
</style>
