<template>
    <div class="pd10">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="用户状态:">
                <el-select
                    v-model="queryParams.searchState"
                    placeholder="选择用户状态"
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                >
                    <el-option
                        v-for="(item, index) in Statusoptions"
                        :label="item.label"
                        :key="index"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用户类型:">
                <el-select
                    v-model="queryParams.casualUser"
                    placeholder="选择用户类型"
                    size="small"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                >
                    <el-option
                        v-for="(item, index) in Typeoptions"
                        :label="item.label"
                        :key="index"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="筛选数据:">
                <el-input
                    v-model="queryParams.searchValue"
                    clearable
                    size="small"
                    style="width: 250px"
                    placeholder="筛选(仅根据用户名/登录名)"
                />
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="handleQuery">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button v-if="button.add" icon="el-icon-plus" type="primary" @click="handleAdd">新增用户</el-button>
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-refresh" type="primary" @click="handleReset">重置</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" class="el-icon-download" @click="exportExcel">导出</el-button>
            </el-form-item>
        </el-form>
        <el-table
            stripe
            v-loading="loading"
            :height="tableheight + 'px'"
            highlight-current-row
            element-loading-text="数据载入中"
            element-loading-spinner="el-icon-loading"
            header-cell-class-name="table_header"
            border
            @header-click="sort"
            @sort-change="sort_change"
            :data="pageList"
        >
            <el-table-column min-width="100" align="center" label="用户名称" prop="name" />
            <el-table-column min-width="120" align="center" label="登录名" prop="loginName" />
            <el-table-column
                min-width="160"
                align="center"
                label="角色"
                prop="role"
                :formatter="gName"
                width="180"
                :show-overflow-tooltip="true"
            />
            <el-table-column min-width="100" align="center" label="部门" prop="deptName" />
            <!-- sortable -->
            <el-table-column min-width="100" align="center" label="电话" prop="phone" />
            <el-table-column
                min-width="120"
                align="center"
                label="注册时间"
                prop="registerTime"
                :show-overflow-tooltip="true"
            >
                <!-- <template slot-scope="scope">{{
          scope.row.registerTime | formatDate
        }}</template> -->
            </el-table-column>
            <el-table-column
                min-width="130"
                align="center"
                label="登录时间"
                prop="loginTime"
                :show-overflow-tooltip="true"
            >
                <!-- <template slot-scope="scope">{{
          scope.row.loginTime | formatDate
        }}</template> -->
            </el-table-column>
            <el-table-column min-width="80" align="center" label="类型" prop="casualUser">
                <template slot-scope="scope">
                    <span v-if="scope.row.casualUser === 0" type="primary" size="small">临时用户</span>
                    <span v-if="scope.row.casualUser === 1" type="success" size="small">长期用户</span>
                </template>
            </el-table-column>

            <el-table-column min-width="80" align="center" label="状态" prop="state">
                <template slot-scope="scope">
                    <span v-if="scope.row.state === 0" type="primary" size="small">注销</span>
                    <span v-if="scope.row.state === 1" type="primary" size="small">正常</span>
                    <span v-if="scope.row.state === 2" type="primary" size="small">锁定</span>
                    <span v-if="scope.row.state === 3" type="primary" size="small">待审核</span>
                    <span v-if="scope.row.state === 4" type="primary" size="small">休眠</span>
                    <span v-if="scope.row.state === 5" type="primary" size="small">密码过期</span>
                </template>
            </el-table-column>

            <el-table-column align="center" label="操作" min-width="230">
                <template slot-scope="scope">
                    <el-button
                        v-if="scope.row.state == 1"
                        type="primary"
                        size="mini"
                        icon="el-icon-edit"
                        @click.stop="handleUpdate(scope.row)"
                    >
                        修改
                    </el-button>

                    <el-button
                        v-if="scope.row.state == 1"
                        type="primary"
                        size="mini"
                        icon="el-icon-edit-outline"
                        @click.stop="handleResetPassword(scope.row)"
                    >
                        修改密码
                    </el-button>
                    <el-button
                        v-if="
                            scope.row.state == 2 || scope.row.state == 5 || scope.row.state == 0 || scope.row.state == 4
                        "
                        type="primary"
                        icon="el-icon-finished"
                        size="mini"
                        @click.stop="handleUnlock(scope.row)"
                    >
                        激活
                    </el-button>
                    <el-button
                        v-if="scope.row.state == 1 || scope.row.state == 3"
                        type="danger"
                        size="mini"
                        icon="el-icon-delete"
                        @click.stop="handleDelete(scope.row)"
                    >
                        注销
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            v-show="page.total > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page.current"
            :page-sizes="[20, 25, 35, 40, 50]"
            :page-size="page.size"
            layout="total, sizes, prev, pager, next, jumper"
            align="right"
            class="mt10"
            background
            :total="page.total"
        ></el-pagination>
        <!-- 新增或修改删除密码确认对话框 -->
        <el-dialog
            :close-on-click-modal="false"
            title="修改密码"
            :visible.sync="dialogVisible1"
            width="30%"
            :before-close="closepw"
        >
            <el-form ref="passwordform" :model="passwordform" label-width="100px" :rules="rules2">
                <el-form-item label="校验密码:" prop="password">
                    <el-input v-model="passwordform.password" type="password" placeholder="请输入校验密码" />
                </el-form-item>
                <el-form-item label="新密码:" prop="newPwd" style="margin-top: 20px">
                    <el-input v-model="passwordform.newPwd" type="password" placeholder="请输入新密码" />
                </el-form-item>
                <el-form-item label="确认密码:" prop="confirmPwd" style="margin-top: 20px">
                    <el-input v-model="passwordform.confirmPwd" type="password" placeholder="请输入确认密码" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button text-align="center" @click="closepw">取 消</el-button>
                <el-button text-align="center" type="primary" @click="submint">确认</el-button>
            </span>
        </el-dialog>

        <el-dialog
            :close-on-click-modal="false"
            title="注销用户"
            :visible.sync="dialogVisible3"
            width="30%"
            :before-close="closepw"
        >
            <el-form ref="passwordform" :model="passwordform" label-width="120px" :rules="rules3">
                <el-form-item label="二次校验密码:" prop="password">
                    <el-input v-model="passwordform.password" type="password" placeholder="请输入二次校验密码" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button text-align="center" @click="closepw">取 消</el-button>
                <el-button text-align="center" type="primary" @click="submint">确认</el-button>
            </span>
        </el-dialog>
        <!-- 新增或修改参数配置对话框 -->
        <el-dialog
            :close-on-click-modal="false"
            :title="dialog.title"
            :visible.sync="dialogvisibleadd"
            width="800px"
            class="hjks"
            :before-close="closeDialog"
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户名:" prop="name">
                            <el-input v-model="form.name" placeholder="请输入昵称" />
                        </el-form-item>
                        <el-form-item label="登录名:" class="top" prop="loginName">
                            <el-input v-model="form.loginName" :disabled="dis" type="text" placeholder="请输入登录名" />
                        </el-form-item>
                        <el-form-item label="默认密码:" class="top" prop="password" v-if="passwordflag">
                            <el-input v-model="form.password" disabled placeholder="请输入密码" />
                        </el-form-item>
                        <el-form-item label="权限类型:" class="top" prop="deptIndex">
                            <el-select
                                style="width: 100%"
                                v-model="form.type"
                                @change="changeValue"
                                disabled
                                placeholder="请选择权限类型"
                            >
                                <el-option
                                    v-for="item in UserTypeOption"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.index"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="用户类型:" class="top" prop="casualUser">
                            <el-select style="width: 100%" v-model="form.casualUser" placeholder="请选择用户类型">
                                <el-option
                                    v-for="item in Typeoptions2"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.index"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                        <!--            <el-form-item v-if="form.type == 2" class="top"  label="所属部门:">-->
                        <el-form-item class="top" label="所属部门:" prop="deptId">
                            <!-- <el-tree :data="datatree" :props="defaultProps" @node-click="handleNodeClick" style="height:100px;overflow-y: auto;"></el-tree> -->
                            <el-select
                                style="width: 100%"
                                v-model="form.deptName"
                                placeholder="请选择所属部门"
                                ref="fghd"
                            >
                                <el-option :value="deptId" style="height: auto">
                                    <el-tree
                                        ref="tree"
                                        :data="deptOptions"
                                        node-key="id"
                                        accordion
                                        :default-expanded-keys="idArr2"
                                        :props="defaultProps4"
                                        @node-click="handNodeClick"
                                        style="width: 250px; height: 15vh; overflow: auto"
                                    >
                                        <span class="span-ellipsis" slot-scope="{ node, data }">
                                            <span :title="data.name">{{ data.name }}</span>
                                        </span>
                                    </el-tree>
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="角色:" class="top" prop="role">
                            <el-select
                                style="width: 100%"
                                v-model="form.role"
                                multiple
                                collapse-tags
                                placeholder="请选择角色"
                            >
                                <el-option
                                    v-for="item in roleOptions"
                                    :label="item.label"
                                    :key="item.value"
                                    :value="item.value"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="用户ID:" class="top" style="" prop="">
                            <el-radio-group v-model="radio1" size="mini" :disabled="dialog.title == '修改用户'">
                                <el-radio-button label="关闭"></el-radio-button>
                                <el-radio-button label="开启"></el-radio-button>
                            </el-radio-group>
                            <el-input
                                v-model="form.id"
                                :disabled="dialog.title == '修改用户'"
                                placeholder="请输入用户id"
                                v-show="radio1 == '开启'"
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- <el-form-item label="确认密码" prop="password1"  v-if="dialog.title==='新增用户'?status1:''">
              <el-input v-model="form.password1" placeholder="请再次输入密码"/>
            </el-form-item> -->
                        <el-form-item label="手机号:" prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入手机号" />
                        </el-form-item>
                        <el-form-item label="邮箱:" class="top" prop="email">
                            <el-input v-model="form.email" placeholder="请输入邮箱" />
                        </el-form-item>
                        <el-form-item label="起始IP:" class="top" prop="limitIpStart">
                            <el-input v-model="form.limitIpStart" placeholder="请输入起始ip" />
                        </el-form-item>
                        <el-form-item label="结束IP:" class="top" prop="limitIpEnd">
                            <el-input v-model="form.limitIpEnd" placeholder="请输入结束ip" />
                        </el-form-item>
                        <el-form-item label="时间段:" class="top" prop="limitTime">
                            <el-select v-model="Time1" placeholder="请选择" style="width: 99px">
                                <el-option
                                    v-for="item in time"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.index"
                                />
                            </el-select>
                            -
                            <el-select v-model="Time2" placeholder="请选择" style="width: 99px">
                                <el-option
                                    v-for="item in time"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.index"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="短信通知:" class="top" prop="smsNotice">
                            <el-select style="width: 100%" v-model="form.smsNotice" placeholder="请选择">
                                <el-option
                                    v-for="item in noticeOptions"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.index"
                                />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="邮件通知:" class="top" prop="emailNotice">
                            <el-select v-model="form.emailNotice" placeholder="请选择" style="width: 100%">
                                <el-option
                                    v-for="item in enoticeOptions"
                                    :label="item.label"
                                    :value="item.value"
                                    :key="item.index"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button text-align="center" @click="closeDialog">取 消</el-button>
                <el-button text-align="center" type="primary" @click="handleSubmit">提交</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import { getheight } from '@/assets/commjs/common'
import {
    add,
    list,
    getById,
    deleteById,
    dept,
    edit,
    detptree,
    rolelist,
    selecRoleDetail,
    passwordConfirm,
    deluser,
    updatePassword,
    activateUser,
    exportUser,
    exportUserExcel
} from '@/api/admin/user'
import { gongkey, userfunction } from '@/api/user'

import { sm3Digest } from '@/assets/commjs/sm3'
import { sm2, encrypt } from '@/assets/commjs/sm2.js'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
    name: 'uesrmanagement',
    computed: {
        // 实时监听表格
        tables: function () {
            const search = this.search
            if (search) {
                return this.pageList.filter(dataNews => {
                    return Object.keys(dataNews).some(key => {
                        return String(dataNews[key]).toLowerCase().indexOf(search) > -1
                    })
                })
            }
            return this.pageList
        }
        // time:function(){
        //     const timedun = this.Time1+'-'+this.Time2
        //     return  timedun
        // }
    },
    components: { TreeSelect },
    filters: {
        formatDate: function (value) {
            //这里的 value 就是需要过滤的数据
            var date = new Date(value)
            var year = date.getFullYear()
            var month = date.getMonth() + 1
            var day = date.getDate()
            var hours = date.getHours()
            var minutes = date.getMinutes()
            var seconds = date.getSeconds()
            return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
        }
    },
    watch: {
        deep: true,
        'queryParams.searchState': {
            handler(newVal, oldVal) {
                // debugger
                this.page.current = 1
            }
        },
        'queryParams.casualUser': {
            // this.flag = true
            handler(newVal, oldVal) {
                // debugger
                this.page.current = 1
            }
        }
    },
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入密码'))
            } else {
                if (this.passwordform.confirmPwd !== '') {
                    this.$refs.passwordform.validateField('confirmPwd')
                }
                callback()
            }
        }
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'))
            } else if (value !== this.passwordform.newPwd) {
                callback(new Error('两次输入密码不一致!'))
            } else {
                callback()
            }
        }
        return {
            formInline: {},
            button: {
                add: false,
                edit: false,
                delete: false
            },
            dialogVisible1: false,
            dialogvisibleadd: false,
            dialogVisible3: false,
            search: '',
            deptId: '',
            idArr2: [],
            roleOptions: [
                { value: 0, label: '超级管理员' },
                { value: 1, label: '管理员1' },
                { value: 2, label: '测试员' }
            ],
            UserTypeOption: [
                { label: '管理员', value: 1 },
                { label: '普通用户', value: 2 }
            ],
            datatree: [],
            defaultProps4: {
                children: 'children',
                label: 'name'
            },
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            Time1: 0,
            Time2: 23,
            // 遮罩层
            loading: true,
            // 部门树选项
            deptOptions: [],
            // 选中数组
            ids: [],
            id: undefined,
            formPw: {
                password: undefined
            },
            queryParams: {
                casualUser: -1,
                searchState: 1,
                orderBy: '',
                searchBeginTime: '',
                searchEndTime: '',
                searchValue: '',
                sortBy: ''
            },
            page: {
                current: 1,
                size: 20,
                total: undefined
            },
            pageList: [],
            dialog: {
                title: '',
                visible: false
            },
            dialog1: {
                visible: false
            },
            passwordform: {
                password: '',
                newPwd: '',
                confirmPwd: ''
            },
            status1: true,
            status: true,
            passwordflag: true,
            password: '',
            password3: '',
            pd: undefined,
            dept: [],
            Statusoptions: [
                { label: '全部', value: -1 },
                { label: '注销', value: 0 },
                { label: '正常', value: 1 },
                { label: '锁定', value: 2 },
                { label: '待审核', value: 3 },
                { label: '休眠', value: 4 },
                { label: '密码过期', value: 5 }
            ],
            Typeoptions: [
                { label: '全部', value: -1 },
                { label: '临时用户', value: 0 },
                { label: '长期用户', value: 1 }
            ],
            Typeoptions2: [
                { label: '临时用户', value: 0 },
                { label: '长期用户', value: 1 }
            ],
            noticeOptions: [
                { label: '是', value: 1 },
                { label: '否', value: 0 }
            ],
            enoticeOptions: [
                { label: '是', value: 1 },
                { label: '否', value: 0 }
            ],
            time: [
                { label: '0', value: 0 },
                { label: '1', value: 1 },
                { label: '2', value: 2 },
                { label: '3', value: 3 },
                { label: '4', value: 4 },
                { label: '5', value: 5 },
                { label: '6', value: 6 },
                { label: '7', value: 7 },
                { label: '8', value: 8 },
                { label: '9', value: 9 },
                { label: '10', value: 10 },
                { label: '11', value: 11 },
                { label: '12', value: 12 },
                { label: '13', value: 13 },
                { label: '14', value: 14 },
                { label: '15', value: 15 },
                { label: '16', value: 16 },
                { label: '17', value: 17 },
                { label: '18', value: 18 },
                { label: '19', value: 19 },
                { label: '20', value: 20 },
                { label: '21', value: 21 },
                { label: '22', value: 22 },
                { label: '23', value: 23 },
                { label: '24', value: 24 }
            ],
            dis: false,
            t: undefined,
            // 表单参数
            form: {
                id: '',
                name: '测试员',
                password: '123456',
                email: '12@qq.com',
                limitIpStart: '192.168.2.101',
                deptId: '',
                deptName: '',
                casualUser: 1,
                loginName: 'testwa',
                //password1:'0001nj',
                phone: '13922217869',
                limitIpEnd: '192.168.2.102',
                limitTime: this.Time1 + '-' + this.Time2,
                role: [],
                smsNotice: 0,
                emailNotice: 0,
                type: undefined
            },
            radio1: '关闭',
            usertype: undefined,
            tableheight: undefined,
            // 表单校验
            rules: {
                name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
                role: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
                password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
                password1: [{ required: true, message: '确认密码不能为空', trigger: 'blur' }],
                loginName: [{ required: true, message: '登录名不能为空', trigger: 'blur' }],
                deptId: [{ required: true, message: '归属部门不能为空', trigger: 'blur' }],
                casualUser: [{ required: true, message: '用户类型不能为空', trigger: 'blur' }],
                smsNotice: [{ required: true, message: '短信通知不能为空', trigger: 'blur' }],
                emailNotice: [{ required: true, message: '邮件通知不能为空', trigger: 'blur' }],
                email: [
                    { required: false, message: '邮箱不能为空', trigger: 'blur' },
                    {
                        type: 'email',
                        message: "'请输入正确的邮箱地址",
                        trigger: ['blur', 'change']
                    }
                ],
                phone: [
                    { required: false, message: '手机号不能为空', trigger: 'blur' },
                    {
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: '请输入正确的手机号码',
                        trigger: 'blur'
                    }
                ],
                limitTime: [{ required: true, message: '时间段不能为空', trigger: 'blur' }],
                limitIpStart: [
                    { required: true, message: '起始IP不能为空', trigger: 'blur' },
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            let regexp =
                                /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
                            let isCorrect = regexp.test(value)
                            if (value == '') {
                                return callback(new Error('请输入IP地址'))
                            } else if (!isCorrect) {
                                callback(new Error('请输入正确的IP地址'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                limitIpEnd: [
                    { required: true, message: '结束IP不能为空', trigger: 'blur' },
                    {
                        required: true,
                        validator: (rule, value, callback) => {
                            let regexp =
                                /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
                            let isCorrect = regexp.test(value)
                            if (value == '') {
                                return callback(new Error('请输入IP地址'))
                            } else if (!isCorrect) {
                                callback(new Error('请输入正确的IP地址'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }
                ]
            },
            rules2: {
                password: [
                    { required: true, message: '请输入校验密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur'
                    },
                    { validator: validatePass, trigger: 'blur' }
                ],
                newPwd: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur'
                    },
                    { validator: validatePass, trigger: 'blur' }
                ],
                confirmPwd: [
                    { required: true, message: '请确认密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur'
                    },
                    { validator: validatePass2, trigger: 'blur', required: true }
                ]
            },
            rules3: {
                password: [
                    { required: true, message: '请输入二次校验密码', trigger: 'blur' },
                    {
                        min: 6,
                        max: 16,
                        message: '长度在 6 到 16 个字符',
                        trigger: 'blur'
                    },
                    { validator: validatePass, trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        this.loadData()
    },
    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.usertype = window.sessionStorage.getItem('type')
        if (this.usertype == 0) {
            this.form.type = 1
        }
        if (this.usertype == 1) {
            this.form.type = 2
        }
        this.userTreeData()
        this.deptTree()
        this.queryRole2()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.tableheight = window.sessionStorage.getItem('appheight') - 95
        },
        sort_change({ column }) {
            var sort = column.order
            var sortName = column.label
            //  if (column.label == '新增企微数') {
            //  }
            // console.log(sort, '排序方式'); // ascending 升序、descending 降序、 null 默认排序
            // console.log(sortName, 'sortName');//当前表头名称
        },
        //  resetForm() {

        //     if (this.$refs["form"]) {
        //       this.$refs["form"].resetFields();
        //     }
        //   },
        closeDialog() {
            this.dialogvisibleadd = false
            this.resetForm()
        },

        userTreeData() {
            userfunction().then(res => {
                var data = res.data
                data.forEach(m => {
                    if (m.routePath == '/system') {
                        m.children.forEach(n => {
                            n.children.forEach(d => {
                                if (d.routePath == '/user-boot/user/list') {
                                    d.children.forEach(f => {
                                        if (f.code == 'add' || f.code == 'edit' || f.code == 'delete') {
                                            this.button.add = true
                                            this.button.edit = true
                                            this.button.delete = true
                                        }
                                    })
                                }
                            })
                        })
                    }
                })
            })
        },
        //点击获取字典类型表头字段等属性
        sort(column, event) {
            //console.log(column)
            this.queryParams.orderBy = column.order
            this.queryParams.sortBy = column.property
            // console.log(
            //   this.queryParams.orderBy + "=============" + this.queryParams.sortBy
            // );
            this.handleQuery()
        },
        changeValue(value) {
            this.form.type = value
            this.queryRole2()
        },
        gName(row, column) {
            var gNamelist = []
            for (var i = 0; i < row.role.length; i++) {
                gNamelist.push(row.role[i])
            }
            return gNamelist.join()
        },
        handNodeClick(data, node, nodeData) {
            //alert(data)
            console.log(data, node)
            this.deptId = data
            this.form.deptName = data.name
            this.form.deptId = data.id
            this.$refs.fghd.blur()
        },
        loadData() {
            this.handleQuery()
        },
        deptlist() {
            dept().then(response => {
                const { data } = response
                for (var i = 0; i < data.length; i++) {
                    let arr = {
                        label: data[i].deptsName,
                        value: data[i].deptsIndex
                    }
                    this.dept.push(arr)
                }
            })
        },
        deptTree() {
            detptree().then(response => {
                this.deptOptions = response.data
                this.deptOptions.forEach(m => {
                    this.idArr2.push(m.id)
                })
            })
        },
        queryRole() {
            var p = {
                orderBy: '',
                pageNum: 0,
                pageSize: 0,
                searchBeginTime: '',
                searchEndTime: '',
                searchState: 0,
                searchValue: '',
                sortBy: ''
            }
            rolelist(p).then(response => {
                const { data } = response
                var data1 = data.records
                var arr = []
                for (var i = 0; i < data1.length; i++) {
                    let p = {
                        label: data1[i].name,
                        value: data1[i].id
                    }
                    arr.push(p)
                }
                this.roleOptions = arr
            })
        },
        queryRole2() {
            this.usertype = window.sessionStorage.getItem('type')

            if (this.usertype == 0) {
                var p = { id: this.usertype }
            }
            if (this.usertype == 1) {
                var p = { id: this.usertype }
            }
            selecRoleDetail(p).then(response => {
                const { data } = response
                var data1 = data
                var arr = []
                for (var i = 0; i < data1.length; i++) {
                    let p = {
                        label: data1[i].name,
                        value: data1[i].id
                    }
                    arr.push(p)
                }
                this.roleOptions = arr
            })
        },
        gkeyadd() {
            gongkey({ loginName: window.sessionStorage.cnloginname }).then(response => {
                if (response.code === 'A0000') {
                    var publicKey = response.data
                    console.log('获取公钥后赋值' + publicKey)
                    var sm3Pwd = sm3Digest(this.form.password) //SM3加密
                    var jiamipassword = ''
                    jiamipassword = sm2(sm3Pwd + '|' + this.form.password, publicKey, 0) //SM2公钥加密
                    this.password = jiamipassword
                    console.log('密码加密后:' + jiamipassword)
                    let p = {
                        name: this.form.name,
                        //password':this.password,
                        email: this.form.email,
                        limitIpStart: this.form.limitIpStart,
                        deptId: this.form.deptId,
                        casualUser: this.form.casualUser,
                        loginName: this.form.loginName,
                        phone: this.form.phone,
                        limitIpEnd: this.form.limitIpEnd,
                        limitTime: this.Time1 + '-' + this.Time2,
                        role: this.form.role,
                        smsNotice: this.form.smsNotice,
                        emailNotice: this.form.emailNotice,
                        type: this.form.type,
                        id: this.form.id
                    }
                    // console.log(p);
                    add(p).then(response => {
                        if (response.code === 'A0000') {
                            this.$message.success('新增成功')
                            this.dialogvisibleadd = false
                            this.handleQuery()
                        }
                    })
                }
            })
        },
        //用户列表查询
        handleQuery() {
            this.queryParams.pageNum = this.page.current
            this.queryParams.pageSize = this.page.size
            list(this.queryParams).then(response => {
                if (response.code === 'A0000') {
                    const { data } = response
                    this.pageList = data.records
                    this.page.total = data.total
                    this.page.size = data.size
                    this.loading = false
                }
                if (response.code === 'A0110') {
                    this.$message.success('暂无用户')
                    const { data, total } = response
                    this.pageList = []
                    // this.pagination.total = ''
                    this.loading = false
                }
            })
        },
        closepw() {
            this.$refs.passwordform.resetFields()
            this.dialogVisible1 = false
            this.dialogVisible3 = false
        },
        //更换条数
        handleSizeChange(val) {
            this.page.size = val
            this.handleQuery()
        },
        //更换页数
        handleCurrentChange(val) {
            this.page.current = val
            this.handleQuery()
        },
        handleUnlock(row) {
            var arr = {
                id: row.id
            }
            activateUser(arr).then(response => {
                if (response.code === 'A0000') {
                    this.$message({ message: response.message, type: 'success' })
                }
                this.handleQuery()
            })
        },
        //导出文件
        exportExcel() {
            exportUser(this.queryParams).then(res => {
                if (res.code == 'A0000') {
                    let fileName = res.data.substring(res.data.lastIndexOf('/') + 1, res.data.length) //获取文件名
                    let path = encodeURIComponent(res.data)
                    this.getpath(path, fileName)
                }
            })
        },
        getpath(path, fileName) {
            exportUserExcel(path).then(res => {
                let blob = new Blob([res], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                }) //response是返回的数据对象
                let downloadElement = document.createElement('a')
                let href = window.URL.createObjectURL(blob) //创建下载的链接
                downloadElement.href = href
                downloadElement.setAttribute('download', fileName)
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放掉blob对象
            })
        },
        handleAdd() {
            this.usertype = window.sessionStorage.getItem('type')
            if (this.usertype === '0') {
                //this.resetForm()
                this.dis = false
                this.t = 'add'
                this.form = {
                    name: '',
                    password: '123456',
                    email: '',
                    limitIpStart: '0.0.0.0',
                    deptId: '',
                    casualUser: 1,
                    loginName: '',
                    phone: '',
                    limitIpEnd: '255.255.255.255',
                    limitTime: this.Time1 + '-' + this.Time2,
                    role: [],
                    smsNotice: 0,
                    emailNotice: 0,
                    type: 1,
                    id: ''
                }
                this.dialog = {
                    title: '新增用户',
                    visible: true
                }
                this.dialogvisibleadd = true
                this.passwordflag = true
            }
            if (this.usertype === '1') {
                //this.resetForm()
                this.dis = false
                this.t = 'add'
                this.form = {
                    name: '',
                    password: '123456',
                    email: '',
                    limitIpStart: '0.0.0.0',
                    deptId: '',
                    casualUser: 1,
                    loginName: '',
                    phone: '',
                    limitIpEnd: '255.255.255.255',
                    limitTime: this.Time1 + '-' + this.Time2,
                    role: [],
                    smsNotice: 0,
                    emailNotice: 0,
                    type: 2,
                    id: ''
                }
                this.dialog = {
                    title: '新增用户',
                    visible: true
                }
                this.dialogvisibleadd = true
                this.passwordflag = true
            }
        },

        depttree(deptId, data) {
            //遍历树  获取id数组
            for (var i = 0; i < data.length; i++) {
                if (data[i].id === deptId) {
                    this.form.deptName = data[i].name
                }
                if (data[i].children) {
                    this.depttree(deptId, data[i].children)
                }
            }
            // return data
        },

        handleUpdate(row) {
          
            this.$prompt('', '密码二次校验', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                inputPattern: /^.{6,16}$/,
                inputType: 'password',
                closeOnClickModal: false,
                inputErrorMessage: '长度在 6 到 16 个字符',
                beforeClose: (action, instance, done) => {
                    if (action === 'confirm') {
                    gongkey({ loginName: window.sessionStorage.cnloginname }).then(response => {
                        if (response.code === 'A0000') {
                            var publicKey = response.data
                            // console.log("获取公钥后赋值" + publicKey);
                            var sm3Pwd = sm3Digest(instance.inputValue) //SM3加密
                            var jiamipassword = ''
                            jiamipassword = sm2(sm3Pwd + '|' + instance.inputValue, publicKey, 0) //SM2公钥加密

                            passwordConfirm(jiamipassword).then(response => {
                                if (response.code === 'A0000') {
                                    done()
                                    console.log(row)
                                    this.dis = true
                                    var one = row.limitTime.split('-')
                                    this.Time1 = one[0]
                                    this.Time2 = one[1]
                                    //console.log(one);
                                    //this.resetForm()
                                    // this.dialog1={
                                    //   visible: true,
                                    // }
                                    this.dialog = {
                                        title: '修改用户',
                                        // visible: true,
                                        flag: 1
                                    }
                                    this.radio1 = '关闭'
                                    this.dialogvisibleadd = true
                                    this.t = 'edit'
                                    this.passwordflag = false
                                    this.form = {
                                        id: row.id,
                                        name: row.name,
                                        email: row.email,
                                        limitIpStart: row.limitIpStart,
                                        deptName: row.deptName,
                                        deptId: row.deptId,
                                        casualUser: row.casualUser,
                                        loginName: row.loginName,
                                        phone: row.phone,
                                        limitIpEnd: row.limitIpEnd,
                                        limitTime: this.Time1 + '-' + this.Time2,
                                        role: row.roleList,
                                        roleList: row.roleList,
                                        smsNotice: row.smsNotice,
                                        emailNotice: row.emailNotice,
                                        type: row.type
                                    }
                                } else {
                                }
                            })
                        }
                    })
                           
                           
                    } else {
                        done()
                    }
                }
            })
                // .then(({ value }) => {
                 
                // })
                // .catch(() => {})
        },
        handleSubmit() {
            if (this.t == 'add') {
                //新增
                this.gkeyadd()
            }
            if (this.t == 'edit') {
                let p = {
                    id: this.form.id,
                    name: this.form.name,
                    email: this.form.email,
                    limitIpStart: this.form.limitIpStart,
                    deptId: this.form.deptId,
                    casualUser: this.form.casualUser,
                    loginName: this.form.loginName,
                    phone: this.form.phone,
                    limitIpEnd: this.form.limitIpEnd,
                    limitTime: this.Time1 + '-' + this.Time2,
                    role: this.form.role,
                    smsNotice: this.form.smsNotice,
                    emailNotice: this.form.emailNotice,
                    type: this.form.type
                }
                edit(p).then(response => {
                    if (response.code === 'A0000') {
                        this.$message.success('修改成功')
                        this.dialogvisibleadd = false
                        this.handleQuery()
                    }
                })
            }
        },
        handleDelete(row) {
            this.dialogVisible3 = true
            this.passwordform.password = ''
            this.id = row.id
            this.pd = 'del'
        },
        gonKey() {
            gongkey({ loginName: window.sessionStorage.cnloginname }).then(response => {
                if (response.code === 'A0000') {
                    var publicKey = response.data
                    // console.log("获取公钥后赋值" + publicKey);
                    var sm3Pwd = sm3Digest(this.passwordform.password) //SM3加密
                    var jiamipassword = ''
                    jiamipassword = sm2(sm3Pwd + '|' + this.passwordform.password, publicKey, 0) //SM2公钥加密
                    this.password3 = jiamipassword
                    // console.log("密码加密后hhhhh:" + jiamipassword);
                    // console.log("测试" + this.password3);
                    if (this.pd == 'del') {
                        var password = this.password3
                        this.dialogVisible3 = false
                        passwordConfirm(password).then(response => {
                            if (response.code === 'A0000') {
                                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                                    confirmButtonText: '删除',
                                    cancelButtonText: '取消',
                                    type: 'warning'
                                })
                                    .then(() => {
                                        let data = {
                                            id: this.id
                                        }
                                        deluser(data).then(response => {
                                            this.$message({ type: 'success', message: '删除成功' })
                                        })
                                        this.handleQuery()
                                    })
                                    .catch(() => {
                                        this.$message({
                                            type: 'info',
                                            message: '已取消删除'
                                        })
                                    })
                            }
                        })
                    }
                    if (this.pd === 'pw') {
                        var password = this.password3
                        this.dialogVisible1 = false
                        passwordConfirm(password).then(response => {
                            if (response.code === 'A0000') {
                                // this.$prompt("请输入新密码", "提示", {
                                //   confirmButtonText: "确定",
                                //   cancelButtonText: "取消",
                                // })
                                //   .then(({ value }) => {
                                gongkey({ loginName: window.sessionStorage.cnloginname }).then(response => {
                                    if (response.code === 'A0000') {
                                        var publicKey = response.data
                                        //console.log("获取公钥后赋值" + publicKey);
                                        var sm3Pwd = sm3Digest(this.passwordform.newPwd) //SM3加密
                                        var jiamipassword = ''
                                        jiamipassword = sm2(sm3Pwd + '|' + this.passwordform.newPwd, publicKey, 0) //SM2公钥加密
                                        let data = {
                                            id: this.id,
                                            newPassword: jiamipassword
                                        }
                                        updatePassword(data).then(response => {
                                            if (response.code === 'A0000') {
                                                this.$message({
                                                    type: 'success',
                                                    message: '修改成功'
                                                })
                                            }
                                        })
                                    }
                                })
                                // })
                                // .catch(() => {
                                //   this.$message({
                                //     type: "info",
                                //     message: "取消输入",
                                //   });
                                // });
                            }
                        })
                    }
                }
            })
        },
        submint() {
            this.gonKey()
        },
        handleResetPassword(row) {
            this.passwordform.password = ''
            this.passwordform.newPwd = ''
            this.passwordform.confirmPwd = ''
            this.pd = 'pw'
            this.dialogVisible1 = true
            this.id = row.id
            //this.gongKey()
        },
        loadRoleOptions() {
            roleList({ queryMode: 'list' }).then(response => {
                this.roleOptions = response.data
            })
        },
        loadDeptOptions() {
            deptList({ queryMode: 'tree' }).then(response => {
                this.deptOptions = [
                    {
                        id: 0,
                        label: '灿能电力',
                        children: response.data
                    }
                ]
            })
        },
        // 表单重置
        resetForm() {
            this.form = {}
            if (this.$refs['form']) {
                this.$refs['form'].resetFields()
            }
        },
        handleReset() {
            this.queryParams = {
                casualUser: -1,
                searchState: 1,
                orderBy: '',
                searchBeginTime: '',
                searchEndTime: '',
                searchValue: '',
                sortBy: ''
            }
        }
    }
}
</script>
<style lang="less" scoped>
@import url('../../../../styles/comStyle.less');
</style>
<style lang="scss" scoped>
::v-deep .hjks .el-dialog .el-dialog__body {
    height: 51vh !important;
    padding: 20px 100px 20px 65px !important;
    overflow-y: auto;
}
</style>
