<template>
    <div class="organizManage-main userManage">
        <div class="organizManage-mainLeft">
            <div class="public-function-div">机构树
                <el-button
                    @click="setCheckedNodes"
                    size="small"
                    class="refresh"
                >展开</el-button>
                <el-button
                    @click="setCheckedKeys"
                    size="small"
                    class="refresh2"
                >收起</el-button>
            </div>
            <el-tree
                ref="orgTree"
                :data="orgTree"
                v-loading='treeLoading'
                :props="defaultProps"
                highlight-current
                node-key="id"
                @node-click="nodeClick"
                :expand-on-click-node="true"
                :filter-node-method="filterOrgTree"
                :style="{height: treeHeight + 'px'}"
            >
            </el-tree>
        </div>
        <div class="organizManage-mainRight">
            <div class="public-function-div">用户列表</div>
            <div class="post-m">
                <el-form
                    class="userModal"
                    label-width="50px"
                >
                    <el-row>
                        <el-col :span="6">
                            <el-form-item
                                label="账户"
                                label-width="35px"
                            >
                                <el-input
                                    style="width:100%;"
                                    v-model="tableParams.form.userCode"
                                    clearable
                                    placeholder="请输入"
                                    size="small"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="姓名">
                                <el-input
                                    style="width:100%;"
                                    v-model="tableParams.form.userName"
                                    clearable
                                    placeholder="请输入"
                                    size="small"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="手机">
                                <el-input
                                    style="width:100%;"
                                    v-model="tableParams.form.mobile"
                                    clearable
                                    placeholder="请输入"
                                    size="small"
                                ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="机构">
                                <el-select
                                    style="width:100%;"
                                    v-model="tableParams.form.orgCode"
                                    @change="changeOrg"
                                    clearable
                                    filterable
                                    placeholder="请选择机构"
                                    size="small"
                                >
                                    <el-option
                                        v-for="item in orgList"
                                        :key="item.orgCode"
                                        :label="item.orgName"
                                        :value="item.orgCode"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div style="text-align: right;margin-bottom:10px;">
                    <!-- <el-checkbox
                        v-model="icoreFilterFlag"
                        style="float:left;margin-top: 9px;"
                    >过滤</el-checkbox> -->
                    <el-button
                        icon="el-icon-search"
                        type="primary"
                        size="small"
                        v-privilege="activeMenu + 'SEARCH'"
                        @click="search"
                    >查询</el-button>
                    <el-button
                        size="small"
                        type="primary"
                        icon="el-icon-circle-plus-outline"
                        v-privilege="activeMenu + 'ADD'"
                        @click="operateClick('add',{})"
                    >新增</el-button>
                    <!-- <el-button type="warning" size="small" @click="delAllPost">批量删除</el-button> -->
                </div>
                <el-table stripe
                    ref="userTable"
                    individual-columns="individual-vue-table-columns"
                    :individual-info="individualInfo"
                    drag-column="individual-vue-table"
                    @icoreFilterChange="icoreFilterChange"
                    :icore-filter-flag="icoreFilterFlag"
                    v-loading="tabLoading"
                    border
                    :height="tableHeight"
                    highlight-current-row
                    :data="table.list"
                >
                    <el-table-column
                        type="index"
                        label="序号"
                        fixed="left"
                        align="center"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="userCode"
                        label="账户"
                        align="center"
                        min-width="150"
                    ></el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="userName"
                        label="姓名"
                        align="center"
                        width="150"
                    ></el-table-column>
                    <!-- <el-table-column :show-overflow-tooltip="true" label="部门" min-width="100"></el-table-column> -->
                    <!-- <el-table-column :show-overflow-tooltip="true"
                           prop="duty"
                           label="职务"
                           :filter-method="filterColumn"
                           min-width="100"></el-table-column> -->
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="mobile"
                        label="手机"
                        align="center"
                        min-width="120"
                    ></el-table-column>
                    <!-- <el-table-column :show-overflow-tooltip="true"
                           prop="degree"
                           align="center"
                           label="文化程度"
                           min-width="80"></el-table-column> -->
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="orgName"
                        align="center"
                        label="机构"
                        width="150"
                    ></el-table-column>
                    <!-- <el-table-column :show-overflow-tooltip="true"
                           prop="major"
                           align="center"
                           label="专业"
                           min-width="80"></el-table-column> -->
                    <el-table-column
                        :show-overflow-tooltip="true"
                        align="center"
                        type="noFilter"
                        label="在职状态"
                        width="80"
                    >
                        <template slot-scope="scope">
                            <span
                                class="color-primary"
                                v-if="scope.row.sysUserLogin !== null && scope.row.sysUserLogin.leave ==='0'"
                            >在职</span>
                            <span
                                class="color-danger"
                                v-else-if="scope.row.sysUserLogin !== null && scope.row.sysUserLogin.leave ==='1'"
                            >离退</span>
                            <span
                                class="color-danger"
                                v-else-if="scope.row.sysUserLogin !== null && scope.row.sysUserLogin.leave ==='2'"
                            >离休</span>
                            <span
                                class="color-danger"
                                v-else-if="scope.row.sysUserLogin === null || scope.row.sysUserLogin.leave === null"
                            ></span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        type="noFilter"
                        label="状态"
                        width="80"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <span
                                class="color-danger"
                                v-if="scope.row.status==='0'"
                            >停用</span>
                            <span
                                class="color-primary"
                                v-else-if="scope.row.status==='1' && scope.row.sysUserLogin && scope.row.sysUserLogin.status==='0'"
                            >启用</span>
                            <span
                                class="color-danger"
                                v-else-if="scope.row.status==='1' && scope.row.sysUserLogin && scope.row.sysUserLogin.status==='1'"
                            >锁定</span>
                            <span
                                class="color-danger"
                                v-else-if="scope.row.status==='1' && scope.row.sysUserLogin && scope.row.sysUserLogin.status==='2' && scope.row.sysUserLogin.expireStatus === '0'"
                            >密码过期</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        type="noFilter"
                        fixed="right"
                        width="105"
                    >
                        <template slot-scope="scope">
                            <!-- <el-dropdown
                                @command="handleCommand"
                                :show-timeout="50"
                                style="margin-left: 5px;"
                            >
                                <span
                                    class="el-dropdown-link"
                                    @click.stop
                                >
                                    操作<i class="el-icon-arrow-down"></i>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item
                                        :command="['edit', scope.row]"
                                        v-privilege="activeMenu + 'EDIT'"
                                    >修改</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['czmm', scope.row]"
                                        v-privilege="activeMenu + 'RESETPASSWORD'"
                                    >重置密码</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['jcsd', scope.row]"
                                        v-privilege="activeMenu + 'UNLOCK'"
                                    >解除锁定</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['tyqy', scope.row]"
                                        v-privilege="activeMenu + 'DEACTIVATEENABLE'"
                                    >{{!Number(scope.row.status) ? '启用':'停用'}}</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown> -->
                            <el-dropdown
                                split-button
                                size="mini"
                                type="primary"
                                trigger="click"
                                @click="handleCommand(['edit', scope.row])"
                                @command="handleCommand"
                                v-privilege="activeMenu + 'EDIT'"
                            >
                                修改
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item
                                        :command="['czmm', scope.row]"
                                        v-privilege="activeMenu + 'RESETPASSWORD'"
                                    >重置密码</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['jcsd', scope.row]"
                                        v-privilege="activeMenu + 'UNLOCK'"
                                    >解除锁定</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['tyqy', scope.row]"
                                        v-privilege="activeMenu + 'DEACTIVATEENABLE'"
                                    >{{!Number(scope.row.status) ? '启用':'停用'}}</el-dropdown-item>
                                    <el-dropdown-item
                                        :command="['del', scope.row]"
                                        v-privilege="activeMenu + 'DELETE'"
                                        style="color: #ff474e"
                                    >删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="yt-table-page">
                    <el-pagination
                        @size-change="pageSizeChange"
                        @current-change="pageCurrentChange"
                        :current-page="tableParams.form.pageNum"
                        :page-sizes="[10, 20, 50, 100, 200]"
                        :page-size="tableParams.form.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="tableParams.page.total"
                    >
                    </el-pagination>
                </div>
            </div>
        </div>

        <div
            is='usersAddAndEdit'
            v-if="userModal.show"
            :operate="operate"
            :item="table.item"
            @on-then="userModalThen"
            @on-close="userModalClose"
        ></div>

        <!-- 分配岗位 -->
        <el-dialog
            :title="'岗位选择'"
            :visible.sync="postModal.show"
            width="680px"
            center
        >
            <el-table stripe
                ref="postTable"
                v-loading="postModal.loading"
                border
                :height="400"
                highlight-current-row
                :data="postModal.list"
                @selection-change="postSelectChange"
            >
                <el-table-column
                    type="selection"
                    align="center"
                    fixed="left"
                ></el-table-column>
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="postCode"
                    label="岗位编码"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="postName"
                    label="岗位名称"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="cate"
                    label="岗位类别"
                    min-width="80"
                ></el-table-column>
                <!-- <el-table-column :show-overflow-tooltip="true" prop="level" label="岗位级别"
        min-width="150"></el-table-column> -->
                <el-table-column
                    :show-overflow-tooltip="true"
                    prop="postDesc"
                    label="职责描述"
                    min-width="150"
                ></el-table-column>
                <el-table-column
                    label="岗位类型"
                    prop="postType"
                    min-width="150"
                >
                    <template slot-scope="scope">
                        <template v-for="item in postModal.items">
                            <span
                                :key="item.postId"
                                v-if="item.postId === scope.row.postId && item.postType === '1'"
                            >主岗位</span>
                            <span
                                :key="item.postId"
                                v-if="item.postId === scope.row.postId && item.postType === '2'"
                            >副岗位</span>
                            <el-button
                                :key="item.postId + 'btn'"
                                v-if="item.postId === scope.row.postId && item.postType === '2'"
                                @click="postTypeMain(item)"
                                size="mini"
                                :style="{padding: '3px 6px'}"
                            >设为主岗位</el-button>
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <div
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="postModal.show = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    :loading="postModal.okLoading"
                    @click="postUserOk"
                    size="small"
                >确 定</el-button>
            </div>
        </el-dialog>
        <icore-individual
            uiId="pangguoqianperf"
            indexClass="individual-index"
        ></icore-individual>
    </div>

</template>
<script>
import store from '@/store/index.js';
import usersAddAndEdit from './usersAddAndEdit.vue';
import { dgTree } from '@/utils/util.js';
import checkPermission from '@/config/permission.js';
export default {
    components: {
        usersAddAndEdit
    },
    data () {
        return {
            setFilterCurrent: null,
            icoreFilterFlag: false,
            showButton: false,
            filterText: '',
            store,
            activeMenu: '',
            treeHeight: 600,
            tableHeight: 300,
            operate: 'detail',
            treeLoading: false,
            tabLoading: false,
            table: {
                list: [],
                //  选中项
                items: [],
                item: {}
            },
            tableParams: JSON.parse(JSON.stringify(store.state.tableParams)),
            //  modal
            userModal: {
                show: false
            },
            //  岗位弹窗
            postModal: {
                show: false,
                userId: '',
                //  岗位列表
                list: [],
                //  中间表列表
                postUserList: [],
                //  选中岗位
                items: [],
                loading: false,
                okLoading: false
            },
            orgList: [],
            filterStatus: false,
            individualInfo: {},
            activeRow: {},
            prEdit: false,
            prReset: false,
            prUnlock: false,
            prDeact: false
        }
    },
    watch: {
        filterText (val) {
            this.$refs.orgTree.filter(val);
        }
        // icoreFilterFlag (val) {
        //     if (this.icoreFilterFlag === false) {
        //         this.tableParams.page.total = this.tableParams.page.totalBack;
        //     }
        //     if (val) {
        //         this.setFilterCurrent = this.tableParams.form.pageNum;
        //     }
        // }
        // table: {
        //     deep: true,
        //     handler: function (newVal,oldVal){
        //         this.tableParams.page.total = this.tableParams.page.totalBack;
        //     }
        // }
    },
    computed: {
        //  菜单树数据
        orgTree () {
            let tree = this.store.state.system.organizManage.tree;
            //
            dgTree(tree, 'children', item => {
                if ('children' in item && item.children.length < 1) {
                    delete item.children;
                }
            });
            return tree;
        },
        //  树配置
        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);
            }
        },
        //  选中节点数据
        treeItem () {
            return this.store.state.system.sysPosts.treeItem;
        }
    },
    created () {
      this.activeMenu = window.localStorage.getItem('activeMenu');
    },
    mounted () {
        this.initData();
        //  设置树区域高度
        this.treeHeight = this.getTreeHeight(this.$refs['orgTree'].$el);
        //
        this.$nextTick(() => {
            this.showButton = true;
            this.tableHeight = this.getTreeHeight(this.$refs['userTable'].$el) - 70;
            this.prEdit = this.checkPrivilege(this.activeMenu + 'EDIT');
            this.prReset = this.checkPrivilege(this.activeMenu + 'RESETPASSWORD');
            this.prUnlock = this.checkPrivilege(this.activeMenu + 'UNLOCK');
            this.prDeact = this.checkPrivilege(this.activeMenu + 'DEACTIVATEENABLE');
            this.icoreFilterFlag = true;
        });
    },
    methods: {
        checkPermission,
        async initData () {
            this.treeLoading = true;
            this.tabLoading = true;
            this.getOrgList();
            //  查询机构树
            await this.store.dispatch('system/organizManage/tree').then(res => {
                if (res.code === '0') {
                    this.store.commit('system/organizManage/tree', res.data);
                    // console.log(this.store.state.system.organizManage.tree)
                    this.treeLoading = false;
                } else {
                    this.$message.error(res.message);
                }
            });
            this.getUser(this.tableParams.form);
        },
        //  取列表
        getUser (form) {
            this.tabLoading = true;
            this.store.dispatch('system/usersManage/list', form).then(res => {
                if (res.code === '0') {
                    this.table.list = res.data.list;
                    for (let a = 0; a < this.table.list.length; a++) {
                        this.table.list[a].orgName = this.getOrgName(this.orgTree, this.table.list[a].orgCode)
                    }
                    //   this.setFilterDatas(this.$refs.userTable.columns, this.table.list, ['userCode', 'userName','mobile','duty','orgName']);
                    this.tableParams.form.pageNum = res.data.pageNum;
                    this.tableParams.form.pageSize = res.data.pageSize;
                    this.tableParams.page.total = res.data.total;
                    this.tableParams.page.totalBack = res.data.total;
                    let index = 0;
                    for (let i = 0; i < this.table.list.length; i++) {
                        if (this.table.list[i].userId === this.activeRow.userId) {
                            index = i;
                        }
                    }
                    this.$refs['userTable'].setCurrentRow(this.table.list[index])
                    this.tabLoading = false;
                } else {
                    this.$message.error(res.message);
                    this.tabLoading = false;
                    this.tableParams.form.pageNum = 1;
                    this.tableParams.page.total = 0;
                }
            });
        },
        //  搜索
        search () {
            console.log('111', new Date().getTime())
            this.store.dispatch('system/organizManage/tree').then(res => {
                console.log('organizManage', new Date().getTime())
                if (res.code === '0') {
                    this.store.commit('system/organizManage/tree', res.data);
                    this.axios.get('pass/v1/sysorgs/?pageSize=' + 1000 + '&pageNum=' + 1).then(res => {
                        console.log('sysorgs', new Date().getTime())
                        if (res.code === '0') {
                            this.orgList = res.data.list;
                            this.tableParams.form.pageNum = 1
                            this.getUser(this.tableParams.form);
                            this.$refs.userTable.clearFilter();
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  点击树事件
        nodeClick (item) {
            //  放入
            this.store.commit('system/sysPosts/treeItem', item);
            //  取岗位列表
            this.tableParams.form.orgCode = item.orgCode;
            this.getUser(this.tableParams.form);
        },
        //  计算树区域高度
        getTreeHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        //  计算table高度
        getTableHeight (dom) {
            return ((window.innerHeight - dom.offsetTop) - 100) / 2;
        },
        //  删除用户
        delUser (items) {
            let that = this;
            this.$confirm('确定要删除记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.store.dispatch('system/usersManage/delUser', items).then(res => {
                    if (res.code === '0') {
                        this.$message.success('删除成功');
                        this.getUser(this.tableParams.form);
                    } else {
                        this.$message.error(res.message);
                    }
                });
                // 删除用户下的角色关联
                that.axios.get('pass/v1/sysuserroles/?userId=' + items[0].userId + '&pageNum=1&pageSize=100').then((result) => {
                    if (result.data.list.length > 0) {
                        for (let item of result.data.list) {
                            that.axios.delete('pass/v1/sysuserroles/' + item.id).then(res => {
                                // do somthing
                            }).catch((err) => {
                                console.log(err);
                                return false;
                            })
                        }
                    }
                }).catch((err) => {
                    console.log(err);
                })
            }).catch((err) => {
                console.log(err)
                this.$message.error('操作失败');
            });
        },
        //  操作
        operateClick (str, item) {
            this.operate = str;
            //
            switch (str) {
                case 'add':
                    this.userModal.show = true;
                    this.table.item = item;
                    break;
                case 'edit':
                    this.userModal.show = true;
                    this.table.item = item;
                    this.$refs['userTable']
                    this.activeRow = item;
                    break;
                case 'detail':
                    this.userModal.show = true;
                    this.table.item = item;
                    break;
                case 'del':
                    this.delUser([item]);
                    break;
                case 'post':
                    this.postModal.show = true;
                    this.table.item = item;
                    //  查询岗位
                    this.getPost(item.userId);
                    break;
                case 'czmm':
                    this.resaltPassword(item);
                    break;
                case 'jcsd':
                    this.unlock(item);
                    break;
                case 'tyqy':
                    this.editUser(item);
                    break
            }
        },
        // 重置密码
        resaltPassword (item) {
            let that = this;
            let data = {
                password: '123456'
            };
            this.axios.put('pass/v1/sysusers/resetPassword/' + item.userId, data).then(res => {
                if (res.code === '0') {
                    this.$message.success(res.message);
                    this.getUser(this.tableParams.form);
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        // 解除锁定
        unlock (item) {
            let that = this;
            this.axios.put('pass/v1/sysuserlogins/resetLoginInfo/' + item.userCode).then(res => {
                if (res.code === '0') {
                    this.$message.success('已成功解锁用户')
                    this.getUser(this.tableParams.form);
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        //  行点击
        userTableTrClick (item) {
            this.operateClick('detail', item);
        },
        //
        pageSizeChange (size) {
            this.tableParams.form.pageSize = size;
            this.getUser(this.tableParams.form);
        },
        //
        pageCurrentChange (index) {
            this.tableParams.form.pageNum = index;
            this.getUser(this.tableParams.form);
            // if (this.icoreFilterFlag) {
            //     this.icoreFilterFlag = false;
            // }
        },
        //  操作点击
        handleCommand (command) {
            this.operateClick(command[0], command[1]);
        },
        // //  table选中
        // selectChange (items) {
        //   this.table.items = items;
        // },
        //  弹窗完成
        userModalThen (str, item) {
            switch (str) {
                case 'close':
                    this.userModal.show = false;
                    break;
                case 'success':
                    this.userModal.show = false;
                    //  刷新
                    this.getUser(this.tableParams.form);
                    break;
            }
        },
        //  关闭弹窗
        userModalClose () {

        },
        //  选择下拉
        cascaderChange (codeArr) {
            //
            this.tableParams.form.orgCode = codeArr[codeArr.length - 1];
        },
        // ===================== 岗位 =============
        //  取岗位列表
        getPost (userId) {
            let form = JSON.parse(JSON.stringify(store.state.tableParams));
            this.table.loading = true;
            //  查询岗位列表
            form.pageSize = 100000;
            this.store.dispatch('system/sysPosts/list', form).then(res => {
                this.table.loading = false;
                if (res.code === '0') {
                    this.postModal.list = res.data.list;
                    //  查询用户关联
                    let form = JSON.parse(JSON.stringify(store.state.tableParams));
                    form.userId = userId;
                    form.pageSize = 100000;
                    this.getPostUser(form);
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  取中间表
        getPostUser (form) {
            //  查询岗位列表
            form.pageSize = 100000;
            this.store.dispatch('system/usersManage/postUser', form).then(res => {
                if (res.code === '0') {
                    this.postModal.postUserList = res.data.list;
                    //
                    this.$nextTick(() => {
                        this.defaultPostUser();
                    });
                } else {
                    this.$message.error(res.message);
                }
            });
        },
        //  选中默认已绑定项
        defaultPostUser () {
            //  选中
            let tab = this.postModal.list;
            let pul = this.postModal.postUserList;
            for (let item of tab) {
                for (let item2 of pul) {
                    if (item.postId === item2.postId) {
                        //  选中
                        this.$refs['postTable'].toggleRowSelection(item, true);
                        break;
                    }
                }
            }
            //  重新选中默认项
            setTimeout(() => {
                this.postModal.items.forEach(item => {
                    for (let item2 of this.postModal.postUserList) {
                        if (item.postId === item2.postId) {
                            item.postType = item2.postType;
                            break;
                        }
                    }
                });
                this.postModal.items = [...this.postModal.items];
            }, 100);
        },
        // 选择
        postSelectChange (items) {
            this.postModal.items = items;
            // //  清空
            // for (let item of this.postModal.list) {
            //   delete item.postType;
            // }
            //  设置岗位类型
            let selectItem = null;
            for (let item of items) {
                if (item.postType !== '1') {
                    item.postType = '2';
                } else {
                    selectItem = item;
                }
            }
            if (!selectItem && items.length > 0) {
                items[0].postType = '1';
            }
        },
        //  设为主岗位
        postTypeMain (item) {
            //  原主岗位设为 兼岗位
            this.postModal.items.forEach(item => {
                item.postType = '2';
            });
            //
            item.postType = '1';
            this.postModal.items = [...this.postModal.items];
            // for (let item of this.postModal.list) {
            //   if (item.postType === '1') {
            //     item.postType = '2';
            //     break;
            //   }
            // }
            // //  设置主岗位
            // item.postType = '1';
            // console.log(this.postModal.list);
        },
        //  设置用户岗位
        async setInsertUserPosts (userId, items) {
            let form = {
                userId: userId,
                form: []
            }
            //  整理数据  岗位类型：1-主岗位 2-兼岗位
            for (let item of items) {
                form.form.push({
                    postId: item.postId,
                    postType: item.postType
                });
            }
            //
            const promise = await this.store.dispatch('system/userAuth/insertUserPosts', form).then(res => {
                if (res.code === '0') {
                    this.$message.success('设置成功');
                    this.postModal.show = false;
                } else {
                    this.$message.error(res.message);
                }
            });
            return promise;
        },
        //  确定
        postUserOk () {
            //  格式化选中项
            //  提交
            this.setInsertUserPosts(this.table.item.userId, this.postModal.items);
        },
        //  格式化选中项
        filterPostUser () {

        },
        // 树形控件过滤数据
        filterOrgTree (value, data) {
            if (!value) return true;
            return data.orgName.indexOf(value) !== -1;
        },
        // 停用启用
        editUser (item) {
            let data = new FormData();
            let that = this;
            let status = item.status === '1' ? '0' : '1';
            data.append('status', status);
            data.append('leave', item.sysUserLogin.leave);
            that.store.dispatch('system/usersManage/editUser', { id: item.userId, form: data }).then(res => {
                if (res.code === '0') {
                    let msg = res.data.status === '1' ? '启用' : '停用';
                    that.$message.success('该账户已成功' + msg);
                    res.data.orgName = item.orgName;
                    that.updataUserInfo(res.data);

                } else {
                    that.$message.error(res.message);
                }
            });
        },
        // 无刷新更新数据 
        updataUserInfo (item) {
            let that = this;
            for (let i = 0; i < that.table.list.length; i++) {
                if (that.table.list[i].userId === item.userId) {
                    for (let key in that.table.list[i]) {
                        that.table.list[i][key] = item[key]
                    }
                }
            }
        },
        // 查询机构名称
        getOrgName (list, code) {
            var name = '';
            for (let i = 0; i < list.length; i++) {
                try {
                    if (list[i].orgCode === code) {
                        name = list[i].orgName
                        return name
                    } else if (list[i].children && list[i].children.length >= 1) {
                        name = this.getOrgName(list[i].children, code);
                        if (name) {
                            return name
                        }
                    }
                } catch (error) {
                    console.log(error)
                }
            }
            return name;
        },
        // 表格过滤
        // filterChange (filters) {
        //   var _this = this;
        //   _this.setFilterDatas(_this.$refs.userTable.columns, _this.$refs.userTable.tableData, ['userCode', 'userName','mobile','duty','orgName']);
        //   if(_this.filterStatus){
        //       _this.filterStatus = false;
        //       _this.initData();

        //   } else {
        //       _this.filterStatus = true;
        //       _this.tableParams.page.total = _this.$refs.userTable.tableData.length;
        //   }

        // },
        // 获取机构树列表
        getOrgList () {
            let that = this;
            that.axios.get('pass/v1/sysorgs/?pageSize=' + 1000 + '&pageNum=' + 1).then(res => {
                if (res.code === '0') {
                    that.orgList = res.data.list;
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        icoreFilterChange (item) {
            let filter1 = JSON.stringify(this.$refs['userTable'].store.states.filterIndividualMap),
                filter2 = JSON.stringify(this.$refs['userTable'].store.states.filterMapper);
            if (filter1 === '{}' && filter2 === '{}') {
                this.tableParams.form.pageNum = this.setFilterCurrent;
                this.tableParams.page.total = this.tableParams.page.totalBack;
            } else {
                this.tableParams.form.pageNum = 1;
                this.tableParams.page.total = item.filterData.length;
            }
        },
        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;
            }
        },
        changeOrg () {
            this.$forceUpdate()
        }
    }
}
</script>
<style lang="less">
.userManage {
    position: relative;
    min-width: 790px;
    .el-tree-node {
        .el-tree-node__label {
            border-bottom: 0;
        }
    }
}

.og-st-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: keep-all;
    padding-right: 60px;
}

.organizManage-main {
    height: 100%;
}

.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;
}

.el-tree {
    overflow-x: hidden !important;
}

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

.FormorganizManage-main {
    margin: 20px 20px;
}
.post-m {
    margin: 20px;
}
.filterTree {
    width: 95%;
    margin: 10px 2.5%;
}
.el-select {
    width: 100%;
}
.individual-index {
    .setPosition {
        position: relative;
    }
}
.public-function-div .refresh {
    position: absolute;
    right: 15px;
    top: 10px;
}
.public-function-div .refresh2 {
    position: absolute;
    right: 80px;
    top: 10px;
}
.color-primary {
    color: #409eff;
}
</style>
