<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">{{$t('message.add')}}</el-button>
                            <el-button icon="el-icon-delete" @click="batchDeleteUser">{{$t('message.delete')}}</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">
            <el-table ref="filterTable" :data="pageResult.list"
                      @selection-change="selectChange"
                      v-loading="listLoading"
                      @sort-change="handleSortChange"
                      @filter-change="handleFilterChange"
                      tooltip-effect="light">
                <el-table-column prop="roleId" type="selection" width="55"></el-table-column>
                <el-table-column type="index" :label="$t('message.Table.index')" width="70" />
                <el-table-column prop="userName" :label="$t('message.UserInfo.userName')" />
                <el-table-column prop="mobilephone" :label="$t('message.UserInfo.phone')" width="120" />
                <el-table-column prop="realName" :label="$t('message.UserInfo.realName')" :show-overflow-tooltip="true" min-width="120"/>
                <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="sex.name" :label="$t('message.UserInfo.sex')" :filters="statusSex" :filter-multiple="false" column-key="sex" :filter-method="filterSexStatus" width="70" />
                <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="remark" :label="$t('message.Table.remark')"  :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)">
                               <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-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">
            </el-pagination>
        </div>
        <el-dialog :title="dialogTitle" style="z-index:1999" custom-class="ajm-dialog-middle" :visible.sync="userFormVisible" width="45%" top="0" :modal-append-to-body="false" :close-on-click-modal="false">
            <el-form class="ajm-form" :model="editForm" ref="editForm" :rules="editFormRules" label-width="80px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.userName')" prop="userName">
                            <el-input auto-complete="off" v-model="editForm.userName" :placeholder="$t('message.UserInfo.confirmUserName')" :disabled="(editForm.userId == '') == false"></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" v-model="editForm.realName" :placeholder="$t('message.UserInfo.confirmRealName')" :maxlength="20"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.pwd')" prop="password">
                            <el-input auto-complete="off" v-on:change="change" v-model="editForm.password" :placeholder="$t('message.UserInfo.confirmPsw')" type="password" :maxlength="32"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('message.UserInfo.ensurePwd')" prop="confirmPassword">
                            <el-input auto-complete="off" v-model="editForm.confirmPassword" :placeholder="$t('message.UserInfo.confirmPswAgain')" type="password" :maxlength="32"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <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 :label="$t('message.UserInfo.man')" value="1"></el-option>
                                <el-option :label="$t('message.UserInfo.woman')" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <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-row>
                <el-row :gutter="20">
                    <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-col :span="12">
                        <el-form-item :label="$t('message.Table.remark')" prop="remark">
                            <el-input auto-complete="off" :rows="4" type="textarea" style="max-width: 260px;" v-model="editForm.remark" :placeholder="$t('message.Table.confirmRemark')" :maxlength="200"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <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-form-item :label="$t('message.UserBaseMain.dataRange')" required v-show="showDatePickTime == 2">
                    <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-form-item :label="$t('message.UserBaseMain.userStatus')" prop="status" required>
                    <el-radio-group v-model="editForm.status">
                        <el-radio-button label="1">{{$t('message.Table.Enabled')}}</el-radio-button>
                        <el-radio-button label="2">{{$t('message.Table.Unabled')}}</el-radio-button>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div class="transfer-panel">
                <el-transfer :titles="roleTitles" v-model="editForm.roleIds" :data="roleList">
                </el-transfer>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="small" @click="saveOrUpdateUser('editForm')">{{$t('message.save')}}</el-button>
                <el-button size="small" @click="userFormVisible = false">{{$t('message.cancel')}}</el-button>
            </div>
        </el-dialog>
        <!--账号密码-->
        <transition name="dialog-fade-top">
            <el-dialog custom-class="ajm-dialog-smaller" size="tiny" :visible.sync="passwordVisible" :title="$t('message.UserBaseMain.password')" :show-close="false" :modal-append-to-body="false" :close-on-click-modal="false">
                <div style="padding: 5px 20px;">
                    <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>
                <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>
                    <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>
                    <!--<h2 v-show="sureResetPassword" style="font-size: 14px">
                        <img :src="warnImg" style="vertical-align: middle;padding-right: 10px;">
                        <span>是否确认重置账号 {{resetName}} 的密码？</span>
                    </h2>
                    <h2 v-show="!sureResetPassword" style="font-size: 16px;margin-top: -20px;">
                        账号  <span style="color: #0576e8;"> {{resetName}} </span> 的密码已重置成功!
                    </h2>-->

                </div>
                <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 roleService from "../services/roleService";
//图片
import successImg from '../images/success.png';
import warnImg from '../images/warn.png';

export default {
    data() {
        return {
            // 修改密码表单
            pwdForm: {
                password: "",
                confirmPassword: "",
            },
            //弹窗标题
            dialogTitle:'',
            statusUser: [{ text: this.$t('message.Table.Enabled'), value: 1 }, { text: this.$t('message.Table.Unabled'), value: 2 }],
            statusSex:[{ text: this.$t('message.UserInfo.man'), value: 1 }, { text: this.$t('message.UserInfo.woman'), value: 2 }],
            permissionCode:this.$store.getters.userInfo.permissionCode,
            // 列表加载
            listLoading: false,
            // 用户表单是否可见
            userFormVisible: false,
            //分页结果集
            pageResult: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
                list: []
            },
            // 查询表单
            searchForm: {
                // 用户名
                userName: "",
                // 手机号码
                mobilephone: "",
            },
            //编辑新增表单
            editForm: {
                //用戶状态
                status: "1",
                //用户id
                userId: "",
                // 用户名称
                userName: "",
                realName:"",
                remark:"",
                // 密码
                password: "",
                //确认密码
                confirmPassword: "",
                // 性别
                sex: {
                    value: 1,
                    name:this.$t('message.UserInfo.man')
                },
                // 手机号
                mobilephone: "",
                //邮箱
                email: "",
                //角色
                roleIds: [],
                validStartDate: "",
                validEndDate: ""
            },
            passwordValue:"",
            /*editFormRules: {
                userName: [{required:true, validator: checkUserName, trigger: "blur" }],
                realName:[{required:true,message:"请输入真实姓名"}],
                password: [{required:true, validator: checkPassword, trigger: "blur" }],
                confirmPassword: [
                    {required:true, validator: checkConfirmPassword, trigger: "blur" }
                ],
                mobilephone: [{ validator: checkMobilephone, trigger: "blur" }],
                email: [{required:true, validator: checkEmail,  trigger: "blur" }],
            },*/
            //角色标题
            roleTitles: [this.$t('message.UserBaseMain.roleList'), this.$t('message.UserBaseMain.checkedRole')],
            // 角色列表
            roleList: [],
            // 选中角色
            //selectedRoles: [],
            // 选中用户集合
            selectedUsers: [],
            // 选中用户ID集合
            selectedUserIds: [],
            status: '',
            sex:'',
            sortType:'',  //2019年5月28日09:20:21变更 默认先按启用排序

            //当前用户Id
            userId:this.$store.getters.userInfo.userId,
            //图片地址
            successImg: successImg,
            warnImg: warnImg,
            //是否显示密码框
            passwordVisible: false,
            //新建的账号名称
            passwordUserName: "",
            password: "", //新建账号生成密码

            //是否显示重置密码框
            resetPasswordVisible: false,
            //加载重置密码弹窗效果
            resetLoading: false,
            //是否确认重置密码信息
            sureResetPassword: true,
            rePassword: "", //重置生成的密码
            sureBtnFunction: 1,//确认按钮功能
            //重置账号的Id
            resetId: "",
            resetName: "",//重置的账号

            //是否显示期限
            showDatePickTime: 1,
            //使用期限
            validDates: [],
            pickerOptions1: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7
                }
            },
        };
    },
    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 checkPassword = (rule, value, callback) => {
                var userId = this.editForm.userId;
                if (userId && value === "") {
                    return callback();
                }
                if (value === "") {
                    callback(new Error(this.$t('message.UserInfo.confirmPsw')));
                } else {
                    var reg = /^[a-zA-Z0-9]{8,32}$/;
                    if (reg.test(value)) {
                        if (this.editForm.confirmPassword !== "") {
                            this.$refs.editForm.validateField("confirmPassword");
                        }
                        callback();
                    } else {
                        callback(new Error(this.$t('message.UserInfo.confirmPwdRule')));
                    }
                }
            };

            var checkConfirmPassword = (rule, value, callback) => {
                var userId = this.editForm.userId;
                if (userId && value === "" && this.editForm.password === "") {
                    return callback();
                }
                if (value === "") {
                    callback(new Error(this.$t('message.UserInfo.confirmPswAgain')));
                } else if (value !== this.editForm.password) {
                    callback(new Error(this.$t('message.UserInfo.checkConfirmPassword')));
                } else {
                    callback();
                }
            };

            var checkMobilephone = (rule, value, callback) => {
                if (value === "") {
                    callback();
                }
                var reg = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[0-8])|(18[0-9]))\d{8}$/;
                if (reg.test(value)) {
                    callback();
                } else {
                    callback(new Error(this.$t('message.UserInfo.checkPhone')));
                }
            };
            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();
                }
            };
            return{
                userName: [{required:true, validator: checkUserName, trigger: "blur" }],
                realName:[{required:true,message:this.$t('message.UserInfo.confirmPswAgain')}],
                password: [{required:true, validator: checkPassword, trigger: "blur" }],
                confirmPassword: [
                    {required:true, validator: checkConfirmPassword, trigger: "blur" }
                ],
                mobilephone: [{ validator: checkMobilephone, trigger: "blur" }],
                email: [{required:true, validator: checkEmail,  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: {
        //修改密码
        change(value){
            this.passwordValue = value;
        },
        //格式化是否锁定
        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')
            }
        },
        //解锁用户
        unlockUser(index,row){
            userService.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);
        },
        //查询用户分页列表
        findUserListByPage() {
            //查询用户列表
            var params = {
                page: this.pageResult.pageNum,
                rows: this.pageResult.pageSize,
                userNameLike: this.searchForm.userName,
                mobilephoneLike: this.searchForm.mobilephone,
                sex:{value:this.sex},
                status: {
                    value: this.status
                },
                sortType:this.sortType
            };
            this.listLoading = true;
            // 根据调节查询用户列表
            userService.findUserListByPage(params).then(resp => {
                this.pageResult = resp;
                this.listLoading = false;
            }).catch(() => {
                this.listLoading = false;
            });
        },
        //切换页面
        changePage(page) {
            this.pageResult.pageNum = page;
            this.findUserListByPage();
        },
        //依据页码数分页
        handleSizeChange(pageSize) {
            this.pageResult.pageSize = pageSize;
            this.findUserListByPage();
        },
        // 查询
        search() {
            this.pageResult.pageNum = 1
            this.findUserListByPage();
        },
        //刷新页面
        refreshSearch(){
            this.searchForm.userName = '';
            this.pageResult.pageNum = 1
            this.pageResult.pageSize = 10
            this.sortType = 2
            if(this.status || this.sex){
                this.$refs.filterTable.clearFilter();
                this.status = ''
                this.sex = ''
            }
            this.findUserListByPage();
        },
        // 加载角色集合
        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() {
            //重置editForm
            this.dialogTitle = this.$t('message.UserBaseMain.addUser');
            this.resetForm("editForm");
            this.editForm.userId = "";
            this.editForm.userName = "";
            this.editForm.password = "";
            this.editForm.confirmPassword = "";
            this.editForm.sex.value = "1";
            this.editForm.status = "1";
            this.editForm.mobilephone = "";
            this.showDatePickTime = "1";
            this.editForm.email = "";
            this.editForm.roleIds = [];
            this.validDates = [];
            this.userFormVisible = true;
            this.loadRoleList();
        },
        // 编辑用户
        editUser(index, row) {
            this.resetForm("editForm");
            this.dialogTitle = this.$t('message.edit');
            var userId = row.userId;
            this.editForm.userId = userId;
            this.editForm.userName = row.userName;
            this.editForm.realName = row.realName;
            this.editForm.password = "";
            this.editForm.confirmPassword = "";
            if(row.sex){
                this.editForm.sex.value = row.sex.value.toString();
            }
            if(row.status.value){
                this.editForm.status = row.status.value.toString();
            }

            this.editForm.mobilephone = row.mobilephone;
            this.editForm.email = row.email;
            this.editForm.roleIds = row.roleIds;
            this.userFormVisible = true;
            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'), 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 => {
                        this.tips(res);
                        this.findUserListByPage();
                    });
                })
                .catch(() => {});
        },
        //批量删除用户
        batchDeleteUser() {
            if (this.selectedUserIds.length > 0) {
                this.$confirm( this.$t('message.confirmBatch'),  this.$t('message.confirmDel'), {
                    cancelButtonClass:"message-cancel-button",
                    confirmButtonText:this.$t('message.confirm'),
                    cancelButtonText: this.$t('message.cancel'),
                    type: "warning"
                })
                    .then(() => {
                        userService
                            .batchDeleteUser(this.selectedUserIds)
                            .then(res => {
                                this.tips(res);
                                this.findUserListByPage();
                            });
                    })
                    .catch(() => {});
            } else {
                this.$message({
                    message: this.$t('message.UserBaseMain.chooseUser'),
                    type: "error",
                    duration: 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;
        },
        //保存账号信息
        saveOrUpdateUser(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if(this.editForm.userId == ''){
                        this.editForm.password = this.$md5(this.editForm.password);
                        this.editForm.confirmPassword = this.$md5(this.editForm.confirmPassword);
                        /* this.editForm.status = {
                            value:this.editForm.status
                        } */
                    }else if(this.editForm.userId != '' && !this.passwordValue){
                        this.editForm.password = null;
                        this.editForm.confirmPassword = null;
                        /* this.editForm.status = {
                            value:this.editForm.status
                        } */
                    }else{
                        this.editForm.password = this.$md5(this.passwordValue);
                        /* this.editForm.status = {
                            value:this.editForm.status
                        } */
                    }
					this.editForm.status = {
					    value:this.editForm.status
					}
                    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;
                    }
                    userService.saveOrUpdateUser(edit).then(resp => {
                        if(resp.status == 500){
                            this.$message({
                                message: resp.message,
                                type: "error"
                            });
                        }else{
                            this.$message({
                                message: this.$t('message.saveSuccess'),
                                type: "success"
                            });
                            this.userFormVisible = false;
                            this.findUserListByPage();

                            // var _this = this;
                            // if (resp.password && resp.password.length >= 0) {
                            //     setTimeout(function () {
                            //         _this.password = resp.password;
                            //         _this.passwordUserName = resp.userName;
                            //         _this.passwordVisible = true;
                            //     }, 1000);
                            // }
                        }
                    });
                }
            });
        },
        //提示信息
        tips(res) {
            var resp = res;
            var type = "success";
            var message = this.$t('message.delSuccess');
            if (resp.status == 500 || resp.data == 0) {
                type = "error";
                message = this.$t('message.delFailed');
            }
            //message = resp.message;
            this.$message({
                message: message,
                type: type,
                duration: 1500
            });
        },
        //选中行，获得值
        selectChange(val) {
            this.selectedUserIds = [];
            this.selectedUsers = val;
            var num = 0;
            var $this = this;
            this.selectedUsers.forEach(function(item) {
                $this.selectedUserIds[num] = item.userId;
                num++;
            });
        },
        resetForm(formName) { //重置表单
            if (this.$refs[formName] !== undefined) {
                this.$refs[formName].resetFields();
            }
        },
        handleFilterChange(filters) {
            if(filters.status){
                this.status = filters.status[0];
            }else if(filters.sex){
                this.sex = filters.sex[0];
            }
            this.pageResult.pageNum = 1
            this.findUserListByPage();
        },
        //筛选状态
        filterStatus(value, row) {
            return row.status.value === value;
        },
        //筛选性别
        filterSexStatus(value,row){
            if(row.sex){
                return row.sex.value === value;
            }
        },
        //时间排序
        handleSortChange(column, prop, order) {
            if (column.order === "ascending") {
                this.sortType = 1;
            } else if (column.order === "descending") {
                this.sortType = 2;
            }
            this.findUserListByPage();
        },
    },
    //初始化
    mounted() {
        //查询用户信息
        this.findUserListByPage();
        let self = this;
        document.getElementById("enterSearch").addEventListener("keydown", function (event) {
            if (event.keyCode === 13) {
                self.search(event);
            }
        }, false);
    }
};
</script>
