<template>
    <div class="app-container">
        <!-- <div>
            <el-form :inline="true" :model="formSearch" ref="ruleForm" class="demo-form-inline">
                <el-form-item label="用户名:">
                    <el-input v-model="formSearch.account" size="mini" placeholder="请输入用户名" clearable maxlength="50"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="mini" icon="el-icon-search" @click="search">查询</el-button>
                </el-form-item>
                <el-form-item class="float-right">
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="addUserDialog">新增</el-button>
                </el-form-item>
            </el-form>
        </div> -->
        <el-table :data="tableData" style="width: 100%" header-row-class-name="">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="account" label="用户名"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="联系电话"></el-table-column>
            
            <el-table-column prop="enIdText" label="用户级别"></el-table-column>
            <el-table-column prop="enIdText" label="操作时间"></el-table-column>
            <el-table-column prop="enIdText" label="操作人"></el-table-column>
            <!-- <el-table-column label="状态" width="100">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="1"
                               :inactive-value="0" @change="openOrClose(scope.row)"></el-switch>
                </template>
            </el-table-column> -->
            <el-table-column label="操作" width="200">
                <template slot-scope="scope">
                    <!-- <el-button type="text" size="small" @click="editUser(scope.row.id)"><i class="el-icon-edit"></i>修改</el-button>
                    <el-button type="text" size="small" @click="deleteUser(scope.row.id)"><i class="el-icon-delete"></i>移除</el-button> -->
                    <el-button type="text" size="small" @click="resetPassDialog(scope.row)"><i class="el-icon-delete"></i>重置密码</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total,  prev, pager, next, sizes, jumper"
            :total="total">
        </el-pagination>
        <el-dialog :title="isEdit == true ?'修改':'新增'" :visible.sync="dialogAddUserVisible" width="850px">
            <el-form :model="form" :rules="rules" ref="ruleForm">
                <el-row>
                    <el-col :span="12" style="padding-right:30px;">
                        <el-form-item label="用户名：" :label-width="formLabelWidth" prop="account">
                            <el-input type="text" v-if="!isEdit" v-model="form.account" auto-complete="new-password"
                                      placeholder="请输入用户名（必填）"></el-input>
                            <span v-else>{{ form.account }}</span>
                        </el-form-item>
                        <el-form-item v-if="!isEdit" label="密码：" :label-width="formLabelWidth" prop="password">
                            <el-input type="password" v-model="form.password" auto-complete="new-password" placeholder="请输入密码（必填）"></el-input>
                        </el-form-item>
                        <el-form-item v-if="!isEdit" label="确认密码：" :label-width="formLabelWidth" prop="again">
                            <el-input type="password" v-model="form.again" autocomplete="off" placeholder="请再次输入密码（必填）"></el-input>
                        </el-form-item>
                        <el-form-item label="所属企业：" :label-width="formLabelWidth" prop="enId">
                            <el-select v-model="form.enId" placeholder="请选择所属企业">
                                <el-option v-for="(item,index) in companyList" :key="index" :label="item.name" :value="parseInt(item.id)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" style="padding-right:30px;">
                        <el-form-item label="姓名：" :label-width="formLabelWidth" prop="name">
                            <el-input v-model="form.name" autocomplete="off" placeholder="请输入姓名（必填）"></el-input>
                        </el-form-item>
                        <el-form-item label="电话：" :label-width="formLabelWidth" prop="phone">
                            <el-input v-model.number="form.phone" autocomplete="off" minlength="11" maxlength="11"
                                      placeholder="请输入电话号码（必填）"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱：" :label-width="formLabelWidth" prop="email">
                            <el-input v-model="form.email" autocomplete="off" placeholder="请输入邮箱（必填）"></el-input>
                        </el-form-item>
                        <el-form-item label="身份证件类型：" :label-width="formLabelWidth" prop="typeId">
                            <el-select v-model="form.typeId" placeholder="请选择性别（必填）">
                                <el-option label="中国居民身份证" :value="1"></el-option>
                                <el-option label="港澳居民往来内地通行证" :value="2"></el-option>
                                <el-option label="台湾居民往来大陆通行证" :value="3"></el-option>
                                <el-option label="外国人永久居留身份证" :value="4"></el-option>
                                <el-option label="港澳台居民居住证" :value="5"></el-option>
                                <el-option label="护照" :value="6"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="身份证件号码：" :label-width="formLabelWidth" prop="idNumber">
                            <el-input v-model="form.idNumber" autocomplete="off" placeholder="请输入身份证件号码（必填）"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" size="mini" @click="submitForm('ruleForm')">保存</el-button>
                <el-button type="info" size="mini" @click="resetForm('ruleForm')">重置</el-button>
            </div>
        </el-dialog>
        <el-dialog title="重置密码" :visible.sync="dialogResetPass" width="500px">
        <el-form :model="formPass" :rules="rulesPass" ref="passForm">
            <el-form-item label="用户名：" :label-width="formLabelWidth">
            <span>{{ formPass.account }}</span>
            </el-form-item>
            <el-form-item label="密码：" :label-width="formLabelWidth" prop="password">
            <el-input type="password" v-model="formPass.password" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitForm('passForm')">保存</el-button>
            <el-button type="info" size="mini" @click="resetForm('passForm'),dialogResetPass = false">取消</el-button>
        </div>
        </el-dialog>
    </div>
</template>
<script>
import {
    getUserList, getUserDetail, editUserStatus,
    addUser, deleteUser, resetPass,
    updateUserInfo, getAddRole, existsUserName
} from "@/api/user"
import {validateEmail, validatePhone, validateIDCard, validateChinese} from "@/utils/validate"
import { getEnterpriseList } from "@/api/company"
export default {
    name: "userManage",
    data() {
        const checkAgainPassword = (rule, value, callback) => {
            if (value != this.form.password) {
                return callback(new Error('两次输入密码不一致'));
            } else {
                callback()
            }
        };
        const checkIsUserdUser = (rule, value, callback) => {
            if (validateChinese(value)) {
                return callback(new Error('用户名不可为中文'));
            } else {
                if (!this.isEdit) {
                    existsUserName({account: this.form.account}).then(res => {
                        callback()
                    }).catch(err => {
                        return callback(new Error(err.message));
                    })
                } else {
                    callback()
                }
            }
        };
        const checkPhone = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('手机号不能为空'));
            } else {
                if (validatePhone(value)) {
                    callback();
                } else {
                    return callback(new Error('请输入正确的手机号'));
                }
            }
        }
        const checkEmail = (rule, value, callback) => {
            if (!validateEmail(value)) {
                return callback(new Error('请输入正确格式的Email'));
            } else {
                callback();
            }
        }
        const checkIDNum = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入身份证件号码'));
            } else if (this.form.typeId == 1 && !validateIDCard(value)) {
                return callback(new Error('请输入正确格式的身份证件号码'));
            } else {
                callback();
            }
        }

        return {
            isEdit: false,                       //添加 or 修改标记
            formSearch: {//模糊搜索
                account: ''
            },
            currentPage: 1,                      //当前页
            pageSize: 10,                        //每页条数
            total: 0,                            //总条数
            dialogAddUserVisible: false,         //添加修改的Dialog
            dialogResetPass: false,              //重置密码的Dialog
            formLabelWidth: '130px',             //form的lable的宽带
            form: {                              //添加修改的form
                account: '',
                name: '',
                phone: '',
                typeId: '',
                idNumber: '',
                password: '',
                email: '',
                again: '',
                enId:'',
                status:'1'
                //enName: '',
                //goId: '',
                //enCode: '',
            },
            formPass: {                          //重置密码的form
                id: '',
                password: '',
                version: '',
                account: '',
            },
            rules: {                            //添加修改的校验规则
                account: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {validator: checkIsUserdUser, trigger: 'blur'}
                ],
                enId: [
                    {required: true, message: '请选择所属企业', trigger: 'change'}
                ],
                name: [
                    {required: true, message: '请输入姓名', trigger: 'blur'},
                    {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
                ],
                phone: [
                    {required: true, validator: checkPhone, trigger: 'blur'}
                ],
                email: [
                    {required: true, message: '请填写邮箱', trigger: 'blur'},
                    {validator: checkEmail, trigger: 'blur'}
                ],
                typeId: [
                    {required: true, message: '请选择身份证件类型', trigger: 'change'}
                ],
                idNumber: [
                    {required: true, message: '请输入身份证件号码', trigger: 'blur'},
                    {validator: checkIDNum, trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入新密码', trigger: 'blur'},
                    {min: 8, max: 12, message: '长度在 8 到 12 个字符', trigger: 'blur'}
                ],
                
                again: [
                    {required: true, message: '请再次输入新密码', trigger: 'blur'},
                    {validator: checkAgainPassword, trigger: 'blur'}
                ],
            },
            rulesPass: {                         //重置密码的校验规则
                password: [
                    {required: true, message: '请输入新密码', trigger: 'blur'},
                    {min: 8, max: 12, message: '长度在 8 到 12 个字符', trigger: 'blur'}
                ],
            },
            tableData: [],                      //表格数据
            companyList:[]
        };
    },
    mounted() {
        this.initData()
    },
    methods: {
        //搜索查询
        search() {
            this.currentPage = 1
            this.initData()
        },
        //获取用户列表
        initData() {
            const params = {
                pageNum: this.currentPage,
                pageSize: this.pageSize,
                search:{
                    account: this.formSearch.account.trim()
                },
                sort:''
            }
            getUserList(params).then(res => {
                this.tableData = res.data.list
                this.total = res.data.count
            })
        },
        //获取企业下拉列表
        getCompanyList(){
            const params = {
                pageNum: 1,
                pageSize: 1000,
                search:{
                    name: this.form.enId
                },
                sort:''
            }
            getEnterpriseList(params).then(res => {
                if (res.data) {
                    this.companyList = res.data.list
                }
            })
        },
        //状态启用、停用
        openOrClose(row) {
            const param = {
                flag: row.status,
                id: row.id
            }
            editUserStatus(param).then(res => {
                this.$message({
                    message: '修改成功！',
                    type: 'success'
                });
            }).catch((err) => {
                row.status === 0 ? row.status = 1 : 0
            })
        },
        //打开重置密码dialog
        resetPassDialog(row) {
            this.formPass.account = row.account;
            this.formPass.password = '';
            this.formPass.id = row.id;
            this.formPass.version = row.version;
            this.dialogResetPass = true
        },
        //重置密码保存
        resetPassword() {
            let params = JSON.parse(JSON.stringify(this.formPass)) 
            params.password = this.$md5(params.password)
            resetPass(params).then(res => {
                this.$message({
                    message: '密码重置成功！',
                    type: 'success'
                });
                this.dialogResetPass = false
            })
        },
        //打开添加.修改用户dialog
        addUserDialog() {
            this.isEdit = false
            // this.form = {}
            if(this.companyList.length == 0)
            {
                this.getCompanyList()
            }
            this.dialogAddUserVisible = true
        },
        //添加用户信息
        addUserInfo() {
            let params = JSON.parse(JSON.stringify(this.form)) 
            params.password = this.$md5(params.password)
            delete(params.again)
            addUser(params).then(res => {
                this.$message({
                    message: res.message,
                    type: res.status == 200 ? 'success' : 'error'
                });
                this.resetForm('ruleForm')
                this.dialogAddUserVisible = false
                this.initData()
            })
        },
        //删除用户
        deleteUser(id) {
            this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteUser([id]).then(res => {
                    this.$message({
                        message: '删除成功！',
                        type: 'success'
                    });
                    this.initData()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });

        },
        //获取用户详细信息
        editUser(id) {
            this.isEdit = true
            if(this.companyList.length == 0)
            {
                this.getCompanyList()
            }
            // this.form = {}
            this.dialogAddUserVisible = true
            getUserDetail(id).then(res => {
                // this.form = {//添加修改的form
                //     id: res.data.id,
                //     account: res.data.account,
                //     name: res.data.realName,
                //     phone: res.data.phone,
                //     typeId: res.data.typeId,
                //     idNumber: res.data.idNumber,
                //     email: res.data.email
                // }
                this.form = res.data
            })
        },
        //更新用户信息
        updateUserData() {
            updateUserInfo(this.form).then(res => {
                this.$message({
                    message: res.message,
                    type: res.status == 200 ? 'success' : 'error'
                });
                this.dialogAddUserVisible = false
                this.initData()
            })
        },
        //form提交检验
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (formName == 'passForm') {
                        this.resetPassword()
                    } else if (formName == 'ruleForm') {
                        if (this.isEdit) {
                            this.updateUserData()
                        } else {
                            this.addUserInfo()
                        }
                    }

                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //form重置
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        //每页条数变化
        handleSizeChange(val) {
            this.pageSize = val
            this.initData()
        },
        //当前页变化
        handleCurrentChange(val) {
            this.currentPage = val
            this.initData()
        }

    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.input-with-select {
    float: left;
    top: 10px;
}

.el-input {
    width: 230px;
}
</style>
