/***********************************************************************
 * 目的: 用户职务管理-主要用于流程建模根据职务配置
 * 作者: heyf@steerinfo.com
 * 创建日期: 2020-06-29
 *
 * 更新历史:
 * 日期                    人员                变更目的
 * 2020-06-29        修改人员名     修改的原因和目的*
**********************************************************************/
<template>
    <div class="dutysManage">
        <div class="dutysManage-left">
            <div class="duty-table-header">
                <div style="margin-top:10px;margin-left:20px; font-size:16px;float:left;">职级列表</div>
                <el-button
                    size="small"
                    type="primary"
                    @click="operateDuty('add', {})"
                    style="float: right;margin-right: 20px;margin-top: 7px;"
                    v-privilege="activeMenu + 'ADD'"
                >新增职级</el-button>
            </div>
            <div style="width: 100%;padding: 20px 20px 0 20px;position: relative;">
                <el-table
                    ref="dutyTable"
                    v-loading="tableLoading"
                    @filter-change="filterDutyChange"
                    @row-click="nodeClick"
                    @current-change="handleCurrentChange"
                    border
                    :height="tableHeight"
                    highlight-current-row
                    :data="tableData"
                >
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="dutyName"
                        label="职级名称"
                        align="center"
                        :filter-method="filterColumn"
                    > 
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        prop="remark"
                        label="职级描述"
                        align="center"
                        :filter-method="filterColumn"
                    >
                    </el-table-column>
                    <el-table-column
                        :show-overflow-tooltip="true"
                        label="操作"
                        align="center"
                        width="195"
                    >
                        <template slot-scope="scope">
                            <el-button
                                type="danger"
                                size="mini"
                                @click="operateDuty('del',scope.row)"
                                v-privilege="activeMenu + 'DELETE'"
                            >删除</el-button>
                            <el-button
                                size="mini"
                                @click="operateDuty('edit',scope.row, scope.$index)"
                                v-privilege="activeMenu + 'PUT'"
                            >编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <div class="dutysManage-right">
            <el-tabs class="right-tabs">
                <el-tab-pane label="关联用户信息">
                    <!-- <div class="userTable-header">关联用户信息</div> -->
                    <el-table
                        ref="userTable"
                        style="margin: 20px 20px 0 20px;width: calc(100% - 40px);"
                        v-loading="userTable.loading"
                        @filter-change="filterChange"
                        border
                        :height="tableHeight"
                        highlight-current-row
                        :data="userTable.list"
                    >
                        <el-table-column
                            type="index"
                            label="序号"
                            min-width="80"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            :show-overflow-tooltip="true"
                            prop="userCode"
                            label="账户"
                            :filter-method="filterColumn"
                            min-width="150"
                        ></el-table-column>
                        <el-table-column
                            :show-overflow-tooltip="true"
                            prop="userName"
                            label="姓名"
                            :filter-method="filterColumn"
                            min-width="150"
                        ></el-table-column>
                        <el-table-column
                            :show-overflow-tooltip="true"
                            prop="orgName"
                            label="所属机构"
                            :filter-method="filterColumn"
                            min-width="150"
                        >
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="关联机构信息">
                    <el-table
                        ref="orgTable"
                        style="margin: 20px 20px 0 20px;width: calc(100% - 40px);"
                        v-loading="orgTable.loading"
                        @filter-change="filterChange2"
                        border
                        :height="tableHeight"
                        highlight-current-row
                        :data="orgTable.list"
                    >
                        <el-table-column
                            type="index"
                            label="序号"
                            min-width="80"
                            align="center"
                        ></el-table-column>
                        <el-table-column
                            :show-overflow-tooltip="true"
                            prop="orgCode"
                            label="机构编码"
                            :filter-method="filterColumn"
                            min-width="150"
                        ></el-table-column>
                        <el-table-column
                            :show-overflow-tooltip="true"
                            prop="orgName"
                            label="机构名称"
                            :filter-method="filterColumn"
                            min-width="150"
                        ></el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </div>
        <!-- 弹窗 -->
        <el-dialog
            :title="status==='add' ? '新增职级' : '编辑职级'"
            :visible.sync="dialogVisiable"
            width="400px"
            center
        >
            <div style="text-align:center;margin:20px 0 40px 0;">
                <el-form
                    ref="dialogForm"
                    :model="form"
                    :rules="rules"
                    label-width="90px"
                >
                    <!-- <el-form-item
                        label="父级职级"
                        prop="pId"
                    >
                        <el-select
                            v-model="form.pId"
                            size="small"
                            filterable
                            clearable
                            placeholder="请选择职级"
                            :disabled="status === 'add' ? false : true"
                            style="width: 100%;"
                        >
                            <el-option
                            v-for="item in tableData"
                            :key="item.dutyId"
                            :label="item.dutyName"
                            :value="item.dutyId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        label="职级编码"
                        prop="dutyCode"
                    >
                        <el-input
                            v-model="form.dutyCode"
                            :disabled="status === 'add' ? false : true"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item> -->
                    <el-form-item
                        label="职级名称"
                        prop="dutyName"
                    >
                        <el-input
                            v-model="form.dutyName"
                            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="form.remark"
                            size="small"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span
                slot="footer"
                class="dialog-footer"
            >
                <el-button
                    @click="dialogVisiable = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    :loading="saveLoading"
                    type="primary"
                    @click="submit"
                    size="small"
                >保存</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import store from '@/store/index.js';
import { checkCharLength, checkCharLength2, checkCharNoChinese, checkChar } from '@/utils/validator.js';
import { dgTree, objAssign } from '@/utils/util.js';
    export default {
        data () {
            return {
                store,
                activeMenu: '',
                companys: [], // 用户公司列表
                companyId: '', // 选择公司Id
                companyName: '', // 选择公司名称
                tableLoading: false,
                tableData: [],
                tableHeight: 500,
                dialogVisiable: false,
                status: 'add',
                saveLoading: false,
                form: {
                    companyId: '',
                    id: '',
                    dutyId: '',
                    dutyName: '',
                    dutyCode: '',
                    pId: '',
                    PCode: '',
                    status: 0,
                    remark: ''
                },
                rules: {
                    dutyName: [
                        { required: true, message: '职级名称不能为空', trigger: 'change' },
                        { validator: checkCharLength, max: 32, trigger: 'change' },
                        { validator: checkChar, trigger: 'change' }
                    ]
                },
                // 用户列表
                userTable: {
                    height: 600,
                    loading: false,
                    list: []
                },
                // 用户列表
                orgTable: {
                    height: 600,
                    loading: false,
                    list: []
                },
                //  机构树
                orgTree: {
                    tree: []
                },
                userMap: [],
                activeRow: {}, // 当前行
                orgMap: []
            }
        },
        created () {
            this.activeMenu = window.top.localStorage.getItem('activeMenu');
        },
        mounted () {
            // 获取公司信息
            this.companys = JSON.parse(window.top.localStorage.getItem('companys'));
            this.companyId = window.top.localStorage.getItem('companyId');
            if (this.companyId !== '' && this.companyId !== null) {
                this.companyName = this.companys.find((x) => x.id === this.companyId).companyName;
            }
            this.getTableData();
            this.getUserMap();
            this.getOrg();
            this.$nextTick(() => {
                //  设置树区域高度
                this.tableHeight = this.getTableHeight(this.$refs['dutyTable'].$el) - 120;
            });
        },
        methods: {
            //  计算表格区域高度
            getTableHeight (dom) {
                return window.innerHeight - dom.offsetTop;
            },
            // 用户过滤
            filterChange (filters) {
                var _this = this;
                _this.setFilterDatas(_this.$refs.userTable.columns, _this.$refs.userTable.tableData, ['userCode', 'userName', 'orgName']);
            },
            // 机构过滤
            filterChange2 (filters) {
                var _this = this;
                _this.setFilterDatas(_this.$refs.orgTable.columns, _this.$refs.orgTable.tableData, ['orgCode', 'orgName']);
            },
            filterDutyChange (filters) {
                var _this = this;
                _this.setFilterDatas(_this.$refs.dutyTable.columns, _this.$refs.dutyTable.tableData, ['dutyName', 'remark']);
            },
            // 当前行发生改变
            handleCurrentChange () {
                // this.getDutyUser(this.activeRow);
            },
            getUserMap () {
                this.axios.get('pass/v1/sysusers/?pageSize=1000000' + '&companyId=' + this.companyId).then((res) => {
                    if (res.code === '0') {
                        res.data.list.forEach((item, index) => {
                            item['orgName'] = this.getOrgName(this.orgTree.tree, item.orgCode)
                            this.userMap[item.id] = item;
                        });
                    } else {
                        this.$message.error(res.message);
                    }
                });
            },
            getTableData () {
                this.tableLoading = true;
                let form = {
                    pageNum: 1,
                    pageSize: 100000,
                    companyId: this.companyId
                }
                this.axios.get('pass/v1/sysdutys/', {params: form}).then((res) => {
                    if (res.code === '0') {
                        this.tableData = res.data.list;
                        // 设置过滤数据 setFilterDatas(列数组对象, 数据, 需要过滤的字段, 列名转义对象)
                        this.setFilterDatas(this.$refs.dutyTable.columns, res.data.list, ['dutyName', 'remark']);
                        this.tableLoading = false;
                    } else {
                        this.$message.error(res.message);
                    }
                }).catch((err) => {
                    console.log(err);
                })
            },
            nodeClick (item) {
                this.activeRow = item;
                this.getDutyUser(item);
                this.getDutyOrg(item);
            },
            // 取机构树
            getOrg () {
                this.store.dispatch('system/organizManage/tree', this.companyId).then(res => {
                    if (res.code === '0') {
                        dgTree(res.data, 'children', item => {
                            if ('children' in item && (item.children === null || item.children.length < 1)) {
                                delete item.children;
                            }
                        });
                        this.orgTree.tree = res.data;
                        this.getTreeAll(this.orgTree.tree);
                    } else {
                        this.$message.error(res.message);
                    }
                });
            },
            // 遍历树获获取所有机构
            getTreeAll (tree) {
                let arr = []
                if (!!tree && tree.length !== 0) {
                    tree.forEach(item => {
                        let obj = {}
                        obj = {...item}
                        arr.push(obj)
                        if (obj.hasOwnProperty('children') && obj.children.length > 0) {
                            obj.children = this.getTreeAll(item.children);
                        }
                    })
                }
                arr.forEach((item, index) => {
                    this.orgMap[item.id] = item;
                });
            },
            // 获取职级下用户
            getDutyUser (item) {
                this.userTable.loading = true;
                let form = {
                    pageNum: 1,
                    pageSize: 100000,
                    companyId: this.companyId,
                    resourceType: '1',
                    dutyId: item.id
                }
                this.axios.get('pass/v1/sysuserdutys/', {params: form}).then(res => {
                    if (res.code === '0') {
                        let data = [];
                        for (let item of res.data.list) {
                            this.userMap[item.resourceId] ?data.push(this.userMap[item.resourceId]): ''
                        }
                        this.userTable.list = data;
                        // 设置过滤数据 setFilterDatas(列数组对象, 数据, 需要过滤的字段, 列名转义对象)
                        // this.setFilterDatas(this.$refs.userTable.columns, this.userTable.list, ['userCode', 'userName', 'orgName']);
                        this.userTable.loading = false;
                    }
                }).catch((err) => {
                    console.log(err)
                })
            },
            // 获取职级机构信息
            getDutyOrg (item) {
                this.orgTable.loading = true;
                let form = {
                    pageNum: 1,
                    pageSize: 100000,
                    companyId: this.companyId,
                    resourceType: '2',
                    dutyId: item.id
                }
                this.axios.get('pass/v1/sysuserdutys/', {params: form}).then(res => {
                    if (res.code === '0') {
                        let data = [];
                        for (let item of res.data.list) {
                            data.push(this.orgMap[item.resourceId])
                        }
                        this.orgTable.list = data;
                        // 设置过滤数据 setFilterDatas(列数组对象, 数据, 需要过滤的字段, 列名转义对象)
                        this.setFilterDatas(this.$refs.orgTable.columns, this.orgTable.list, ['orgCode', 'orgName']);
                        this.orgTable.loading = false;
                    }
                }).catch((err) => {
                    console.log(err)
                })
            },
            // 查询机构名称
            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;
            },
            operateDuty (str, item, index, node) {
                switch (str) {
                    case 'add':
                        this.status = 'add';
                        this.dialogVisiable = true;
                        break;
                    case 'edit':
                        this.status = 'edit';
                        this.form = item;
                        this.dialogVisiable = true;
                        break;
                    case 'del':
                        //
                        let data = item;
                        this.$confirm('确定要删除记录吗？', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.delDuty(item);
                        }).catch(() => {
                            this.$message.info('已取消操作');
                        });
                        break;
                }
            },
            delDuty (item) {
                this.axios.delete('pass/v1/sysdutys/' + item.id).then((res) => {
                    if (res.code === '0') {
                        this.$message.success('删除成功')
                        this.getTableData();
                    } else {
                        this.$message.error(res.message);
                    }
                }).catch((err) => {
                    console.log(err);
                })
            },
            submit () {
                if (this.status === 'add') {
                    this.form.companyId = this.companyId;
                    this.axios.post('pass/v1/sysdutys/', this.form).then((res) => {
                        if (res.code === '0') {
                            this.$message.success('新增成功');
                            this.dialogVisiable = false;
                            this.resetForm();
                            this.getTableData();
                        } else {
                            this.$message.error(res.message);
                        }
                    }).catch((err) => {
                        console.log(err);
                    })
                } else {
                    this.axios.put('pass/v1/sysdutys/' + this.form.id, this.form).then((res) => {
                        if (res.code === '0') {
                            this.$message.success('修改成功');
                            this.dialogVisiable = false;
                            this.resetForm();
                            this.getTableData();
                        } else {
                            this.$message.error(res.message);
                        }
                    }).catch((err) => {
                        console.log(err);
                    })
                }
            },
            resetForm() {
                this.$refs['dialogForm'].resetFields();
            }
        }
    }
</script>

<style lang="less">
    .dutysManage {
        .dutysManage-left {
            width: 40%;
            border-right: 1px solid #e0e0e0;
            float: left;
            overflow-x: hidden;
            height: inherit;
            .duty-table-header {
                height: 42px;
                border-bottom: 1px solid #d5d5d5;
                position: relative;
                overflow: hidden;
            }
        }
        .dutysManage-right {
            width: 60%;
            float: left;
            .userTable-header {
                height: 42px;
                width: 100%;
                border-bottom: 1px solid #d5d5d5;
                position: relative;
                font-size:16px;
                padding-left: 20px;
                line-height: 42px;
            }
            .right-tabs {
                .roles-menuTree {
                    .el-checkbox {
                        margin-right: 10px;
                    }
                }
                .el-tabs__item {
                    height: 42px;
                    line-height: 42px;
                }
                .el-tabs__nav-wrap::after {
                    height: 1px;
                    background-color: rgb(213, 213, 213);
                }
                .el-tabs__active-bar {
                    height: 1px;
                }
                .el-tabs__nav {
                    margin-left: 20px;
                }
            }
            .foot-style {
                margin: 5px 0 0;
                text-align: right;
            }
        }
    }
</style>