/***********************************************************************
 * 目的: 系统的租户管理
 * 作者: heyf@steerinfo.com
 * 创建日期: 2019-02-11
 * 
 * 更新历史:
 * 日期                    人员                变更目的
 * 2019-02-11         修改人员名     修改的原因和目的*
**********************************************************************/
<template>
    <div class="_box">
        <div
            class="operateArea"
            v-if="userCode === 'admin'"
        >
            <el-input
                v-model.trim="search.companyName"
                size="small"
                style="width:200px; margin:0px 5px 0px 10px"
                placeholder="租户名称"
                label="属性一"
                clearable
            >
            </el-input>
            <el-button
                type="primary"
                size="mini"
                @click="getTableData()"
            >查询</el-button>
        </div>
        <div>
            <div>
                <el-row>
                    <el-col :span="14">
                        <div class="tableDiv1">
                            <el-row>
                                <el-col :span="16">
                                    <div class="title"> 租户表 <span></span></div>
                                </el-col>
                                <el-col
                                    :span="8"
                                    style="text-align: right;"
                                >
                                    <el-button
                                        type="primary"
                                        size="mini"
                                        @click="add"
                                        v-if="userCode === 'admin'"
                                    >新增租户</el-button>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-table
                                    :data="tableData"
                                    v-loading="tableLoading"
                                    :height="tableHeight"
                                    style="width: 100%"
                                    ref="groupTable"
                                    border
                                    class="table"
                                    highlight-current-row
                                    @row-click="handleCurrentChange"
                                >
                                    <!-- 不需要序号可将一下序号列删除 -->
                                    <el-table-column
                                        fixed
                                        width="50px"
                                        type="index"
                                        label="序号"
                                        align="center"
                                    >
                                    </el-table-column>
                                    <!-- tableKey表示为根据获取的tableData设置的header显示值列表 -->
                                    <el-table-column
                                        v-for="(item, index) of tableKeys"
                                        :key="index"
                                        :label="item.label"
                                        :prop="item.key"
                                        :fixed="item.fixed"
                                        :width="item.width"
                                        header-align="center"
                                        align="center"
                                        sortable
                                        show-overflow-tooltip
                                    >
                                    </el-table-column>
                                    <el-table-column
                                        label="状态"
                                        prop="status"
                                        width="auto"
                                        header-align="center"
                                        align="center"
                                        sortable
                                    >
                                        <template slot-scope="scope">
                                            <span :style="{color: scope.row.status === '1' ? 'green' : 'red'}">{{scope.row.status === '1' ? '启用' : '禁用'}}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        fixed="right"
                                        label="操作"
                                        align="center"
                                        v-if="userCode === 'admin'"
                                        width="105"
                                    >
                                        <template slot-scope="scope">
                                            <el-dropdown
                                                split-button
                                                size="mini"
                                                type="primary"
                                                trigger="click"
                                                @click="groupHandle(['authorize', scope.row])"
                                                @command="groupHandle"
                                            >
                                                授权
                                                <el-dropdown-menu slot="dropdown">
                                                    <el-dropdown-item :command="['edit', scope.row]">编辑</el-dropdown-item>
                                                    <el-dropdown-item :command="['delete', scope.row]">删除</el-dropdown-item>
                                                    <el-dropdown-item :command="['status', scope.row]">{{scope.row.status === '1' ? '禁用' : '启用'}}</el-dropdown-item>
                                                </el-dropdown-menu>
                                            </el-dropdown>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </el-row>
                        </div>
                    </el-col>
                    <el-col :span="10">
                        <div class="tableDiv2">
                            <el-row>
                                <el-col :span="8">
                                    <div class="title"> 机构树 <span></span></div>
                                </el-col>
                                <el-col
                                    :span="16"
                                    style="text-align: right;"
                                >
                                    <el-button
                                        @click="setCheckedNodes"
                                        type="success"
                                        size="mini"
                                        class="refresh"
                                    >展开</el-button>
                                    <el-button
                                        @click="setCheckedKeys"
                                        type="success"
                                        size="mini"
                                        class="refresh2"
                                    >收起</el-button>
                                    <el-button
                                        @click="organiz_data.show = true;handleReset('formItem');"
                                        type="primary"
                                        size="mini"
                                        class="_refresh3"
                                        v-privilege="'ORGANADD'"
                                    >新增顶级</el-button>
                                </el-col>
                            </el-row>
                            <el-input
                                placeholder="输入关键字进行过滤"
                                class="filterTree"
                                v-model="filterText"
                            >
                            </el-input>
                            <el-tree
                                ref="orgTree"
                                :data="orgTree"
                                :props="defaultProps"
                                node-key="orgId"
                                @node-expand="nodeExpand"
                                :expand-on-click-node="true"
                                :style="{height: treeHeight + 'px'}"
                                :filter-node-method="filterOrgTree"
                                v-loading="treeLoading"
                            >
                                <span
                                    class="custom-tree-node"
                                    slot-scope="{ node, data }"
                                >
                                    <span>{{ node.label }}</span>
                                    <span class="nodeOperate" v-show="privilegeObj.ORGANADD || privilegeObj.ORGANPUT || privilegeObj.ORGANDELETE">
                                        <el-dropdown @command="handleCommand">
                                            <span class="el-dropdown-link">
                                                <i
                                                    class="el-icon-arrow-down icore-icon-size"
                                                    style="color: #111; background-color: #61f06e"
                                                ></i>
                                            </span>
                                            <el-dropdown-menu slot="dropdown">
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'add', node:node, data:data}"
                                                        class='el-icon-plus addMenuPr'
                                                        style="display: inline-block"
                                                        v-privilege="'ORGANADD'"
                                                    >添加</el-dropdown-item>
                                                </el-row>
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'edit', node:node, data:data}"
                                                        class='el-icon-edit addMenuPr'
                                                        style="display: inline-block"
                                                        v-privilege="'ORGANPUT'"
                                                    >修改</el-dropdown-item>
                                                </el-row>
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'delete', node:node, data:data}"
                                                        class='el-icon-delete delMenuPr'
                                                        style="display: inline-block"
                                                        v-privilege="'ORGANDELETE'"
                                                    >删除</el-dropdown-item>
                                                </el-row>
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'up', node:node, data:data}"
                                                        class='el-icon-upload2 upMenuPr'
                                                        style="display: inline-block"
                                                        v-privilege="'ORGANPUT'"
                                                    >上移</el-dropdown-item>
                                                </el-row>
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'down', node:node, data:data}"
                                                        class='el-icon-download downMenuPr'
                                                        style="display: inline-block"
                                                        v-privilege="'ORGANPUT'"
                                                    >下移</el-dropdown-item>
                                                </el-row>
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'left', node:node, data:data}"
                                                        v-privilege="'ORGANPUT'"
                                                        v-if="node.level > 1"
                                                        class='el-icon-d-arrow-left leftMenuPr'
                                                        style="display: inline-block"
                                                    >左移</el-dropdown-item>
                                                </el-row>
                                                <el-row>
                                                    <el-dropdown-item
                                                        :command="{str:'right', node:node, data:data}"
                                                        v-privilege="'ORGANPUT'"
                                                        v-if="!(node.level === 1 && node === node.parent.childNodes[0])"
                                                        class='el-icon-d-arrow-right rightMenuPr'
                                                        style="display: inline-block"
                                                    >右移</el-dropdown-item>
                                                </el-row>
                                            </el-dropdown-menu>
                                        </el-dropdown>
                                    </span>
                                </span>
                            </el-tree>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>
        <!-- 授权弹窗页面 -->
        <el-dialog
            title="授权"
            :visible.sync="formData.show"
            width="20%"
            @closed='submitDay'
        >
            <div style="text-align:center;margin:20px 0 40px 0;">
                <el-form
                    :model="formData.ruleForm"
                    :rules="formData.rules"
                    ref="ruleForm"
                    label-width="80px"
                    class="demo-ruleForm"
                >
                    <el-form-item
                        label="授权时间"
                        prop="dayTime"
                    >
                        <el-input
                            v-model="formData.ruleForm.dayTime"
                            size="small"
                            style="width: 80%;left: -8px"
                        ></el-input>
                        <span>天</span>
                    </el-form-item>
                </el-form>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="formData.show = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    @click="saveData"
                    size="small"
                    :loading='dialogButton'
                >保存</el-button>
            </span>
        </el-dialog>
        <!-- 租户新增/编辑弹窗 -->
        <el-dialog
            :title="dialog_data.state === '新增' ? '租户新增' :'租户编辑'"
            :visible.sync="dialog_data.show"
            @closed="handleSubmit"
            :show-close="!dialogButton"
            center
        >
            <div style="text-align:center;margin:20px 0 40px 0;">
                <el-form
                    ref="dialogData"
                    :model="dialog_data.form.data"
                    :rules="dialog_data.form.rules"
                    label-width="90px"
                >
                    <el-form-item
                        label="租户编码"
                        prop="companyCode"
                    >
                        <el-input
                            v-model="dialog_data.form.data.companyCode"
                            :disabled="dialog_data.state !== '新增'"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="租户名称"
                        prop="companyName"
                    >
                        <el-input
                            v-model="dialog_data.form.data.companyName"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="租户简称"
                        prop="companyBrief"
                    >
                        <el-input
                            v-model="dialog_data.form.data.companyBrief"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        label="备注"
                        prop="remark"
                    >
                        <el-input
                            type="textarea"
                            :autosize="{ minRows: 2, maxRows: 4}"
                            v-model="dialog_data.form.data.remark"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="dialog_data.show = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    @click="save"
                    size="small"
                    :loading='dialogButton'
                >保存</el-button>
            </span>
        </el-dialog>
        <!-- 机构新增/编辑弹窗 -->
        <el-dialog
            :title="organiz_data.state === '新增' ? '机构新增' :'机构编辑'"
            :visible.sync="organiz_data.show"
            :show-close="!addLoading1"
            center
        >
            <div style="text-align:center;margin:20px 0 40px 0;">
                <el-form
                    ref="formItem"
                    :model="formItem"
                    :rules="ruleValidate"
                    label-width="80px"
                    class="FormorganizManage-main"
                >
                    <el-row>
                        <el-col :span="12">
                            <el-form-item
                                label="父机构"
                                prop="pName"
                            >
                                <el-input
                                    v-model="formItem.pName"
                                    disabled
                                    size="small"
                                    style="vertical-align:top;"
                                >
                                    <!-- <el-button
                                        slot="append"
                                        @click="handleReset('formItem')"
                                    >清空</el-button> -->
                                </el-input>
                            </el-form-item>
                            <el-form-item
                                label="机构id"
                                prop="orgId"
                                style="display:none;"
                            >
                                <el-input
                                    v-model="formItem.orgId"
                                    placeholder="请输入"
                                    disabled
                                    size="small"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="机构编码"
                                prop="orgCode"
                            >
                                <el-input
                                    v-model="formItem.orgCode"
                                    placeholder="请输入"
                                    :disabled="!(operateStatus==='add')"
                                    size="small"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item
                                label="机构名称"
                                prop="orgName"
                            >
                                <el-input
                                    v-model="formItem.orgName"
                                    placeholder="请输入"
                                    size="small"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item
                                label="备注"
                                prop="remark"
                            >
                                <el-input
                                    v-model="formItem.remark"
                                    placeholder="请输入"
                                    type="textarea"
                                    :autosize="{minRows: 3,maxRows: 5}"
                                    style="width:100%"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="organiz_data.show = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    size="small"
                    v-show="operateStatus==='edit'"
                    type="primary"
                    @click="organizSave('formItem')"
                    :loading="addLoading1"
                >保存
                </el-button>
                <el-button
                    size="small"
                    v-show="operateStatus==='add'"
                    type="primary"
                    @click="organizSave('formItem')"
                    :loading="addLoading2"
                >添加
                </el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import store from '@/store/index.js';
import { checkCharLength, checkCharLength2, checkCharNoChinese, checkTel, checkEmail, checkNumber, checkChar } from '@/utils/validator.js';
import { objAssign, dgTree, getCookie } from '@/utils/util.js';
export default {
    data () {
        return {
            rowData: {},
            userCode: '',
            search: {
                companyName: ''
            },
            tableData: [],
            tableHeight: 0,
            tableLoading: false,
            tableKeys: [],
            dialogButton: false,
            dialog_data: {
                state: '',
                show: false,
                editId: '',
                form: {
                    data: {
                        groupId: '',
                        companyCode: '',
                        companyName: '',
                        companyBrief: '',
                        remark: '',
                        status: ''
                    },
                    rules: {
                        groupId: [
                            { required: true, message: '该项不能为空', trigger: 'change' }
                        ],
                        companyCode: [
                            { required: true, message: '该项不能为空', trigger: 'change' }
                        ],
                        companyName: [
                            { required: true, message: '该项不能为空', trigger: 'change' }
                        ]
                    }
                }
            },
            formData: {
                show: false,
                ruleForm: {
                    dayTime: ''
                },
                rules: {
                    dayTime: [
                        { required: true, message: '该项不能为空', trigger: 'blur' },
                        {
                            validator (rule, value, callback) {
                                if (Number.isInteger(Number(value))) {
                                    callback()
                                } else {
                                    callback(new Error('请输入正整数'))
                                }
                            },
                            trigger: 'blur'
                        }
                    ],
                }
            },
            treeLoading: false,
            organiz_data: {
                state: '',
                show: false
            },
            // 机构
            companyId: '', // 选择公司Id
            companyName: '', // 选择公司名称
            filterText: '',
            store,
            addLoading1: false,
            addLoading2: false,
            operateStatus: 'add',
            treeHeight: 600,
            formItem: {
                'orgId': '',
                'pId': '',
                'pName': '',
                'pCode': '',
                'pDeptId': '',
                'pDeptCode': '',
                'cate': '',
                'orgCode': '',
                'rank': '',
                'orgName': '',
                'qrCode': '',
                'orgBrief': '',
                'contact': '',
                'pathName': '',
                'tel': '',
                'citycode': '',
                'officeAddr': '',
                'country': '',
                'email': '',
                'remark': '',
                'post': '',
                'status': '',
                'isVirtual': '',
                'companyId': ''
            },
            activeMenu: '',
            ruleValidate: {
                orgCode: [
                    { required: true, message: '机构编码不能为空', trigger: 'change' },
                    { validator: checkCharLength, max: 32, trigger: 'change' },
                    { validator: checkCharNoChinese, trigger: 'change' }
                ],
                orgName: [
                    { required: true, message: '机构名称不能为空', trigger: 'change' },
                    { validator: checkChar, trigger: 'change' },
                    { validator: checkCharLength, max: 64, trigger: 'change' }
                ],
                cate: [
                    { required: true, message: '机构类别不能为空', trigger: 'change' }
                ],
                remark: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' },
                    { validator: checkChar, trigger: 'change' }
                ],
                tel: [
                    { validator: checkNumber, trigger: 'change' },
                    { validator: checkTel, trigger: 'change' },
                    { validator: checkCharLength2, max: 11, trigger: 'change' }
                ],
                email: [
                    { validator: checkEmail, trigger: 'change' },
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                contact: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                orgBrief: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                officeAddr: [
                    { validator: checkCharLength2, max: 100, trigger: 'change' }
                ],
                post: [
                    { validator: checkNumber, trigger: 'change' },
                    { validator: checkCharLength2, max: 6, message: '请输入正确的邮政编码', trigger: 'change' }
                ]
            },
            privilegeObj: {}
        }
    },
    created () {
        this.activeMenu = window.top.localStorage.getItem('activeMenu');
        this.getPrivilegeData(({arr, obj})=>{this.privilegeObj = obj});
    },
    watch: {
        'filterText': function (newV, oldV) {
            this.$refs.orgTree.filter(newV);
        }
    },
    computed: {
        //  菜单树数据
        orgTree () {
            let orgTree = this.store.state.system.organizManage.tree;
            // 页面筛选注释掉
            // let orgTree = this.companyId !== '' ? this.getTreeAll(_orgTree, this.companyId) : _orgTree;
            return orgTree;
        },
        //  树配置
        defaultProps () {
            return this.store.state.system.organizManage.defaultProps;
        },
        //  展开数组
        expandedKeys: {
            get: function () {
                return this.store.state.system.organizManage.expandedKeys;
            },
            set: function (data) {
                this.store.commit('system/organizManage/expandedKeys', data);
            }
        },
        //  选中节点数据
        orgItem () {
            return this.store.state.system.organizManage.item;
        },
        //  树配置
        formItemCate () {
            return this.store.state.system.organizManage.formItemCate;
        },
        //  是否虚机构
        formItemIsVirtual () {
            return this.store.state.system.organizManage.formItemIsVirtual;
        }
    },
    mounted () {
        // 获取cookie值
        this.userCode = JSON.parse(getCookie('userInfo')).userCode
        this.$nextTick(() => {
            this.tableHeight = this.getTreeHeight(this.$refs['groupTable'].$el) - 130;
        });
        //  设置树区域高度
        this.treeHeight = this.getTreeHeight(this.$refs['orgTree'].$el) - 88;
        this.getTableData();
        this.tableKeys = [
            {
                key: 'companyCode',
                label: '租户编码',
                width: 'auto'
            },
            {
                key: 'companyName',
                label: '租户名称',
                width: 'auto'
            },
            {
                key: 'companyBrief',
                label: '租户简称',
                width: 'auto'
            },
            {
                key: 'remark',
                label: '备注',
                width: 'auto'
            }
        ]
    },
    methods: {
        //  计算树区域高度
        getTreeHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        getTableData (pageNum) {
            let _this = this
            // this.pageNum = pageNum || this.pageNum;
            _this.tableLoading = true
            this.axios.get('pass/v1/syscompanys/like/?pageSize=10000&companyName=' + this.search.companyName).then(res => {
                if (res.code === '0') {
                    let arr = [];
                    for (let item of res.data.list) {
                        arr.push({
                            id: item.id,
                            groupId: item.groupId,
                            companyCode: item.companyCode,
                            companyName: item.companyName,
                            companyBrief: item.companyBrief,
                            remark: item.remark,
                            status: item.status
                        })
                    }
                    _this.tableData = arr;
                } else {
                    this.$message.error(res.message)
                }
                _this.tableLoading = false
            }).catch(function () {
                _this.tableLoading = false
            })
        },
        cleraForm () {
            let that = this;
            that.dialog_data.state = '';
            that.dialog_data.form.data = {
                groupId: '',
                companyCode: '',
                companyName: '',
                companyBrief: '',
                remark: '',
                status: ''
            };
        },
        add () {
            this.dialog_data.show = true;
            this.dialog_data.state = '新增';
        },
        // 重置公司表单
        handleSubmit () {
            this.cleraForm()
            this.$refs['dialogData'].resetFields()
        },
        submitDay () {
            this.$refs['ruleForm'].resetFields()
        },
        // 集团授权
        authorize (row) {
            let _this = this
            _this.formData.show = true
            _this.authorizeId = row.groupId
        },
        edit (row) {
            this.dialog_data.form.data = JSON.parse(JSON.stringify(row));
            this.dialog_data.editId = JSON.parse(JSON.stringify(row)).id
            this.dialog_data.show = true;
            this.dialog_data.state = '编辑';
        },
        // 租户(公司)操作
        groupHandle (command) {
            switch (command[0]) {
                case 'authorize':
                    this.authorize(command[1]);
                    break;
                case 'edit':
                    this.edit(command[1]);
                    break;
                case 'delete':
                    this.remove(command[1]);
                    break;
                case 'status':
                    this.changeCompany(command[1])
                    break;
            }
        },
        deleteRow (row) {
            this.$confirm(`您确定要删除吗`, 'Warning', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning'
            }).then(async () => {
                this.axios.delete('pass/v1/syscompanys/' + row.id, {}).then(res => {
                    if (res.code === '0') {
                        this.$message.success('删除成功')
                    } else {
                        this.$message.error(res.message)
                    }
                })
            }).catch(() => { })
        },
        // 主项保存
        save () {
            let _this = this
            let data = this.dialog_data.form.data
            if (_this.dialog_data.state === '新增') {
                _this.$refs['dialogData'].validate((valid) => {
                    if (valid) {
                        _this.dialogButton = true;
                        _this.axios.post('pass/v1/sysgroups/?groupCode=' + data.companyCode + '&groupName=' + data.companyName + '&groupBrief=' + data.companyBrief + '&remark=' + data.remark + '&status=1').then(res => {
                            if (res.code === '0') {
                                _this.axios.post('pass/v1/syscompanys/?groupId=' + res.data.id + '&companyCode=' + data.companyCode + '&companyName=' + data.companyName + '&remark=' + data.remark + '&status=1' + '&companyBrief=' + data.companyBrief).then(res_1 => {
                                    if (res_1.code === '0') {
                                        _this.$message.success('新增成功')
                                        _this.dialog_data.show = false;
                                        _this.cleraForm();
                                        _this.getTableData()
                                    } else {
                                        _this.$message.error(res_1.message)
                                    }
                                    _this.dialogButton = false
                                }).catch(res => {
                                    _this.dialogButton = false
                                });
                            } else {
                                _this.$message.error(res.message);
                                _this.dialogButton = false
                            }
                        }).catch(res => {
                            _this.dialogButton = false
                        });
                    } else {
                        return false;
                    }
                });
            } else {
                _this.dialogButton = true
                _this.$refs['dialogData'].validate((valid) => {
                    if (valid) {
                        _this.axios.put('pass/v1/syscompanys/' + _this.dialog_data.editId, _this.dialog_data.form.data).then(res => {
                            if (res.code === '0') {
                                _this.$message.success('修改成功')
                                _this.dialog_data.show = false;
                                _this.cleraForm();
                                _this.getTableData()
                            } else {
                                _this.$message.error(res.message)
                            }
                            _this.dialogButton = false
                        }).catch(() => {
                            _this.dialogButton = false
                        })
                    } else {
                        return false;
                    }
                });
            }
        },
        saveData () {
            let _this = this
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    _this.dialogButton = true
                    this.axios.put('pass/v1/sysgroups/authorizationDate/' + _this.authorizeId + '?exprieDays=' + _this.formData.ruleForm.dayTime).then(res => {
                        if (res.code === '0') {
                            this.$message.success('授权成功')
                            this.formData.show = false;
                        } else {
                            this.$message.error(res.message)
                        }
                        _this.dialogButton = false
                    }).catch(() => {
                        _this.dialogButton = false
                    })
                } else {
                    return false;
                }
            });
        },
        remove (item) {
            let _this = this
            this.$confirm(`您确定要删除吗`, '删除', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning'
            }).then(async () => {
                this.axios.delete('pass/v1/syscompanys/' + item.id, {}).then(res => {
                    if (res.code === '0') {
                        this.axios.delete('pass/v1/sysgroups/' + item.groupId, {}).then(res => {
                            if (res.code === '0') {
                                this.$message.success('删除成功')
                                this.getTableData()
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                    } else {
                        this.$message.error(res.message)
                    }
                })
            }).catch(() => { })
        },
        changeCompany (val) {
            let _this = this
            if (val.status === '1') {
                _this.axios.put('pass/v1/syscompanys/abolish/' + val.id, {}).then(res => {
                    if (res.code === '0') {
                        this.$message.success('禁用成功')
                        this.getTableData()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            } else {
                _this.axios.put('pass/v1/syscompanys/recovery/' + val.id, {}).then(res => {
                    if (res.code === '0') {
                        this.$message.success('启用成功')
                        this.getTableData()
                    } else {
                        this.$message.error(res.message)
                    }
                })
            }
        },
        // 点击行
        handleCurrentChange (row) {
            let _this = this
            _this.rowData = row;
            this.companyId = _this.rowData.id;
            this.companyName = _this.rowData.companyName;
            this.initData();

        },
        initData () {
            //  查询列表
            this.treeLoading = true;
            this.store.dispatch('system/organizManage/tree', this.companyId).then(res => {
                if (res.code === '0') {
                    this.store.commit('system/organizManage/tree', res.data);
                    // this.$nextTick(() => {
                    //     $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
                    //     $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
                    //     $('.upMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                    //     $('.downMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                    //     $('.rightMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                    //     $('.leftMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                    //     $('.nodeOperate').css('display', (this.checkPrivilege(this.activeMenu + 'MENUDELET') || this.checkPrivilege(this.activeMenu + 'MENUADD') || this.checkPrivilege(this.activeMenu + 'EDIT')) ? 'inline-block' : 'none')
                    // })
                } else {
                    this.$message.error(res.message);
                }
                this.treeLoading = false;
            });
        },
        // 遍历树获取相应公司菜单
        getTreeAll (tree, id) {
            let arr = []
            if (!!tree && tree.length !== 0) {
                tree.forEach(item => {
                    let obj = {}
                    obj = { ...item }
                    if (obj.hasOwnProperty('companyId') && obj.companyId === id) {
                        obj.children = this.getTreeAll(item.children);
                        arr.push(obj)
                    }
                })
            }
            return arr
        },
        nodeExpand () {
            // this.$nextTick(() => {
            //     $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
            //     $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
            //     $('.upMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.downMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.rightMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.leftMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.nodeOperate').css('display', (this.checkPrivilege(this.activeMenu + 'MENUDELET') || this.checkPrivilege(this.activeMenu + 'MENUADD') || this.checkPrivilege(this.activeMenu + 'EDIT')) ? 'inline-block' : 'none')
            // })
        },
        //  点击树事件
        nodeClick (item, el) {
            //  放入
            this.store.commit('system/organizManage/item', item);
            //  清空
            this.$refs['formItem'].resetFields();
            //  加入
            this.formItem = objAssign(this.formItem, item);
            this.formItem.pName = el.parent.label;
            //  点击时为编辑状态
            this.operateStatus = 'edit';
            // this.$nextTick(() => {
            //     $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
            //     $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
            //     $('.upMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.downMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.rightMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.leftMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
            //     $('.nodeOperate').css('display', (this.checkPrivilege(this.activeMenu + 'MENUDELET') || this.checkPrivilege(this.activeMenu + 'MENUADD') || this.checkPrivilege(this.activeMenu + 'EDIT')) ? 'inline-block' : 'none')
            // })
        },
        //  清空 清空为添加，添加直接添加顶级目录
        handleReset (name) {
            setTimeout(() => {
                this.$refs[name].resetFields();
                this.formItem.pName = '';
                this.operateStatus = 'add';
            }, 100);
        },
        //  添加点击
        addTreeNode (node, item) {
            this.operateStatus = 'add';
            this.$refs['formItem'].resetFields();
            //  设置pId为当前ID
            this.formItem.pId = item.orgId;
            this.formItem.pName = item.orgName;
            //  机构类别：1-机构 0-部门
            if (item.cate === '1') {
                this.formItem.pId = item.orgId;
                this.formItem.pCode = item.orgCode;
            } else if (item.cate === '0') {
                this.formItem.pDeptId = item.orgId;
                this.formItem.pDeptCode = item.orgCode;
            }
            //  清空ID
            this.formItem.orgId = '';
        },
        //  计算树区域高度
        getTreeHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 节点上移
        nodeUp (node, data) {
            let that = this;
            console.log(node);
            console.log(data);
            let children = node.parent.childNodes;
            console.log(children);
            if (node === children[0]) {
                that.$message.error('已移至当前顶级，无法继续上移');
            } else {
                let node2 = {};
                for (let i = 0; i < children.length; i++) {
                    if (node === children[i]) {
                        node2 = children[i - 1]
                    }
                }
                let changeList = [node.data, node2.data];
                console.log(changeList);
                this.store.dispatch('system/organizManage/dragOrg', { 'dropType': 'before', 'changeList': changeList }).then(res => {
                    console.log(res);
                    if (res.code === '0') {
                        this.$refs['orgTree'].remove(node.data.id);
                        this.$refs['orgTree'].insertBefore(node.data, node2.data);
                        this.$message.success('上移成功');
                    } else {
                        this.$message({ message: res.message, type: 'error' });
                    }
                });
            }
        },
        // 节点下移
        nodeDown (node, data) {
            let that = this;
            console.log(node);
            console.log(data);
            let children = node.parent.childNodes;
            console.log(children);
            let index = children.length;
            if (node === children[index - 1]) {
                that.$message.error('已移至当前底级，无法继续下移')
            } else {
                let node2 = {};
                for (let i = 0; i < children.length; i++) {
                    if (node === children[i]) {
                        node2 = children[i + 1]
                    }
                }
                let changeList = [node.data, node2.data];
                console.log(changeList);
                this.store.dispatch('system/organizManage/dragOrg', { 'dropType': 'after', 'changeList': changeList }).then(res => {
                    if (res.code === '0') {
                        this.$refs['orgTree'].remove(node.data.id);
                        this.$refs['orgTree'].insertAfter(node.data, node2.data);
                        this.$message.success('下移成功');
                    } else {
                        this.$message({ message: res.message, type: 'error' });
                    }
                });
            }
        },
        // 节点右移
        nodeRight (node, data) {
            let that = this;
            console.log(node);
            console.log(data);
            let children = node.parent.childNodes;
            console.log(children);
            if (node.level === 1 && node === children[0]) {
                that.$message.error('顶级第一个菜单不可降级！');
            } else if (children.length <= 1) {
                that.$message.error('此节点无同级节点以供降级！');
            } else if (children.length > 1) {
                let node2 = {};
                if (node === children[0]) {
                    that.$message.error('此节点位于同级中第一个，若要降级请先调整此节点顺序!');
                } else {
                    for (let i = 0; i < children.length; i++) {
                        if (node === children[i]) {
                            node2 = children[i - 1];
                            if (node2.hasOwnProperty('data')) {
                                // for (let j = 0; j < node2.data.children.length; j++){
                                //     if (node.data.orgName === node2.data.children[j].orgName) {
                                //         that.$message.error(node2.data.orgName + '中已有同名机构！');
                                //     } else if (node.data.orgCode === node2.data.children[j].orgCode) {
                                //         that.$message.error(node2.data.orgName + '中已有相同编码机构！')
                                //     }else {
                                let changeList = [node.data, node2.data];
                                console.log(changeList);
                                this.store.dispatch('system/organizManage/dragOrg', { 'dropType': 'right', 'changeList': changeList }).then(res => {
                                    if (res.code === '0') {
                                        this.$refs['orgTree'].remove(node.data.id);
                                        this.$refs['orgTree'].append(node.data, node2.data);
                                        this.$message.success('已降至前一个同级菜单中');
                                    } else {
                                        this.$message({ message: res.message, type: 'error' });
                                    }
                                });
                                //     }
                                // }
                            } else {
                                that.$message.error('未定义情景，请联系管理员添加前端右移逻辑代码！')
                            }
                        }
                    }
                }
            }
        },
        // 节点左移
        nodeLeft (node, data) {
            let that = this;
            console.log(node);
            console.log(data);
            let node2 = {};
            node2 = node.parent
            if (node2.hasOwnProperty('data')) {
                // for (let i = 0; i < node2.parent.childNodes.length; i++) {
                //     if (node.data.orgCode === node2.parent.childNodes[i].data.orgCode) {
                //         that.$message.error(node.data.orgName + '同级中已有相同编码机构存在');
                //     } else if (node.data.orgName === node2.parent.childNodes[i].data.orgName) {
                //         that.$message.error(node.data.orgName + '同级中已有相同名称机构存在');
                //     } else {
                let changeList = [node.data, node2.data];
                console.log(changeList);
                this.store.dispatch('system/organizManage/dragOrg', { 'dropType': 'left', 'changeList': changeList }).then(res => {
                    if (res.code === '0') {
                        this.$refs['orgTree'].remove(node.data.id);
                        this.$refs['orgTree'].insertAfter(node.data, node2.data);
                        this.$message.success('已升至当前父菜单同级');
                    } else {
                        this.$message({ message: res.message, type: 'error' });
                    }
                });
                //     }
                // }
            } else {
                that.$message.error('未定义情景，请联系管理员添加前端左移逻辑代码！')
            }
        },
        handleCommand (command) {
            let that = this,
                str = command.str,
                node = command.node,
                data = command.data;
            switch (str) {
                case 'add':
                    that.organiz_data.show = true;
                    setTimeout(() => {
                        that.addTreeNode(node, data);
                    }, 100);
                    break;
                case 'edit':
                    that.organiz_data.show = true;
                    setTimeout(() => {
                        that.nodeClick(data, node);
                    }, 100);
                    break;
                case 'delete':
                    that.delTreeNode(node, data);
                    break;
                case 'up':
                    that.nodeUp(node, data);
                    break;
                case 'down':
                    that.nodeDown(node, data)
                    break;
                case 'left':
                    that.nodeLeft(node, data);
                    break;
                case 'right':
                    that.nodeRight(node, data);
                    break;
            }
        },
        /**
         * 保存数据
         * */
        organizSave (name) {
            this.$refs[name].validate((valid) => {
                if (valid) {
                    if (this.operateStatus === 'edit') {
                        if (!this.formItem.orgId) {
                            this.$message.error('请选择数据再来操作');
                            return;
                        }
                        this.$confirm('确定要修改已选择的记录吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            //  修改数据
                            this.addLoading1 = true;
                            this.formItem.cate = 1;
                            this.formItem.companyId = this.companyId;
                            //
                            this.store.dispatch('system/organizManage/editOrg', { id: this.orgItem.id, form: this.formItem }).then(res => {
                                //
                                this.addLoading1 = false;
                                //
                                if (res.code === '0') {
                                    this.$message.success('保存成功');
                                    // //  更新菜单项
                                    let tempItem = null;
                                    dgTree(this.orgTree, 'children', item => {
                                        if (item.orgId === this.formItem.orgId) {
                                            tempItem = item;
                                        }
                                    });
                                    tempItem = Object.assign(tempItem, this.formItem);
                                    this.store.commit('system/organizManage/tree', this.orgTree);
                                    this.organiz_data.show = false;
                                } else {
                                    this.$message.error(res.message);
                                }
                            }).catch(() => {
                                this.addLoading1 = false;
                            });
                        }).catch(() => {
                            this.$message.info('已取消操作');
                        });
                    } else if (this.operateStatus === 'add') {
                        //   添加
                        this.addLoading2 = true;

                        this.formItem.cate = 1;
                        this.formItem.companyId = this.companyId;
                        //
                        this.store.dispatch('system/organizManage/addOrg', this.formItem).then(res => {
                            //
                            this.addLoading2 = false;
                            //
                            if (res.code === '0') {
                                this.$message.success('添加成功');
                                this.handleReset('formItem');
                                //  更新树
                                this.$refs['orgTree'].append(res.data, this.formItem.pId);
                                this.$refs['orgTree'].setCurrentKey(res.data.id);
                                this.organiz_data.show = false;
                                // this.$nextTick(() => {
                                //     $('.delMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'DELET') ? 'inline-block' : 'none')
                                //     $('.addMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'ADD') ? 'inline-block' : 'none')
                                //     $('.upMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                                //     $('.downMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                                //     $('.rightMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                                //     $('.leftMenuPr').css('display', this.checkPrivilege(this.activeMenu + 'EDIT') ? 'inline-block' : 'none')
                                //     $('.nodeOperate').css('display', (this.checkPrivilege(this.activeMenu + 'MENUDELET') || this.checkPrivilege(this.activeMenu + 'MENUADD') || this.checkPrivilege(this.activeMenu + 'EDIT')) ? 'inline-block' : 'none')
                                // })
                            } else {
                                this.$message({ message: res.message, type: 'error' });
                            }
                        }).catch(() => {
                            this.addLoading2 = false;
                        });
                    }
                }
            })
        },
        /**
         * 删除树节点元素
         */
        delTreeNode (node, data) {
            if ((data.children && data.children.length > 0) || (node.childNodes && node.childNodes.length > 0)) {
                this.$message.error('此节点有子节点，不允许删除');
                return false;
            }
            //
            this.$confirm('确定要删除已选择的记录吗？', '提示', {
                customClass: 'org-Manage-changeprimaryforbutton',
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.store.dispatch('system/organizManage/delOrg', data.orgId).then(res => {
                    if (res.code === '0') {
                        this.$message.success('删除成功');
                        //  更新树
                        this.handleReset('formItem')
                        this.$refs['orgTree'].remove(node);
                    } else {
                        this.$message.error(res.message);
                    }
                });
            }).catch(() => {
                this.$message.info('已取消操作');
            });

            this.$nextTick(() => {
                document.getElementsByClassName('org-Manage-changeprimaryforbutton')[0].getElementsByClassName('el-message-box__btns')[0].getElementsByTagName('button')[0].classList.add('el-button--primary')
                document.getElementsByClassName('org-Manage-changeprimaryforbutton')[0].getElementsByClassName('el-message-box__btns')[0].getElementsByTagName('button')[1].classList.remove('el-button--primary')
            });
        },
        // 树形控件过滤数据
        filterOrgTree (value, data) {
            if (!value) return true;
            return data.orgName.indexOf(value) !== -1;
        },
        setCheckedKeys () {
            this.defaultExpand = false;
            for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
                this.$refs.orgTree.store._getAllNodes()[i].expanded = this.defaultExpand;
            }
        },
        setCheckedNodes () {
            this.defaultExpand = true; // 展开所有节点
            for (var i = 0; i < this.$refs.orgTree.store._getAllNodes().length; i++) {
                this.$refs.orgTree.store._getAllNodes()[i].expanded = this.defaultExpand;
            }
        }
    }
}
</script>

<style lang="less" scoped>
._box {
    padding: 5px;
    .operateArea {
        width: 100%;
        height: auto;
        margin: 0 auto;
        padding: 10px 0;
    }
    .tableDiv1 {
        padding: 10px;
        border-right: #c0c0c0 1px solid;
        border-top: #c0c0c0 1px solid;
        border-left: #c0c0c0 0px solid;
        border-bottom: #c0c0c0 0px solid;
    }
    .tableDiv2 {
        padding: 10px;
        border-right: #c0c0c0 0px solid;
        border-top: #c0c0c0 1px solid;
        border-left: #c0c0c0 1px solid;
        border-bottom: #c0c0c0 0px solid;
    }
    .title {
        width: 100%;
        height: 20px;
        line-height: 14px;
        margin-top: 10px;
        font-size: 18px;
        padding-left: 15px;
        position: relative;
        span {
            display: block;
            position: absolute;
            width: 3px;
            height: 34px;
            background: #409eff;
            left: 0px;
            top: -15px;
        }
    }
}
</style>
<style scoped>
.og-st-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: keep-all;
    padding-right: 60px;
}

.organizManage-main {
    position: relative;
    min-width: 1000px;
    /* height: 600px; */
}

.public-function-div {
    font-size: 16px;
    padding: 10px 20px;
    border-bottom: 1px solid #d5d5d5;
    position: relative;
}

.organizManage-mainLeft {
    width: 30%;
    border-right: 1px solid #e0e0e0;
    float: left;
    overflow: hidden;
    height: inherit;
}
._company-select {
    padding: 10px 15px 9px 15px;
    border-bottom: 1px solid #d5d5d5;
}
.el-dropdown {
    font-weight: bold;
    font-size: 14px;
    cursor: pointer;
}
.el-dropdown-menu {
    overflow-y: scroll;
    max-height: 200px;
}
.el-tree {
    overflow-x: hidden !important;
}

.el-icon-back:before {
    content: "\E6EA";
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.organizManage-mainRight {
    width: 70%;
    float: left;
}

.FormorganizManage-main {
    margin: 20px 20px;
}

.filterTree {
    width: 95%;
    margin: 10px 2.5%;
}
.el-tree-node__content .el-icon-plus {
    margin-right: 20px;
}
.postionTop {
    position: absolute;
    top: 0px;
}

.public-function-div .refresh {
    position: absolute;
    right: 15px;
    top: 10px;
}
.public-function-div .refresh2 {
    position: absolute;
    right: 80px;
    top: 10px;
}
.public-function-div ._refresh3 {
    position: absolute;
    right: 145px;
    top: 10px;
}
.delMenuPr,
.upMenuPr,
.downMenuPr,
.rightMenuPr,
.leftMenuPr,
.addMenuPr {
    display: none;
}
.el-tree-node__content:hover {
    background-color: #bbdffb;
}
.el-tree-node:focus .el-tree-node__content {
    background-color: #bbdffb;
}
.el-tree .is-current .el-tree-node__content {
    background-color: #bbdffb;
}
.is-current .el-tree-node__children .el-tree-node .el-tree-node__content {
    background-color: #fff;
}
</style>
