<template>
  <div class="app-container">
    <el-row :gutter="24">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="用户账号" prop="username">
            <el-input
              maxlength="20"
              v-model="queryParams.username"
              placeholder="请输入用户账号"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              maxlength="11"
              v-model="queryParams.phonenumber"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择用户状态"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:user:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              @click="handleUpdate"
              v-hasPermi="['system:user:edit']"
            >修改
            </el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--              type="danger"-->
<!--              plain-->
<!--              icon="el-icon-delete"-->
<!--              size="mini"-->
<!--              @click="handleDelete"-->
<!--              v-hasPermi="['system:user:remove']"-->
<!--            >删除-->
<!--            </el-button>-->
<!--          </el-col>-->
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleLogOff"
              v-hasPermi="['system:user:logoff']"
            >注销
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-unlock"
              size="mini"
              @click="handleRelock"
              v-hasPermi="['system:user:relock']"
            >解锁
            </el-button>
          </el-col>
        </el-row>
        <div style="padding-top: 10px">
          <vxe-table
            :row-style="setRowClass"
            ref="userTable"
            align="center"
            :loading="loading"
            class="mytable-style"
            auto-resize
            border
            resizable
            highlight-current-row
            show-overflow
            max-height="700"
            :radio-config="{trigger: 'row'}"
            :data="userList.slice((currentPage-1)*pageSize,currentPage*pageSize)"
          >
            <vxe-column type="radio" width="60"/>
            <vxe-table-column field="username" title="用户账号"/>
            <vxe-table-column field="nickname" title="用户姓名"/>
            <vxe-table-column field="idcard" title="身份证号码"/>
            <vxe-table-column field="mailbox" title="用户邮箱"/>
            <vxe-table-column field="phonenumber" title="手机号码"/>
            <vxe-table-column field="status" title="用户状态" :formatter="statusFormat"/>
            <vxe-table-column field="usertype" title="用户类型" :formatter="typeFormat"/>
            <vxe-table-column field="expDate" title="账号截止日期"/>
            <vxe-table-column title="操作" width="320">
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.id !== 1 && scope.row.id !== 2"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleResetPwd(scope.row)"
                  v-hasPermi="['system:user:send']"
                >初始/重置密码
                </el-button>
                <el-button
                  v-if="scope.row.id !== 1 && scope.row.id !== 2"
                  size="mini"
                  type="text"
                  icon="el-icon-circle-check"
                  @click="handleAuthRole(scope.row)"
                  v-hasPermi="['system:user:role']"
                >分配角色
                </el-button>
              </template>
            </vxe-table-column>
          </vxe-table>

          <vxe-pager
            v-show="showTable"
            perfect
            :current-page.sync="currentPage"
            :page-size.sync="pageSize"
            :total="total"
            :page-sizes="[10,50,100]"
            :layouts="['PrevJump', 'PrevPage','JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
          >
          </vxe-pager>
        </div>
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" width="730px" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号" prop="username">
              <el-input id="un" ref="un" style="width: 220px" v-model="form.username" placeholder="请输入用户账号"
                        maxlength="20" :disabled="edit"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="idcard">
              <el-input style="width: 220px" v-model="form.idcard" placeholder="请输入身份证号码" maxlength="18" :disabled="edit"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型">
              <el-select style="width: 220px" v-model="form.usertype" placeholder="请选择类型" :disabled="edit">
                <el-option
                  v-for="item in typeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickname">
              <el-input style="width: 220px" v-model="form.nickname" placeholder="请输入用户姓名" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="mailbox">
              <el-input style="width: 220px" v-model="form.mailbox" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input style="width: 220px" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="账号截止日期">
              <el-date-picker
                value-format="yyyy-MM-dd"
                v-model="form.expDate"
                type="date"
                placeholder="请选择账号截止日期"
                :picker-options="pickerOptions">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog :title="jstitle" :visible.sync="jsopen" width="650px" append-to-body>
      <el-form width="630px" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户账号">
              <el-input style="width: 220px" v-model="jsusername"
                        maxlength="20" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名">
              <el-input style="width: 220px" v-model="jsnickname" maxlength="30" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色类型" style="width: 100px">
              <el-select style="width: 220px" v-model="userRoleId" placeholder="请选择类型" :disabled="edit" @change="getMenu(userRoleId)">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            ref="menu"
            node-key="id"
            empty-text="无数据，请选择字符标识！"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>

        </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="jssubmitForm">确 定</el-button>
        <el-button @click="jscancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {debounce} from 'lodash'

export default {
  name: "User",
  data() {
    return {
      pickerOptions:{
        disabledDate(time){
          return time.getTime()<Date.now()-8.64e7
        }
      },
      id: undefined,
      username: undefined,
      nickname: undefined,
      idcard: undefined,
      phonenumber: undefined,
      mailbox: undefined,
      status: "0",
      usertype: "0",
      remark: undefined,
      expDate: undefined,
      // 角色表格数据
      jsuserid: '',
      roleList: [],
      jsusername: '',
      jsnickname: '',
      userRoleId: '',
      jsusertype: '',
      statusOptions: [
        {value: '0', label: '正常'},
        {value: '1', label: '锁定'},
        {value: '2', label: '注销'}
      ],
      typeOptions: [
        {value: '0', label: '管理员'},
        {value: '1', label: '业务用户'}
      ],
      // 遮罩层
      loading: true,
      showTable: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      currentPage: 1,
      pageSize: 10,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 角色分配弹出层标题
      jstitle: "",
      // 是否显示弹出层
      open: false,
      // 角色是否显示弹出层
      jsopen: false,
      // 默认密码
      initPassword: undefined,
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        username: undefined,
        phonenumber: undefined,
        status: undefined
      },
      menuExpand: false,
      // 菜单列表
      menuOptions: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      edit: false,
      // 表单校验
      rules: {
        username: [
          {required: true, message: "用户账号不能为空", trigger: "blur"},
          {min: 5, max: 20, message: '用户账号长度必须介于 5 和 20 之间', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户姓名长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        idcard: [
          {required: true, message: "身份证号码不能为空", trigger: "blur"},
          {min: 15, max: 18, message: '身份证号请输入15位或者18位', trigger: 'blur'}
        ],
        mailbox: [
          {required: true, message: "邮箱不能为空", trigger: "blur"},
          {type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"]}
        ],
        phonenumber: [
          {required: true, message: "手机号码不能为空", trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      }
    };
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menu') {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },

    setRowClass({row, rowIndex}){
      if(row.signstr === '1'){
        return "background: #FFEFD5";
      }
    },
    // 注销操作
    handleLogOff(){
      let _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      if (_selectData.id == 1) {
        this.$message({
          type: 'warning',
          message: '内置系统管理员用户不能注销!'
        });
        return
      }
      if (_selectData.id == 2) {
        this.$message({
          type: 'warning',
          message: '内置审计管理员用户不能注销!'
        });
        return
      }
      if (_selectData.status == 2) {
        this.$message({
          type: 'warning',
          message: '已注销的账号不能再次注销!'
        });
        return
      }
      if (_selectData.signstr == '1') {
        this.$message({
          type: 'warning',
          message: '存在待审核，审核管理员审核后请刷新列表'
        });
        return
      }
      this.$prompt('请输入登录密码', '鉴别操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'text',
        customClass:'no-autofill-pwd',
        inputValidator: (val) => {
          if (val === null || val.length < 1 || val.length > 20) {
            return false;
          }
        },
        inputErrorMessage: '不能为空,最多可录入20个字符',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(async ({value}) => {
        this.doLogoff(_selectData, value)
      }).catch((e) => {
      })
    },
    /**
     * 注销提交
     */
    doLogoff: debounce(async function (_selectData, againPwd) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        id: _selectData.id,
        againPwd: againPwd,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/logOffUser', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: res.data
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
        this.loading = false
      })
    }, 500),
    // 列表状态格式化
    statusFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.statusOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "正常"
        } else if (cellValue == "1") {
          belongTo = "锁定"
        } else if (cellValue == "2") {
          belongTo = "注销"
        }
      }
      return belongTo
    },
    // 列表状态格式化
    typeFormat({cellValue}) {
      let belongTo = '未知的类型'
      for (let i = 0; i < this.typeOptions.length; i++) {
        if (cellValue == "0") {
          belongTo = "管理员"
        } else if (cellValue == "1") {
          belongTo = "业务用户"
        }
      }
      return belongTo
    },
    /** 搜索按钮操作 */
    handleQuery: debounce(function () {
      this.currentPage = 1
      this.pageSize = 10
      this.getList()
    }, 1000),
    /** 查询用户列表 */
    async getList() {
      this.loading = true;
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
        this.loading = false;
      })

      var searchParams = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        username: this.queryParams.username,
        phonenumber: this.queryParams.phonenumber,
        status: this.queryParams.status,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.get('/sysUserController/getAll',
        {params: searchParams}).then((res) => {
        this.userList = res.data
        this.total = res.data.length

        if (res.data.records == '') {
          this.showTable = false
        } else {
          this.showTable = true
        }
        this.loading = false
      }).catch((error) => {
        this.loading = false;
        // this.$message.error(error)
      })
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
        return changeUserStatus(row.userId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.getList()
      this.open = false;
      this.reset();
    },
    // 角色取消按钮
    jscancel() {
      this.jsopen = false;
    },
    // 表单重置
    reset() {
      this.edit = false;
      this.form = {
        id: undefined,
        username: undefined,
        nickname: undefined,
        idcard: undefined,
        phonenumber: undefined,
        mailbox: undefined,
        status: "0",
        usertype: "0",
        remark: undefined,
        expDate: undefined
      };
      // this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.edit = false;
      this.open = true;
      this.title = "添加用户";
      this.form.password = this.initPassword;
    },
    /** 提交按钮 */
    submitForm: debounce(function () {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          if (this.form.id != undefined) {
            this.$prompt('请输入登录密码', '鉴别操作', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              inputType: 'text',
              customClass:'no-autofill-pwd',
              inputValidator: (val) => {
                if (val === null || val.length < 1 || val.length > 20) {
                  return false;
                }
              },
              inputErrorMessage: '不能为空,最多可录入20个字符',
              beforeClose(action, instance, done) {
                if (action === "confirm") {
                  instance.$refs["confirm"].$el.onclick = (function (e) {
                    e = e || window.event;
                    if (e.detail != 0) {
                      done();
                    }
                  })();
                } else {
                  done();
                }
              }
            }).then(async ({value}) => {
              let sysTime
              let lk
              await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
                sysTime = res.data.sysTime
                lk = res.data.lk
              }).catch((error) => {
              })
              this.form.sysTime = sysTime
              this.form.lk = lk
              this.form.againPwd = value

              // 更新操作
              await this.$axios.post('/sysUserController/updateUser', this.form).then((res) => {
                if (res.code == 0) {
                  this.$message.success(res.data)
                  this.open = false;
                  this.reset();
                  this.getList();
                }
                if (res.code == 1) {
                  this.$message.error(res.data)
                }
                this.loading = false
              }).catch((error) => {
                // this.$message.error(error)
                this.loading = false
              })
            }).catch((e) => {
            })
          } else {
            let sysTime
            let lk
            await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
              sysTime = res.data.sysTime
              lk = res.data.lk
            }).catch((error) => {
            })

            this.form.sysTime = sysTime
            this.form.lk = lk
            await this.$axios.post('/sysUserController/addUser', this.form).then((res) => {
              if (res.code == 0) {
                this.$message.success(res.data)
                this.open = false;
                this.reset();
                this.getList();
              }
              if (res.code == 1) {
                this.$message.error(res.data)
              }
              this.loading = false
            }).catch((error) => {
              // this.$message.error(error)
              this.loading = false
            })
          }
        }
      });
    }, 1000),
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      if (row.signstr == '1') {
        this.$message({
          type: 'warning',
          message: '存在待审核，审核管理员审核后请刷新列表'
        });
        return
      }
      if (row.status == '2') {
        this.$message({
          type: 'warning',
          message: '已注销的账号不能初始/重置密码!'
        });
        return
      }

      this.$prompt('请输入登录密码', '鉴别操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'text',
        customClass:'no-autofill-pwd',
        inputValidator: (val) => {
          if (val === null || val.length < 1 || val.length > 20) {
            return false;
          }
        },
        inputErrorMessage: '不能为空,最多可录入20个字符',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(async ({value}) => {
        this.doResetPwd(row, value)
      }).catch((e) => {
      })
    },
    doResetPwd: debounce(async function (row,againPwd) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        id: row.id,
        againPwd: againPwd,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/resetPassword', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '创建并发送成功!'
          });
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '创建密码失败!'
        });
        console.log(error)
        this.loading = false
      })
    }, 1000),

    /** 删除按钮操作 */
    handleDelete() {
      const _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      if (_selectData.id == 1) {
        this.$message({
          type: 'warning',
          message: '内置系统管理员不能删除!'
        });
        return
      }
      if (_selectData.id == 2) {
        this.$message({
          type: 'warning',
          message: '内置审计管理员不能删除!'
        });
        return
      }
      this.$prompt('请输入密码', '鉴别操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'text',
        customClass:'no-autofill-pwd',
        inputValidator: (val) => {
          if (val === null || val.length < 1 || val.length > 20) {
            return false;
          }
        },
        inputErrorMessage: '不能为空,最多可录入20个字符',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(async ({value}) => {
        this.doDelete(_selectData, value)
      }).catch((e) => {
      })
    },
    /**
     * 删除提交
     */
    doDelete: debounce(async function (_selectData, againPwd) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      const param = {
        id: _selectData.id,
        againPwd: againPwd,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/delUser', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: res.data
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '删除失败!'
        });
        this.loading = false
      })
    }, 500),
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      let _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      if (_selectData.id == 1) {
        this.$message({
          type: 'warning',
          message: '内置系统管理员不能修改!'
        });
        return
      }
      if (_selectData.id == 2) {
        this.$message({
          type: 'warning',
          message: '内置审计管理员不能修改!'
        });
        return
      }
      if (_selectData.status == 2) {
        this.$message({
          type: 'warning',
          message: '注销的账号不能操作!'
        });
        return
      }
      if (_selectData.signstr == '1') {
        this.$message({
          type: 'warning',
          message: '存在待审核，审核管理员审核后请刷新列表'
        });
        return
      }
      this.form = _selectData;
      this.open = true;
      this.title = "修改用户";
      this.edit = true;
    },
    /** 解锁按钮操作 */
    handleRelock() {
      const _selectData = this.$refs.userTable.getRadioRecord(true)
      if (_selectData == null) {
        this.$message({
          type: 'warning',
          message: '请选择记录!'
        });
        return
      }
      if (_selectData.status !== '1') {
        this.$message({
          type: 'warning',
          message: '只能对【锁定】状态的进行解锁!'
        });
        return
      }
      if (_selectData.signstr == '1') {
        this.$message({
          type: 'warning',
          message: '存在待审核，审核管理员审核后请刷新列表'
        });
        return
      }

      this.$prompt('请输入登录密码', '鉴别操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'text',
        customClass:'no-autofill-pwd',
        inputValidator: (val) => {
          if (val === null || val.length < 1 || val.length > 20) {
            return false;
          }
        },
        inputErrorMessage: '不能为空,最多可录入20个字符',
        beforeClose(action, instance, done) {
          if (action === "confirm") {
            instance.$refs["confirm"].$el.onclick = (function (e) {
              e = e || window.event;
              if (e.detail != 0) {
                done();
              }
            })();
          } else {
            done();
          }
        }
      }).then(async ({value}) => {
        this.doRelock(_selectData, value)
      }).catch((e) => {
      })


    },
    /**
     * 解锁提交
     */
    doRelock: debounce(async function (_selectData, againPwd) {
      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })
      const param = {
        id: _selectData.id,
        againPwd: againPwd,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/relockUser', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '解锁成功!'
          });
          this.getList();
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '解锁失败!'
        });
        console.log(error)
        this.loading = false
      })
    }, 1000),

    /**
     * 角色类型改变时更改权限列表
     * @param rowRoleId
     * @returns {Promise<unknown>}
     */
    getMenu(rowRoleId){
      console.log("rowRoleId="+rowRoleId)
      const a = this.$axios
      const _this = this
      return new Promise(async function (resolve, reject) {
        let sysTime
        let lk
        await a.get('/sysPolicyController/getLicenseKey').then((res) => {
          sysTime = res.data.sysTime
          lk = res.data.lk
        }).catch((error) => {
        })


        var param1 = {
          roleId: rowRoleId,
          sysTime: sysTime,
          lk: lk
        }

        await a.get('/sysMenuController/roleMenuTreeselect',
          {params: param1}).then((res) => {
          _this.menuOptions = res.data.menus;
        })
      }).catch((error) => {
        console.error('获取用户角色出错' + error)
      })
    },
    getUserRole(userid) {
      const a = this.$axios
      const _this = this
      return new Promise(async function (resolve, reject) {
        let sysTime
        let lk
        await a.get('/sysPolicyController/getLicenseKey').then((res) => {
          sysTime = res.data.sysTime
          lk = res.data.lk
        }).catch((error) => {
        })

        var userRoleParams = {
          userId: userid,
          sysTime: sysTime,
          lk: lk
        }
        await a.get('/sysUserController/getUserRole',
          {params: userRoleParams}).then(res => {

          _this.userRoleId = res.data.roleId

          // 返回userRole对象
          resolve(res.data)
        })

        let sysTime1
        let lk1
        await  a.get('/sysPolicyController/getLicenseKey').then((res) => {
          sysTime1 = res.data.sysTime
          lk1 = res.data.lk
        }).catch((error) => {
        })
        var param1 = {
          roleId: _this.userRoleId,
          sysTime: sysTime1,
          lk: lk1
        }

        await a.get('/sysMenuController/roleMenuTreeselect',
          {params: param1}).then((res) => {
          _this.menuOptions = res.data.menus;
        })
      }).catch((error) => {
        console.error('获取用户角色出错' + error)
      })
    },
    getRoleByType(usertype) {
      // 根据用户类型获取角色列表
      const a = this.$axios
      let _this = this
      return new Promise(async function (resolve, reject) {
        let sysTime
        let lk
        await a.get('/sysPolicyController/getLicenseKey').then((res) => {
          sysTime = res.data.sysTime
          lk = res.data.lk
        }).catch((error) => {
        })

        var searchParams = {
          usertype: usertype,
          sysTime: sysTime,
          lk: lk
        }
        await a.get('/sysRoleController/getRoleByType',
          {params: searchParams}).then(res => {
          if (res.code == 0) {
            // 返回角色列表
            _this.roleList = res.data
            resolve(res.data)
          } else {
            // 输出后端返回信息
            this.$message({
              type: 'error',
              message: res.data
            });
          }
        })
      }).catch((error) => {
        this.loading = false
        this.$message.error(error)
      })
    },
    /** 分配角色操作 */
    handleAuthRole: debounce(function (row) {
      if (row.id == 1) {
        this.$message({
          type: 'warning',
          message: '内置系统管理员不能修改!'
        });
        return
      }
      if (row.id == 2) {
        this.$message({
          type: 'warning',
          message: '内置审计管理员不能修改!'
        });
        return
      }
      if (row.status == '2') {
        this.$message({
          type: 'warning',
          message: '注销的账号不能操作!'
        });
        return
      }
      if (row.signstr == '1') {
        this.$message({
          type: 'warning',
          message: '存在待审核，审核管理员审核后请刷新列表'
        });
        return
      }

      this.jsuserid = row.id
      this.jsusername = row.username
      this.jsnickname = row.nickname

      this.getRoleByType(row.usertype)
      this.getUserRole(this.jsuserid)
      this.jsopen = true;
      this.title = "分配角色";
      // Promise.all([this.getRoleByType(row.usertype), this.getUserRole(this.jsuserid)]).then((res) => {
      //   if (res[1] != '' && res[1] != undefined) {
      //     const roleTable = this.$refs.xTable.getTableData()
      //     for (var i = 0; i < roleTable.tableData.length; i++) {
      //       if (res[1].roleId == roleTable.tableData[i].roleId) {
      //         // 将原有的角色勾选上
      //         this.$refs.xTable.setCheckboxRow(roleTable.tableData[i], true)
      //       }
      //     }
      //   }
      // }).catch(e => {
      //   this.loading = false
      //   this.$message.error("获取分配角色异常：" + e)
      // })
    }, 1000),


    /** 角色分配提交按钮 */
    jssubmitForm: debounce(async function () {

      let sysTime
      let lk
      await this.$axios.get('/sysPolicyController/getLicenseKey').then((res) => {
        sysTime = res.data.sysTime
        lk = res.data.lk
      }).catch((error) => {
      })

      // 提交后台角色分配
      const param = {
        userId: this.jsuserid,
        roleId: this.userRoleId,
        sysTime: sysTime,
        lk: lk
      }
      await this.$axios.post('/sysUserController/authRole', param).then((res) => {
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: res.data
          });
          this.jscancel()
          this.getList()
        } else {
          this.$message({
            type: 'error',
            message: res.data
          });
        }
      }).catch((error) => {
        this.$message({
          type: 'error',
          message: '角色分配失败!'
        });
        this.loading = false
      })
    }, 1000)
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
.no-autofill-pwd{
  .el-message-box__content{
    .el-input__inner{
      text-security:disc!important;
      -webkit-text-security:disc!important;
    }
  }
}
</style>
