<template>
    <div class="ajm-panel">
        <div class="ajm-search-form">
            <el-form ref="searchForm" :model="searchForm" :inline="true">
                <el-row>
                    <el-col :span="6">
                        <el-form-item class="operate-buttons">
                            <el-button type="primary" icon="el-icon-ajm-add" @click="addUser" v-permission-code="'001001004_BTN'">{{$t('message.add')}}</el-button>
                            <!--<el-button icon="el-icon-delete" @click="batchDeleteUser" v-permission-code="'001001005_BTN'">删除</el-button>-->
                        </el-form-item>
                    </el-col>
                    <el-col :span="18" class="ajm-search-items">
                        <el-form-item>
                            <el-input id="enterSearch" class="search-item" v-model="searchForm.userName" :placeholder="$t('message.UserInfo.confirmUserName')">
                            </el-input>
                        </el-form-item>
                        <el-form-item class="ajm-search-btns">
                            <el-button icon="el-icon-ajm-search" @click="search"></el-button>
                            <el-button icon="el-icon-ajm-refresh" @click="refreshSearch"></el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <div class="ajm-table tool-table">
            <el-table ref="filterTable" :data="pageResult.list" v-loading="listLoading" @sort-change="handleSortChange" @filter-change="handleFilterChange" tooltip-effect="light">
                <el-table-column sortable type="index" :label="$t('message.Table.index')" width="70" />
                <el-table-column prop="userName" :label="$t('message.UserInfo.userName')" :show-overflow-tooltip="true" min-width="150" />
                <el-table-column prop="realName" :label="$t('message.UserInfo.realName')" :show-overflow-tooltip="true"/>
                <el-table-column prop="departmentName" :label="$t('message.Manager.department')" :show-overflow-tooltip="true"/>
                <el-table-column prop="status.name" :label="$t('message.Table.status')" :filters="statusUser" :filter-multiple="false" column-key="status" :filter-method="filterStatus" width="70" />
                <el-table-column prop="locked" :label="$t('message.UserBaseMain.isLock')" :formatter="formatterLocked" width="70"/>
                <el-table-column prop="expired" :label="$t('message.UserBaseMain.expired')" :formatter="formatterExpired" width="70"/>
                <el-table-column prop="createdUserName" :label="$t('message.Table.createdId')" :show-overflow-tooltip="true"/>
                <el-table-column prop="createdTime" :label="$t('message.Table.createdTime')" sortable="custom" width="180"/>
                <el-table-column :label="$t('message.Table.operate')" width="180" fixed="right">
                    <template slot-scope="scope">
                        <el-tooltip :content="$t('message.edit')" placement="top">
                            <el-button size="small" type="text" @click="editUser(scope.$index, scope.row)" v-permission-code="'001001006_BTN'">
                                <i class="el-icon-ajm-edit"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.UserBaseMain.resetPsw')" placement="top">
                            <el-button size="small" type="text" @click="resetPassword(scope.$index, scope.row)">
                                <i class="el-icon-ajm-resetPwd"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.delete')" placement="top">
                            <el-button size="small" type="text" @click="deleteUser(scope.$index, scope.row)" v-permission-code="'001001007_BTN'" v-if="userId != scope.row.userId">
                                <i class="el-icon-ajm-delete"></i>
                            </el-button>
                        </el-tooltip>
                        <el-tooltip :content="$t('message.UserBaseMain.UnLock')" placement="top">
                            <el-button size="small" type="text" @click="unlockUser(scope.$index, scope.row)" v-if="scope.row.locked">
                                <i class="el-icon-ajm-verify"></i>
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div class="ajm-pagination-bar">
            <el-pagination background @current-change="changePage" @size-change="handleSizeChange" :current-page="pageResult.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="pageResult.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageResult.total" />
        </div>
        <!--用户信息弹窗-->
        <el-dialog custom-class="ajm-dialog-middle" width="45%" top="0" :title="dialogTitle" :visible.sync="editUserFormVisible" :modal-append-to-body="false" :before-close="closeUserDialog" :close-on-click-modal="false">
            <el-form class="ajm-form" :model="editForm" ref="editForm" :rules="editFormRules" label-width="90px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.userName')" prop="userName">
                            <el-input auto-complete="off" :maxlength="20" v-model="editForm.userName" :placeholder="$t('message.UserInfo.confirmUserName')" :disabled="isEditAdd == true"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.realName')" prop="realName">
                            <el-input auto-complete="off" :maxlength="50" v-model="editForm.realName" :placeholder="$t('message.UserInfo.confirmRealName')"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="$t('message.Manager.department')" required>
                            <el-popover popperClass="departTree" ref="popover4" placement="bottom-start" width="260" trigger="click">
                                <el-tree ref="departmentTree" :data="departmentNodes" :props="departmentTreeProps" v-loading="departLoading" node-key="departmentId" @current-change="checkNode">
                                </el-tree>
                            </el-popover>
                            <el-button v-popover:popover4 class="select-btn ellipsis" style="width:100%;max-width:260px;height:32px;text-align:left;">
                                {{editForm.departmentName}}</el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.sex')">
                            <el-select :placeholder="$t('message.UserInfo.chooseSex')" v-model="editForm.sex.value">
                                <el-option v-for="item in sexList" :key="item.name" :label="item.name" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.email')" prop="email">
                            <el-input auto-complete="off" v-model="editForm.email" :placeholder="$t('message.UserInfo.confirmEmail')" :maxlength="50"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.phone')" prop="mobilephone">
                            <el-input auto-complete="off" v-model="editForm.mobilephone" :placeholder="$t('message.UserInfo.confirmPhone')" :maxlength="11"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="$t('message.Table.remark')" prop="remark">
                            <el-input type="textarea" :rows="4" :maxlength="200" style="width:100%;max-width:260px;" v-model="editForm.remark">
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserBaseMain.data')" prop="" required>
                            <el-radio-group v-model="showDatePickTime">
                                <el-radio label="1">{{$t('message.UserBaseMain.noLimit')}}</el-radio>
                                <el-radio label="2">{{$t('message.UserBaseMain.custom')}}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item :label="$t('message.UserBaseMain.dataRange')" required v-show="showDatePickTime == 2">
                        <el-col :span="12">
                            <el-form-item>
                                <el-date-picker v-model="validDates" type="daterange" range-separator=" - " format="yyyy-MM-dd" :editable="false"
                                                :clearable="false" :picker-options="pickerOptions1" :placeholder="$t('message.UserBaseMain.chooseDataRange')" align="left">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserBaseMain.userStatus')" required>
                            <el-switch v-model="editForm.status" active-value="1" :active-text="$t('message.Table.Enabled')"
                                       inactive-value="2" :inactive-text="$t('message.Table.Unabled')" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row>
                     &lt;!&ndash;<el-col :span="2">
                         <el-form-item label="所属角色"></el-form-item>
                     </el-col>&ndash;&gt;
                     <el-col :span="24">
                         <div class="margin-left">
                             <el-transfer filterable filter-placeholder="请输入关键词查询" :titles="roleTitles" v-model="editForm.roleIds" :data="roleList">
                             </el-transfer>
                         </div>
                     </el-col>
                 </el-row>-->
            </el-form>
            <div class="transfer-panel">
                <el-transfer filterable :filter-placeholder="$t('message.UserBaseMain.conClue')" :titles="roleTitles" v-model="editForm.roleIds" :data="roleList">
                </el-transfer>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" :loading="saveUserLoading" @click="saveOrUpdateUser('editForm')">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="editUserFormVisible = false">{{$t('message.cancel')}}</el-button>
            </div>
        </el-dialog>
        <!--账号密码-->
        <transition name="dialog-fade-top">
            <el-dialog custom-class="ajm-dialog-small ajm-dialog-padding" size="tiny" :visible.sync="passwordVisible" title="账号密码" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false">
                <img :src="successImg">
                <div style="padding-left: 60px;margin-top: -35px;">
                    <div style="font-size: 16px;color: #45494c;">
                        账号  <span style="color: #0576e8;"> {{passwordUserName}} </span> 已创建成功!
                    </div>
                    <!--
                    <h2 style="font-size: 16px;color: #45494c;">{{$t('message.UserBaseMain.createdSuccess')}}</h2>
                    <span style="color: #72767a;">
                        <span> {{passwordUserName}} </span>{{$t('message.UserBaseMain.pwdClue')}}</span>
                    <div style="text-align:center;margin-left:20px;display: inline-block;color:#13CE66;">
                        {{password}}
                        <el-button style="border: 1px solid #c4c4c4;padding: 10px 15px;margin-left: 20px" type="text" v-clipboard:message="password" v-clipboard:success="onCopy" v-clipboard:error="onError">{{$t('message.UserBaseMain.copyPwd')}}</el-button>
                    </div>
                    -->
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" size="small" @click="passwordVisible=false">{{$t('message.confirm')}}</el-button>
                </div>
            </el-dialog>
        </transition>
        <!--重置密码-->
        <transition name="dialog-fade-top">
            <el-dialog custom-class="ajm-dialog-smaller" size="tiny" :visible.sync="resetPasswordVisible" :title="$t('message.UserBaseMain.resetPwd')" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false">
               <!-- <div v-loading="resetLoading">
                    <h2 v-show="sureResetPassword" style="font-size: 14px">
                        <img :src="warnImg" style="vertical-align: middle;padding-right: 10px;">
                        &lt;!&ndash;2020-5-20 20:18:16 发布需要暂时不处理中英文的&ndash;&gt;
                        <span>是否确认重置账号 {{resetName}} 的密码？</span>
                        &lt;!&ndash;<span>
                            <span> {{resetName}} </span>{{$t('message.UserBaseMain.confirmResetPsw')}}
                        </span>&ndash;&gt;
                    </h2>
                    <h2 v-show="!sureResetPassword" style="font-size: 16px;margin-top: -20px;">
                        账号  <span style="color: #0576e8;"> {{resetName}} </span> 的密码已重置成功!
                    </h2>
                </div>-->
                <el-form :model="pwdForm" :rules="pwdRules" ref="pwdForm" label-width="130px">
                    <el-form-item :label="$t('message.UserInfo.newPwd')" prop="password">
                        <el-input type="password" v-model="pwdForm.password" :placeholder="$t('message.UserInfo.confirmPwdRule')" :maxlength="32" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('message.UserInfo.ensurePwd')" prop="confirmPassword">
                        <el-input type="password" v-model="pwdForm.confirmPassword" :placeholder="$t('message.UserInfo.confirmPwd')" :maxlength="32" auto-complete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" size="small" :loading="resetLoading" @click="resetPasswordDialog('pwdForm')">{{$t('message.confirm')}}</el-button>
                    <el-button size="small" @click="resetPasswordVisible=false">{{$t('message.cancel')}}</el-button>
                </div>
            </el-dialog>
        </transition>
    </div>

</template>

<script>
    //基础平台用户服务
    import userService from "../services/userService";
    //用户服务
    import userInfoService from "../services/userInfoService";
    //角色服务
    import roleService from "../services/roleService";
    //公司服务
    import companyService from "../services/companyService";
    //图片
    import successImg from '../images/success.png';
    import warnImg from '../images/warn.png';

    export default {
        data() {
            return {
                // 修改密码表单
                pwdForm: {
                    password: "",
                    confirmPassword: "",
                },
                pickerOptions1: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7
                    }
                },
                successImg: successImg,
                warnImg: warnImg,
                statusUser: [{ text: this.$t('message.Table.Enabled'), value: 1 }, { text: this.$t('message.Table.Unabled'), value: 2 }],
                isSearch: false,
                isReload: false,
                userId: '',
                departmentTreeProps: {
                    //部门数据模板
                    label: "departmentName",
                    children: "childDepartments",
                },
                listLoading: false,
                departLoading: false,
                departmentNodes: [],
                //弹窗名称
                dialogTitle:'',
                editUserFormVisible: false,
                password: "", //新建账号生成密码
                rePassword: "", //重置生成的密码
                passwordUserName: "",
                sureResetPassword: true,
                resetLoading: false,
                saveUserLoading: false,
                sureBtnFunction: 1,
                //分页结果集
                pageResult: {
                    pageNum: 1,
                    pageSize: 10,
                    total: 0,
                    list: []
                },
                passwordVisible: false, //密码框
                resetPasswordVisible: false, //重置密码框
                resetId: "",
                resetName: "",
                //判断是编辑还是新增
                isEditAdd: false,
                // 查询表单
                searchForm: {
                    userName: "",
                    realName: ""
                },
                //编辑新增表单
                validDates: [],
                //使用期限
                showDatePickTime: 1,
                sexList: [
                    {
                        name: this.$t('message.UserInfo.man'),
                        value: 1
                    },
                    {
                        name: this.$t('message.UserInfo.woman'),
                        value: 2
                    }
                ],
                editForm: {
                    userCode: "",
                    //用户id
                    userId: "",
                    // 用户名称
                    userName: "",
                    //姓名
                    realName: "",
                    //部门
                    departmentId: "",
                    departmentName: "",
                    companyId: "",
                    sex: {
                        name: this.$t('message.UserInfo.man'),
                        value: 1
                    },
                    mobilephone: "",
                    email: "",
                    roleIds: [],
                    status: {
                        name: "",
                        value: ""
                    },
                    remark:'',
                    validStartDate: "",
                    validEndDate: ""
                },
                defaultCompanyId: "",
                defaultDepartmentName: "",
                defaultDepartmentId: "",
                /*editFormRules: {
                    userName: [
                        {required:true, validator: checkUserName,  trigger: "blur" }
                    ],
                    realName: [
                        {required:true, validator: checkRealName, trigger: "blur" }
                    ],
                    email: [
                        {required:true, validator: checkEmail, trigger: "blur" }
                    ],
                    mobilephone: [
                        { validator: checkMobilephone, trigger: "blur" }
                    ]
                },*/
                //角色标题
                roleTitles: [this.$t('message.UserBaseMain.roleList'), this.$t('message.UserBaseMain.checkedRole')],
                // 角色列表
                roleList: [],
                // 部门集合
                departMent: [],
                permissionCode: this.$store.getters.userInfo.permissionCode,
                status: '',
                sortType: 2
            };
        },
        computed:{
            editFormRules() {
                var checkUserName = (rule, value, callback) => {
                    var userId = this.editForm.userId;
                    if (userId) {
                        return callback();
                    }
                    if (!value) {
                        return callback(new Error(this.$t('message.UserInfo.confirmUserName')));
                    }
                    var reg = /^[a-zA-Z0-9]{4,20}$/;
                    if (reg.test(value)) {
                        userService.checkUserName(value).then(resp => {
                            var result = resp;
                            if (result) {
                                callback();
                            } else {
                                return callback(new Error(this.$t('message.UserInfo.hasUserName')));
                            }
                        });
                    } else {
                        callback(new Error(this.$t('message.UserInfo.userNameClue')));
                    }
                };
                var checkRealName = (rule, value, callback) => {
                    if (!value) {
                        callback(new Error(this.$t('message.UserInfo.confirmRealName')));
                    } else {
                        callback();
                    }
                };
                var checkEmail = (rule, value, callback) => {
                    if (!value) {
                        callback(new Error(this.$t('message.UserInfo.confirmEmail')));
                    } else if (! /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/.test(value)) {
                        callback(new Error(this.$t('message.UserInfo.checkEmail')));
                    } else {
                        callback();
                    }
                };
                var checkMobilephone = (rule, value, callback) => {
                    if (! /^$|^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/.test(value)) {
                        callback(new Error(this.$t('message.UserInfo.checkPhone')));
                    } else {
                        callback();
                    }
                };
                return{
                    userName: [
                        {required:true, validator: checkUserName,  trigger: "blur" }
                    ],
                    realName: [
                        {required:true, validator: checkRealName, trigger: "blur" }
                    ],
                    email: [
                        {required:true, validator: checkEmail, trigger: "blur" }
                    ],
                    mobilephone: [
                        { validator: checkMobilephone, trigger: "blur" }
                    ]
                }
            },

            pwdRules(){
                var newPwdFunc = (rule, value, callback) => {
                    var reg = /^[a-zA-Z0-9]{8,32}$/;
                    if (value === "") {
                        callback(new Error(this.$t('message.UserInfo.confirmNewPwd')));
                    } else if (!reg.test(value)) {
                        callback(new Error(this.$t('message.UserInfo.confirmPwdRule')));
                    }  else {
                        if (this.pwdForm.confirmPassword !== "") {
                            this.$refs.pwdForm.validateField("confirmPassword");
                        }
                        callback();
                    }
                };
                var confirmPwdFunc = (rule, value, callback) => {
                    if (value === "") {
                        callback(new Error(this.$t('message.UserInfo.confirmPswAgain')));
                    } else if (value !== this.pwdForm.password) {
                        callback(new Error(this.$t('message.UserInfo.checkConfirmPassword')));
                    } else {
                        callback();
                    }
                };
                return{
                    // 新密码
                    password: [
                        { required: true, validator: newPwdFunc, trigger: "blur" }
                    ],
                    // 确认密码
                    confirmPassword: [
                        {
                            required: true,
                            validator: confirmPwdFunc,
                            trigger: "blur"
                        }
                    ],
                }
            },
        },
        methods: {
            //获取当前系统用户
            getUserId() {
                let userInfo = this.$store.getters.userInfo;
                if (userInfo) {
                    this.userId = userInfo.userId;
                }
            },
            //格式化是否锁定
            formatterLocked(row, column) {
                if (row.locked === true) {
                    return this.$t('message.UserBaseMain.hasLocked')
                } else {
                    return this.$t('message.UserBaseMain.unLocked')
                }

            },
            //格式化使用期限
            formatterExpired(row, column) {
                if (row.expired === true) {
                    return this.$t('message.UserBaseMain.invalid')
                } else {
                    return this.$t('message.UserBaseMain.valid')
                }
            },
            //时间排序
            handleSortChange(column, prop, order) {
                if (column.order === "ascending") {
                    this.sortType = 1;
                } else if (column.order === "descending") {
                    this.sortType = 2;
                }
                this.findUserInfoListByPage();
            },
            //筛选用户状态
            handleFilterChange(filters) {
                this.status = filters.status[0];
                this.findUserInfoListByPage();
            },
            //关闭用户表单弹窗
            closeUserDialog(done) {
                done();
                this.$refs.editForm.resetFields();
            },
            //确认用户所属部门
            checkNode(data) {
                this.editForm.companyId = data.companyId;
                this.editForm.departmentId = data.departmentId;
                this.editForm.departmentName = data.departmentName;

                this.departmentNodes.forEach(item => {
                    if (this.editForm.departmentName == item.departmentName) {
                        this.editForm.departmentName = '';
                    }
                })
            },
            //获取用户有效期
            handleValidDate(list) {
                var sts = list.validStartDate.split(" ");
                var sts1 = list.validEndDate.split(" ");

                list.validStartDate = sts[0];
                list.validEndDate = sts1[0];
            },
            //加载公司部门树
            findAllCompanyAndDepartments() {
                this.departLoading = true;
                companyService.findAllCompanyAndDepartments().then(resp => {
                    if (resp && resp.length > 0) {
                        if (resp[0].childDepartments[0]) {
                            this.defaultCompanyId = resp[0].childDepartments[0].companyId;
                            this.defaultDepartmentName = resp[0].childDepartments[0].departmentName;
                            this.defaultDepartmentId = resp[0].childDepartments[0].departmentId;
                        }
                        let departmentNodes = resp;

                        this.departmentNodes = [];
                        this.departmentNodes = departmentNodes.map(item => ({
                            childDepartments: item.childDepartments,
                            companyId: item.companyId,
                            departmentCode: item.departmentCode,
                            departmentId: item.departmentId,
                            departmentMaster: item.departmentMaster,
                            departmentName: item.departmentName,
                            parentDepartmentId: item.parentDepartmentId,
                            disabled: true
                        }))
                    }
                    this.departLoading = false;
                });
            },
            //查询用户分页列表
            findUserInfoListByPage(isSearch) {
                let params = {
                    page: this.pageResult.pageNum,
                    rows: this.pageResult.pageSize,
                    userName: this.searchForm.userName,
                    realName: this.searchForm.realName,
                    status: {
                        value: this.status
                    },
                    sortType: this.sortType
                };
                this.listLoading = true;
                isSearch = !!isSearch;

                userInfoService.findUserInfoListByPage(params).then(resp => {
                    this.pageResult = resp.data || resp;
                    var list = this.pageResult.list;
                    /* for (var i = 0; i < list.length; i++) {
                         if (typeof (list[i].validStartDate) == "undefined" || typeof (list[i].validEndDate) == "undefined") {
                             list[i].validDate = "未限制";
                         } else {
                             this.handleValidDate(list[i]);
                             list[i].validDate = list[i].validStartDate + " 至 " + list[i].validEndDate;
                         }
                     }*/
                    this.listLoading = false;
                    this.isSearch = isSearch;
                    this.isReload = true;
                }).catch(() => {
                    this.listLoading = false;
                });
            },
            //切换页面
            changePage(page) {
                this.pageResult.pageNum = page;
                this.findUserInfoListByPage();
            },
            //依据页码数分页
            handleSizeChange(pageSize) {
                this.pageResult.pageSize = pageSize;
                this.findUserInfoListByPage();
            },
            //筛选状态
            filterStatus(value, row) {
                return row.status.value === value;
            },
            // 查询
            search() {
                this.pageResult.pageNum = 1;
                this.findUserInfoListByPage(true);
            },

            //刷新页面
            refreshSearch(){
                this.searchForm.userName = "";
                this.searchForm.realName = "";
                this.pageResult.pageNum = 1;
                this.pageResult.pageSize = 10;
                this.sortType = 2;
                if(this.status){
                    this.$refs.filterTable.clearFilter();
                    this.status = ''
                }
                this.findUserInfoListByPage();
            },
            //加载角色集合
            loadRoleList() {
                var data = [];
                roleService.findAllRoleList().then(resp => {
                    var roleList = resp.data || resp;

                    roleList.forEach((role, index) => {
                        data.push({
                            label: role.roleName,
                            key: role.roleId
                        });
                    });
                    this.roleList = data;
                });
            },
            //加载用户角色集合
            loadUserRoleList(userId) {
                var data = [];
                userService.findRoleListByUserId(userId).then(resp => {
                    var roleList = resp.data || resp;

                    roleList.forEach((role, index) => {
                        data.push(role.roleId);
                    });
                    this.editForm.roleIds = data;
                });
            },
            //添加用户
            addUser() {
                this.resetForm("editForm");
                this.dialogTitle = this.$t('message.UserBaseMain.addUser');
                this.isEditAdd = false;
                this.editForm.userName = "";
                this.editForm.userId = "";
                this.editForm.realName = "";
                this.editForm.remark = "";
                this.editForm.status = "1";
                this.editForm.sex.value = 1;
                this.editForm.mobilephone = "";
                this.editForm.email = "";
                this.editForm.companyId = this.defaultCompanyId;
                this.editForm.departmentId = this.defaultDepartmentId;
                this.editForm.departmentName = this.defaultDepartmentName;
                this.showDatePickTime = "1";
                this.editForm.roleIds = [];
                this.validDates = [];
                this.editUserFormVisible = true;
            },
            //编辑用户
            editUser(index, row) {
                this.resetForm("editForm");
                this.dialogTitle = this.$t('message.edit');
                this.saveUserLoading = false;
                this.editUserFormVisible = true;
                this.isEditAdd = true;
                this.editForm.userCode = row.permissionCode;
                this.editForm.userId = row.userId;
                this.editForm.userName = row.userName;
                this.editForm.realName = row.realName;
                this.editForm.remark = row.remark;
                this.editForm.companyId = row.companyId;
                this.editForm.departmentId = row.departmentId;
                this.editForm.status = row.status.value.toString();
                this.editForm.mobilephone = row.mobilephone;
                this.editForm.email = row.email;
                this.editForm.roleIds = row.roleIds;
                this.editForm.departmentName = row.departmentName;

                if (row.sex) {
                    this.editForm.sex.value = row.sex.value;
                }

                if (row.validStartDate || row.validEndDate) {
                    this.showDatePickTime = "2";
                } else {
                    this.showDatePickTime = "1";
                }
                this.validDates = [row.validStartDate, row.validEndDate];

                this.loadRoleList();
                this.loadUserRoleList(this.editForm.userId);
            },
            //删除用户
            deleteUser(index, row) {
                this.$confirm(this.$t('message.confirmRequest') + "[" + row.userName + "]？", this.$t('message.delClue'), {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText: this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: "warning"
                }).then(() => {
                    userService.deleteUserById(row.userId).then(res => {
                        if (res.status == 500) {
                            this.$message({
                                type: 'error',
                                message: res.message
                            })
                            return;
                        }else{
                            this.$message({
                                type: 'success',
                                message: this.$t('message.delSuccess')
                            })
                            this.findUserInfoListByPage();
                        }
                    });
                }).catch(() => { });
            },
            //解锁用户
            unlockUser(index,row){
                userInfoService.unlockUser(row.userId).then((resp) => {
                    if (resp.status == 500) {
                        this.$message({
                            type: 'error',
                            message: resp.message
                        })
                        return;
                    }
                    this.$message({
                        type: 'success',
                        message: this.$t('message.UserBaseMain.lockSuccess')
                    })
                    this.findUserInfoListByPage();
                })
            },
            //重置密码
            resetPassword(index, row) {
                this.pwdForm.password = '';
                this.pwdForm.confirmPassword = '';
                this.resetLoading = false;
                this.resetForm("pwdForm");
                this.resetName = row.userName;
                this.resetId = row.userId;
                this.resetPasswordVisible = true;
                this.rePassword = "";
            },
            //重置密码弹窗
            resetPasswordDialog(formName) {
                let params = {
                    password: this.$md5(this.pwdForm.password),
                    confirmPassword: this.$md5(this.pwdForm.confirmPassword),
                    userId: this.resetId
                }
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.resetLoading = true;
                        userService.resetUserPwd(params).then(res => {
                            this.resetLoading = false;
                            if(res.status == 500){
                                this.$message({
                                    message: res.message,
                                    type: "error"
                                });
                            }else{
                                this.resetPasswordVisible = false;
                                this.resetLoading = false;
                                this.$message({
                                    message: this.$t('message.saveSuccess'),
                                    type: "success"
                                });
                            }
                        }).catch((err) =>{
                            this.$message.error("服务器繁忙，请稍后再试！");
                        });
                    }
                });
            },
            //复制密码
            onCopy(e) {
                this.$message({
                    showClose: true,
                    message: this.$t('message.UserBaseMain.hasCopyPwd'),
                    type: "success"
                });
            },
            onError(e) {
                // console.log(e);
            },
            //去除空格
            trim(val) {
                return val.replace(/(^\s*)|(\s*$)/g, "");
            },
            //保存用户信息
            saveOrUpdateUser(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        this.saveUserLoading = true;
                        if (this.editForm.departmentId < 0) {
                            this.$message({
                                type: 'warning',
                                message: this.$t('message.UserBaseMain.conDepartment')
                            })
                            this.saveUserLoading = false;
                            return;
                        }

                        var edit = JSON.parse(JSON.stringify(this.editForm));
                        if (this.showDatePickTime == 2) {
                            edit.validStartDate = this.formatDate(this.validDates[0]);
                            edit.validEndDate = this.formatDate(this.validDates[1]);
                            if (edit.validStartDate == "NaN-NaN-NaN" || edit.validEndDate == "NaN-NaN-NaN") {
                                this.$message({
                                    type: 'warning',
                                    message: this.$t('message.UserBaseMain.chooseData')
                                });

                                this.saveUserLoading = false;
                                return;
                            }
                        } else {
                            edit.validStartDate = null;
                            edit.validEndDate = null;
                        }
                        edit.status = {
                            value: parseInt(edit.status)
                        };
                        userInfoService.saveOrUpdateUser(edit).then(resp => {
                            this.saveUserLoading = false;
                            var result = resp.data || resp;
                            if (result.status == 500) {
                                this.$message({
                                    message: resp.message,
                                    type: "error"
                                });

                                return;
                            }
                            let message = '';
                            edit.userId == '' ? message = this.$t('message.UserBaseMain.addUserSuccess')
                                : message = this.$t('message.UserBaseMain.editUserSuccess');

                            this.$message({
                                message: message,
                                type: "success"
                            });

                            this.editUserFormVisible = false;
                            this.findUserInfoListByPage();
                            this.$refs.editForm.resetFields();

                            var _this = this;
                            if (result.password && result.password.length >= 0) {
                                setTimeout(function () {
                                    _this.password = result.password;
                                    _this.passwordUserName = result.userName;
                                    _this.passwordVisible = true;
                                }, 1000);
                            }
                        });
                    }
                });
            },
            //格式化时间
            formatDate(date) {
                var date = new Date(Date.parse(date));
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                var d = date.getDate();
                return y + "-" + m + "-" + d;
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName] !== undefined) {
                    this.$refs[formName].resetFields();
                }
            },
        },
        mounted() {
            this.findUserInfoListByPage();
            this.findAllCompanyAndDepartments();
            this.loadRoleList();
            this.getUserId();
            let self = this;
            document.getElementById("enterSearch").addEventListener("keydown", function (event) {
                if (event.keyCode === 13) {
                    self.search(event);
                }
            }, false);
        }
    };
</script>

<style lang="less" scoped>
    .margin-left {
        margin-left: 22px;
    }
    .el-dialog .el-form-item__content .el-button.select-btn {
        line-height: normal;
        padding-top: 5px;
    }
    .dialog-bottom {
        text-align: center;
        margin-top: 60px;
    }
    .el-tree-node__content span.el-tree-node__label {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 150px;
        margin-top: -3px;
        margin-left: -5px;
    }
    .departTree .el-tree {
        overflow: hidden;
        overflow-y: auto;
        max-height: 300px;
    }
</style>
